Monday, August 5, 2019

Amazing Leading Quality Book

Many developers start to create product without paying a proper attention to QA.
If you want to avoid this problem and in short period of time understand
wisdom about quality in today’s IT world, this book is for you.
An essential lesson in how to differentiate your product and business with quality

Look in Amazon Store and it's actually free

Wednesday, October 26, 2011

Measure your site performance (HTTPModule)

Preface

When creating a web site or web service , often you wonder how to measure request life cycle. May be you wonder if requested or web service ended at all. In order to do it we will look in feature that .Net framework expose to us, "HTTPModule"  .

HTTPModule

So what is HTTPModule ?  Picture for example water filter.  When water flowing from the crane , it's coming to some filter , filter doing some stuff with it ,and it's coming to your glass. The same mechanism is with the "HTTP" module . When you are requesting some page, you can write you own filter that will be invoked before beginning processing the page. And will pass page to parser that will process Asp. page.

Implementation

In order to implement filter we need to create a new class that will inherit from IHttpModule interface.
Than we need to implement Init function of the interface . Please see example


  public void Init(HttpApplication httpApplication)
        {
            
            // register for events created by the pipeline 
            httpApplication.BeginRequest += new EventHandler(this.OnBeginRequest);
            httpApplication.EndRequest += new EventHandler(this.OnEndRequest);
        }

When implementing the Init function we will subscribe to HTTPApplication events.
Like in the example below we subscribed to Begin and End  Request.

So when we will request specific page before process the page we will enter
to OnBeginRequest function . After the request ended  OnEndRequest function
will be called.

See all various events that we can subscribe to


  • AcquireRequestState:  event will be called to allow the module to acquire or create the state (for example, session) for the request.
  • AuthenticateRequest:  event will be called when a security module needs to authenticate the user before it processes the request.
  • AuthorizeRequest: event will be called  by a security module when the request needs to be authorized. Called after authentication.
  • BeginRequest: event will be called  to notify a module that new request is beginning.
  • Disposed: event will be called to notify the module that the application is ending for some reason. Allows the module to perform internal cleanup.
  • EndRequest: event will be called to notify the module that the request is ending.
  • Error: event will be called  to notify the module of an error that occurs during request processing.
  • PostRequestHandlerExecute: event will be called  to notify the module that the handler has finished processing the request.
  • PreRequestHandlerExecute: event will be called  to notify the module that the handler for the request is about to be called.
  • PreSendRequestContent: event will be called  to notify the module that content is about to be sent to the client.
  • PreSendRequestHeaders: Call this event to notify the module that the HTTP headers are about to be sent to the client.
  • ReleaseRequestState: Call this event to allow the module to release state because the handler has finished processing the request.
  • ResolveRequestCache: event will be called  after authentication. Caching modules use this event to determine if the request should be processed by its cache or if a handler should process the request.
  • UpdateRequestCache: event will be called  after a response from the handler. Caching modules should update their cache with the response.
In our example we subscribed only to Begin and End Request. See the event handler functions

 public void OnBeginRequest(object o, EventArgs args)
        {
            beginrequest = DateTime.Now;
            Trace.Write(string.Format("Request started at {0}", DateTime.Now));
        }
        public void OnEndRequest(object obj, EventArgs args)
        {
            // get the time elapsed for the request 
            TimeSpan elapsedtime = DateTime.Now - beginrequest;
            Trace.Write(string.Format("Request ended at {0}", DateTime.Now));
            Trace.Write(string.Format("Elapsed time {0}", elapsedtime));
        }

And final step , we need to declare about our model in web config . In order 
to declare need to add following row 
      <add name="RequestInspector" type="Namespace.Class,Assembly"/>

Please see example below
  <system.web>
    <httpModules>
      <add name="RequestInspector" type="RequestInspectorNamespace.RequestInspector,RequestInspectorAssembly"/>
    </httpModules>


You can download  Source Code 



Wednesday, September 28, 2011

Send email easily

Preface

Sending email in .Net it's not complicated thing . You can do it via config file or via code.
But we will create an email sender compoment that will encapsulate the process of sending email.
In future we will use this component in order to send a stock graph in program that we created

Implementation

Lets start our desing with the UML .




First we create base class  "SMTPBase". The class will implement IDisposable interface.
The interface will help to Garbage Collector to free resources that were allocated by this object.

The class will have a basic functionality to send emails. We will define properties such as :
  • From  - sender email
  • To  - recipient email 
  • Subject - email subject
  • SmtpHost  - smtp server host
  • Port - smtp port
  • Body - email text
  • Attachment - files that we want to attach to the email
 Of course we need to include validation if email valid or not. The most effective way  to do it
 is by regular expression.

