Wednesday, October 26, 2011

Measure your site performance (HTTPModule)


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"  .


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.


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
      <add name="RequestInspector" type="RequestInspectorNamespace.RequestInspector,RequestInspectorAssembly"/>

You can download  Source Code 

Wednesday, September 28, 2011

Send email easily


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


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, "", "johnpass"))"", "", string.Empty, "Subject", "Text Body")

All the code can be dowloaded from here.


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

Friday, September 23, 2011

GetXml dataset method not good enough


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

        <personId >354</personId > 
        <personName >Jhon</personName 

But if you want to change it to

       <Person personId = 354 personName="Jhon" >

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.


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;
= new XmlTextWriter(new MemoryStream(), Encoding.UTF8);

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

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

if (isStatefull && dt.Rows.Count == 0)

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

//start enumerate in rows collection
foreach (DataRow dr in dt.Rows)
//start <Table> element
if (isStatefull)
.WriteAttributeString("stat", "0");
.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))
= tmpDate.ToString("yyyy-MM-ddTHH:mm:ss");
= dr[dc, DataRowVersion.Current].ToString();

= dr[dc, DataRowVersion.Current].ToString();


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


//end <NewDataSet> element

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

The code iterates over the tables and build XML accrodingly.


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

Yahoo Download Stock Data


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.


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)

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.


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.


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.AddLine(singleGraph.GraphPane, list, Action.Add, Color.Red, stockName);

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

Code can be downloaded from this location.


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

    Two XSLT transformation in javascript


    In order to execute XSLT transformation in IE two different javascript methods can be done.
    In this article I would like explain how to use each of the javascript method.


    So for a start I created XML and XSL that I will show transformation.

    XML Example
    <?xml version="1.0"?>
    <product href="">
          <name>Playfield Text</name>
          <price currency="usd">299</price>
          <description>Faster than the competition.</description>

    XSLT Example
    <?xml version="1.0"?>
    <xsl:stylesheet version="1.0" xmlns:xsl="">
    <xsl:output method="html" indent="no"/>
       <xsl:template match="/products">
              <tr class="header">
    <xsl:template match="product[position() mod 2 = 1]">
       <tr class="odd">
          <td><xsl:value-of select="name"/></td>
          <td><xsl:value-of select="price"/></td>
          <td><xsl:value-of select="description"/></td>
    <xsl:template match="product">
       <tr class="even">
          <td><xsl:value-of select="name"/></td>
          <td><xsl:value-of select="price"/></td>
          <td><xsl:value-of select="description"/></td>

    The first method.

    The first method that can trasform XSLT is to use "transformNode"
    method of Microsoft.XMLDOM object.

    Please see below the code

       var xml = new ActiveXObject("Microsoft.XMLDOM");
       var xslt = new ActiveXObject("Microsoft.XMLDOM");

       var output = xml.transformNode(xslt);

    The code is pretty simple. Need to define a two XMLDom object and invoke transform method.

    The second method.

    The second method is to use with XSLTemplate.

        var xml = new ActiveXObject("Microsoft.XMLDOM");
        var xslt = new ActiveXObject("MSXML2.FreeThreadedDOMDocument");
       var processor   = new ActiveXObject("Msxml2.XSLTemplate");
       processor.stylesheet = xslt;

       var objXSLTProc = processor.createProcessor();
       objXSLTProc.input = xml;
       var output  = objXSLTProc.output;

    The object is to load XSLT need to be created from FreeThreadedDOMDocument.
    The transformation is done by object created from Msxml2.XSLTemplate.
    Afterwords need to invoke transform method.


    We looked in two different approaches of XSLT transformatiion.
    On my next article, we will check which is the best solution.
    Please follow my next article to see the result.

    Sunday, September 11, 2011

    Remove mask from the Grid (ExtJS)

    I created a grid using ExtJs framework. When the grid was loading , the 'loading...'  text was displayed in
    the screen. The text was displayed by Extjs framework , and I needed to remove it. In order to do it,
    I debuged ExtJs framework and found out that the message was created by the
    LoadMask class. In order to remove the loading message need to define in the class config setup of the grid,  viewConfig section with the 'loadMask:false' option.
    viewConfig: {


    Friday, September 9, 2011

    Extjs S.gif

    I staretd to use Extjs library. It's really a great library with the strong features.
    ( .  I wrote first page , opened a fiddler to see the data between client and server.
    I found out that the Extjs is downloading image s.gif from the external server. I searched in the
    Net about this issue and found that need to download this image from sencha site to local server.
    The file can be downloaded  from  "". And then need to include at the beginning of the code 
    Ext.BLANK_IMAGE_URL='include/images/blank.gif'; This code will remove unwanted request to external server.

    Thursday, September 8, 2011

    Tooltip Class. Prototype

    One of my projects was developed on prototype java-script framework. I needed to write a functionality to show tool tip . I started to look in the prototype framework if they already have it.
    Unfortunately I did not find any component . I started to goggle it  and did not found anything as well.So I wrote my class that aimed to show tool tip . In constructor class receiving following parameters.

    elementOb -  The parent element to show tip
    tool_tip -  Tool tip message
    width - Tooltip width
    height - Tooltip height


    In order to setup a css class for the tool tip need to define a css style with the
    .toolTip className.

    To use it need to write the code below.

    var toolTipMessage = "The message is showing tooltip.Please change and play with it";
    var toolTip = new Tooltip($('tblToolTip'),toolTipMessage);
    I wrote sample page to test it .

    All the code can be downloaded from here Download

    See below sample picture

    Wednesday, September 7, 2011

    Parsing Typed XML

    I had a task to parse XML into Database.  I started to plan execution of the task. First of all XML has a constant structure. So the plan was to create the schema (XSD) of the XML and then produce from the schema collection of classes. Afterwards the XML can be de serialized .The schema creation in .Net can be done with the XSD tool. But the problem that I wanted that collection of classes 
    will support LINQ.  I was confident that someone already wrote framework that does it and I found it. Project called “Linq to XSD”.  (  The project creates  schema from the XML and produce classes from it.  The collection of classes can be queried in LINQ manner. That’s exactly what I was looking for!   The single problem that I had with it , was to installed it. Because the project in the Beta phase, need to work a litle. But after I finished
    that, it was really easy to use.  My tip for using the framework is to remove unnecessary functions,  that was created by the framework.  Functions that  you are not using simply holding the pointer in virtual table.