Regex re = new Regex(@"\w.\w@{1,1}\w[.\w]?.\w");return re.IsMatch(email);

Email can be send using Gmail or Hotmail accout. We will define an Enum that will holds various account types and we will call it "SMTPHostType".


At the end we will create the service class that will send an email. Of course
the class will inherit from our base class. We will call it "SMTPSender".


The class will have several constructors


Constructor that receives host and port
public SMTPSender(string host, int port) : base(host, port) { }


Constuctor that will receive Host type Like Google or Hotmail
public SMTPSender(SMTPHostType smtpHost) : base(smtpHost ) { }




Here is a sample code that can be used in order to send an email.

using (SMTPSender smtpSender = new SMTPSender(SMTPHostType.HOTMAIL, "john@hotmail.com", "johnpass"))"john@gmail.com", "john@gmail.com", string.Empty, "Subject", "Text Body")

All the code can be dowloaded from here.

Summary

We created in this blog component that knows how to send emails using .Net .

Friday, September 23, 2011

GetXml dataset method not good enough

Preface

Dataset class has GetXml method. The method takes data and creates XML.The problem is that you cannot change  XML that created by function  For example  if you created SQL statement

Select PersonId,PersonName from Employee.

You will get following XML

<newdataset>
     <table1>
        <personId >354</personId > 
        <personName >Jhon</personName 
      </table1> 
</newdataset>

But if you want to change it to


<newdataset>
     <Persons>
       <Person personId = 354 personName="Jhon" >
      </Persons> 
</newdataset>

You cannot do it.

The other problem that can happen, that if SQL statement includes Left Outer Join, and one of the field
will be Null, the field will not be included in XML.

In order to solve these issus I created my "GetXml" function . You can customize your code any way you like.

Implementation

Basically I needed to implemented this function when I created statefull mechanism between client and server. So I needed to add in each row field "StateId" that will show the status of the row.

So here is the code 

private string GetXmlFromDataset(DataSet dataSet, bool isStatefull) {
   
XmlTextWriter xwriter = null;
   
try
   
{
        xwriter
= new XmlTextWriter(new MemoryStream(), Encoding.UTF8);
        xwriter
.WriteStartElement("NewDataSet");

       
//start enumerate in table collection
       
foreach (DataTable dt in dataSet .Tables )
       
{
           
int rowNum = 0;
           
DateTime tmp = DateTime.MinValue;

           
if (isStatefull)
                dt
.Columns.Add(new DataColumn("IsDummy", typeof(bool)));

           
if (isStatefull && dt.Rows.Count == 0)
           
{
                dt
.Rows.Add(dt.NewRow());

                dt
.Rows[0]["IsDummy"] = true;
           
}

           
//start enumerate in rows collection
           
foreach (DataRow dr in dt.Rows)
           
{
               
//start <Table> element
                xwriter
.WriteStartElement(dt.TableName);
               
if (isStatefull)
               
{
                    xwriter
.WriteAttributeString("stat", "0");
                    xwriter
.WriteAttributeString("rowNum", rowNum.ToString());
               
}
               
DateTime tmpDate = DateTime.MinValue  ;
               
//start enumerate in columns collection
               
foreach (DataColumn dc in dr.Table.Columns)
               
{
                   
string colValue = String.Empty;

                   
switch (dc.DataType.Name)
                   
{
                       
case "DateTime":
                           
if (DateTime.TryParse(dr[dc, DataRowVersion.Current].ToString(), out tmpDate))
                                colValue
= tmpDate.ToString("yyyy-MM-ddTHH:mm:ss");
                           
else
                                colValue
= dr[dc, DataRowVersion.Current].ToString();
                           
break;

                       
default:
                            colValue
= dr[dc, DataRowVersion.Current].ToString();
                           
break;

                   
}

                    xwriter
.WriteStartElement(dc.ColumnName.Replace(" ","_x0020_"));
                   
if ( isStatefull || String.Compare(dc.DataType.Name, "string", true) != 0)
                   
{
                        xwriter
.WriteAttributeString("datatype", dc.DataType.Name);
                   
}
                   
if (isStatefull)
                   
{
                        xwriter
.WriteAttributeString("stat", "0");
                   
}
                    xwriter
.WriteString(colValue);
                    xwriter
.WriteEndElement();
               
}
               
//end <Table> element
                xwriter
.WriteEndElement();

                rowNum
++;
           
}
       
}

       
//end <NewDataSet> element
        xwriter
.WriteEndElement();
        xwriter
.Flush();

        xwriter
.BaseStream.Seek(0, SeekOrigin.Begin);
       
StreamReader reader = new StreamReader(xwriter.BaseStream);
       
return reader.ReadToEnd();
   
}
   
finally
   
{
       
if (xwriter != null)
       
{
            xwriter
.Close();
            xwriter
= null;
       
}
   
}
 
} 

The code iterates over the tables and build XML accrodingly.

Summary

We learned in this post how to write custom "GetXml" function.

Yahoo Download Stock Data

Preface

Almost everyone knows that Yahoo has API to retrieve financial data.We will write a client that will
consume Yahoo API to retrieve history stock data. Let's start to develop set of classes
that will handle required functionality.

Implementation

First we define an Enum that holds different period types. The name of the class "PeriodType".
Yahoo stock data can be retrieved for various period types. It can be daily,monthly and etc..
Than we will define a class that holds information about single piece of data.
If we will request daily data , than class will holds single day, and if we request data by month
it will holds single month . The class name "Bar".

The main class that uses Yahoo API is class that named "YahooHistoryDownloader".
The class knows how to retrieve a stock data for different periods and different intervals.
The main function "GetBarHistory"  .
Input parameters:

  •    string stockName  - ticker name of the stock . "GOOG" for example.
  •    PeriodType periodType - enum that represent interval
  •    DateTime frDate - start date
  •    DateTime toDate -  from date


In order to test I created a console application that will print  the downloaded data to console.
The test function knows how to download data for the half year. 

  private static void GetDataFromStock(string stockName,PeriodType periodType)
        {
            YahooHistoryDownloader historyDown = new YahooHistoryDownloader();
            List<Bar> listBar = historyDown.GetBarHistory(stockName,periodType, DateTime.Now.AddMonths(-6), DateTime.Now);
            foreach (Bar bar in listBar)
                Console.WriteLine(bar);
        }


In order to use it
   string stockName = "GOOG";
   GetDataFromStock(stockName, PeriodType.Weekly );


Than you can collect the stock data and develop your  trading strategy

Here is UML



All the code can be downloaded from hereDownload

Please see how this component can be used to display stock graph in my next blog Click here !

Wednesday, September 21, 2011

See stock on your screen.

Preface

I think that if you intrested in stock trading , and you want to see the graph of you favorite stock,
you will like this blog for sure !


Please see the GUI of our next program.
We will build a program that will display a stock data. In the progran you will enter Ticker Name, From Date, End Date and the program display the data in a graph.We will use  Yahoo download component  that I posted in other blog.




Desing

As every good design we will start with UML


As we see in the picture we defined an Interface that called "ZedGraph" . Zedgraph expose common properties of our Graph object . Please see below several of them :
  • Description - A description of what this demo is showing.
  • Title - Graph Title
Than we will define base graph "BaseGraph" for all stock graphes. The class is abstract so no one can instance it. The class is implemented the interface that we created above so he must impement
properties that we defined in interface. The main public function of the class is "AddLine" . The function
know how to display the data in the graph.

In order to show the data we must created a class that will be inherited from the base.
So we will create class "SingleGraph". The graph will inherit from "BaseGraph" and the class will be responsible for charting.

In our window form class in order to show the graph we will implement following code

     YahooHistoryDownloader yahoo = new YahooHistoryDownloader();
            List<StockDownloader.Bar> list = yahoo.GetBarHistory(stockName, from, toDate);
            if (list.Count > 0)
            {
                singleGraph.ClearGraph();
                singleGraph.AddLine(singleGraph.GraphPane, list, Action.Add, Color.Red, stockName);
                singleGraph.ZedGraphControl.AxisChange();
                singleGraph.ZedGraphControl.Refresh();


Our task is complete I prepare for you code that you can play with it .


Code can be downloaded from this location.

Summary

We wanted to see the stock data and see how our stock do today.
So we created simple design how to do it and implement it as window form.
In my next blogs we will define stock with indicator, so it will be other graph type and
more intresting.

    Tuesday, September 13, 2011

    Compare two XSLT transformation

    In my previous blog I showed two methods for XSLT transformation. See for details Previous blog.
    Today I would like to compare run time of  two methods.
    Therefore  I created big xml with the same fields as I showed in my previous blog
    and XSL stays the same. I created method that uses "transformnode" approach and
    method that uses "processor" approach.

    Afterwords I created a method that will run 5  transformation at once and create a table
    with the results. I colored in red the method which run faster.


    As you see the process template is the quicker one. Please note that I did not measure CPU
    execution time only time that took to do XML transformation.

    You can play with the source and check yourself. All files can be downloaded from Download