Pages

Monday, December 17, 2012

System Development Life Cycles (SDLC)


The system development life cycle (SDLC) follows a project through from the initial idea to the point where it is a functional system. It is a core part of the methodology that is used when defining a project.
Life cycles fall into a number of different categories, iterative being the most common but they also include waterfall, spiral and chaos models. Common methodologies include Structured Systems Analysis and Design Method (SSADM) and Microsoft Solutions Framework (MSF).
Each step in a systems lifecycle can be broken down into many smaller sub-steps or processes. Each stage follows logically after the previous, but it is an oversimplification to say that one stage is a distinct step after another. It is important to understand that the system lifecycle is iterative as well as the stages involved along the way.
Different methodologies will have different variations of this lifecycle model. A common iterative lifecycle is show in the diagram below and each stage is described after the diagram.
System Development Life Cycle

Initial Idea

All projects must start with an initial idea. Usually this consists of a brief definition on what is the project all about, what is its purpose and what the project aims to accomplish. How will the success of the project be measured?

Feasibility Study

Expanding on the Initial Idea, the Feasibility Study involves drawing up the terms of reference, which state the objectives and scope of the project, how long it should take and how the results should be presented. The terms of reference are usually drawn up by senior management. The feasibility study must determine if development of the project is justified in terms of economic and organisational terms.
The main role of the analyst in the feasibility study is to analyse the current system at a high level. Data Flow Diagrams (DFD) are used to describe how the current system performs and to illustrate known problems.
Feasibility studies are not carried out for all projects, and smaller projects omit this stage.

Requirements Analysis

The Requirements Analysis stage defines a series of possible solutions to the problem and presents them to management in terms of business options. These options may be supported by technical documents such as high-level DFD’s, Logical Data Models (LDM) and Work Practise Models. The requirements analysis report must also contain financial and risk assessments to be presented and supported by outline implementation descriptions.
The steps involved within the requirements analysis will define the flow of data in the system, deriving system functions and to develop user role specifications, prototypes and process specifications.

Systems Analysis and Specification

The Systems Analysis stage is an extension to the feasibility study. If the project has a feasibility study then the bulk of the work has already been done. A terms of reference will also be required if one does not exist. The output from this stage is the System Specification which gives precise details of what the new system is required to do, but does not go into how it does it. It provides a logical model of the new system.
Once agreed, the specification is the basis for the work done by the system designers.

Systems Design

This stage deals with how the requirements of the new system are carried out (how the logical model is implemented as a physical system). The system designer will develop a number of design options and test them against the requirements specification and design criteria. The one that comes closest to the design brief with the most cost effective use of equipment and personnel is selected and broken down into more detailed specs.
Because of this the design stage has two phases: produce outline designs based on requirements specification with input from users and the detailed designs produced from the selected design.

Development

This is the only stage in the development where program code is written. The designs and specifications provide enough detail for the programmer to code and test individual modules. Each unit is tested to ensure that it meets the requirements of the specification.

Testing

Within the life cycle there are various levels of testing as well as the unit testing performed in the development stage.
Link testing ensures that programs work together, e.g. the data passed from one program to another has the correct format.
System testing ensures that the system as a whole performs according to the design specification. Recovery procedures must be tested as well as normal operation procedures.
Finally user acceptance testing is carried out by the users in stages to ensure that the system is usable.
Any modifications are passed back to the design stage where changes are made as necessary and passed to the development team.

Implementation

When the testing has been carried out to the users satisfaction the system, or parts of it, are put live. The “put live” phase can also be known as implementation, cut over or production. This is when the users start using the system to carry out their business activities.
There are two main approaches to implementation a project:
  • Phased: Stand-alone subsets of the system are implemented over a period of time.
  • Big Bang: The whole system is put live in one go.
Some systems will require special programs or tasks to convert existing data to a format usable by the new system. The process of changing data from the old system to the new is called conversion.

Maintenance and Review

Once the system is put into place, maintenance is required to ensure satisfactory operation.
Maintenance should include regular reviews and evaluations to ensure that it is achieving its objectives, identify any aspects that can be improved or any operational problems. Maintenance falls into two categories, implementation of new features or elimination of errors.

Wednesday, December 12, 2012

Redirecting User to Login Page After Session Timeouts


  In most of the applications you might come across the situation where you need to redirect the user to login page after session timeouts. It is simple, if you want to redirect user to login page when the user submits the page after session timeout. You got the control in server, you can check for session timeout. If that is true, then you can redirect the user to any page you want. If you implemented Authentication like Forms authentication or Passport authentication in your applications. Then this is done automatically when the user resubmits the page after session timeouts.
     But the requirement is such that you want to redirect the user immediately after timeout to login page before the user submits the page. In this article, I am going to explain how we can achieve this in ASP.NET.Before we see how to redirect the the user to login page after session timeout, we will see how to refresh any page after certain intervals. This will help me to clearly explain how to play with page redirection from client.  

Refreshing any page after certain interval

     For refreshing any page after certain interval, you need to use client side script only. You cant do this in server side, The reason being that the page has been served to the client, end of request.  The web is stateless; until the user comes back and initiates another request the server can't do anything. So we need to do this refreshing activity from client side only. There are two ways to achieve this,
                    1. Using Window.setTimeout method
                    2. Using Meta Tag - Refresh. 
Using Window.setTimeout method:
              DHTML Window object has a method called "setTimeout" which  evaluates an expression after a specified number of milliseconds has elapsed. With the help of this method, you can run the client side script window.location.href="somepage" to redirect page in the current window. SetTimeout accepts three parameters.
vCodeRequired. Variant that specifies the function pointer or string that indicates the code to be executed when the specified interval has elapsed.
iMilliSecondsRequired. Integer that specifies the number of milliseconds.
sLanguageOptional. String that specifies one of the following values:
JScriptLanguage is JScript.
VBScriptLanguage is VBScript.
JavaScriptLanguage is JavaScript.
             You need to call this method in body load and start the timer( by calling setTimeout method). This timer will elapse depending upon the second parameter for this method. When it is elapsed, it will fire the script which is given as first parameter. So you need to add this to the body element onload method. For adding client side event to body tag in asp.net you need to follow this methos.
1. Declare the body tag in html window as server control by specifing runat attribute and give an id to that tag.
                                <body runat="server" id= "body">< /P>< /FONT>
2. In the code behind, declare this element as htmlgenericcontrol like this.             
  Protected WithEvents body As System.Web.UI.HtmlControls.HtmlGenericControl   
3. Finally add the following code in your page_load event handler, this will add the client side handler for body tag.
 body.Attributes.Add("onLoad", "window.setTimeout(""window.location.href='<somepage>.aspx'"",5000);")    
This method will refresh the page to the specified location after 5 secs. The disadvantage of this method is, this might not work in some lower end browsers. So you need to go for other method i.e. by using Meta Tags.
Using Meta Tag - Refresh
    Another way for refreshing the page after certain interval is by using meta tag - Refresh. This tag specifies a delay in seconds before the browser automatically reloads the document. Optionally, specifies an alternative URL to load. Example
               <META HTTP-EQUIV="Refresh" CONTENT="3;URL=http://www.some.org/some.html">
In ASP.NET, you can add headers in code behind using this method.
             Response.AppendHeader("Refresh", "10; URL=.aspx")
This method will reload the current window after interval mentioned in the second parameter to the page which is mentioned as URL to refresh. In this case page will be refreshed after 10 seconds.

Redirecting User To Login Page after Session Timeouts.

Redirecting user to login page after session timeout is similar to refreshing the page after certain intervals method. Only thing which will differ is that calculating time after which the page has to be redirected. Hence time can be calculated using Session.timeout property which will give us session timeout value for that session. Add some grace timings to that value and redirect the user to the login page automatically.
Using Window.setTimeout method
body.Attributes.Add("onLoad", "window.setTimeout(""window.location.href='login.aspx'""," & (Session.Timeout * 60 * 1000) + 10000 & ");")
Using Meta Tag - Refresh
Response.AppendHeader("Refresh", Convert.ToString((Session.Timeout * 60) + 10) & "; URL=Login.aspx")
Both these methods will redirect the user to login page  after session timeout + 10 seconds. This is how you can redirect the user to login page after session timeout without user interaction.

State Management in ASP.NET


One of the frequently asked question in Newsgroups or Usergroups is regarding "State Management in ASP.NET". So here  i will give the short decription about various option for State management in ASP.NET and will give the links to various article which explains detaily about various options for state management in ASP.NET.

Session

     Is used for storing user specific data which needs to be persistant between requests for the same page/different pages in a request.

Httpcontext.Cache

     Is Used to store Application level STATIC data (which doesn't change frequently.)

Application 

     This is kind of kept for backward compatibility. I prefer using Cache to store Application level data since you have more flexibility with how you want to manage the cache. You can even set expiration for Cache object which is not possible using application.

ViewState 

       You can use this to store data between multiple requests to the same page.

HttpContext.Current.Items 

       You may use this to store data to be available per page level OR when you want to transfer data between pages using server.transfer (but this is not the suggested way to transfer data between pages.) the suggested way is to use page level public properties and access them from the destination page.
We have few other options like using cookies, using querystring and stroing in database also. Since there are lots of options availble you need to analyze use proper one which suits your application requirements

Related Links

Setting focus to an Textbox after Page Loads


In this code snippet, you will see how you can set the focus to an textbox either after the page loads for the first time or after postback. In asp.net there is no direct way for setting focus after post back, you need to use client side script only.  For example to set the focus for an textbox,
           document.forms[0].Textbox1.focus();
Note:This method uses the name property of the textbox. To use the id, you would use
          document.getElementById("Textbox1").focus();
For injecting client side script using code behind, you can either use registerstartupscript method or registerclientsidescript. In our case we need to use registerstartupscript, since we need to set the focus immediately after page loads. Registerstartupscript method will place the script just before form end tag. So this script will be executed after page loads. To set focus we need to write following code,
Page.RegisterStartupScript("SetFocus", "<script language=""Jscript"" > document.getElementById(""Textbox1"").focus(); </Script>")
This will set the focus to the textbox right after the page loads.

Adding Controls to the DataGrid Footer Item


In this article, I am going to explain how we can add controls like label,textbox and other controls to DataGrid Footer item. By two ways, you can add controls to datagrid item. One way is during desing mode itself, we can have footertemplate for adding controls. Other way is by adding controls dynamically to DataGrid footer. In this article, I am going to explain both these methods in detail.
For example, in the products datagrid we need to add one cell in which we need to show the total price of all the products. Best place to add this cell is at footer item. Here we are going to see how we can achieve this using two methods. Datagrid will like this with total column in footer item,

Adding controls during Design mode

Use the FooterTemplate property to control the appearance of the footer section in the TemplateColumn. The appearance is specified by creating a template that defines how the item is rendered in the column. To specify a template for the item selected for editing, first place opening and closing <FooterTemplate> tags between the opening and closing tags of the TemplateColumn element. You can then list the content that controls the appearance of the item between the opening and closing <FooterTemplate> tags. The content can be as simple as plain text, or more complex by embedding other controls in the template. As per our requirement, to add total column to datagrid footer we need to add one label control and one textbox as shown below using footertemplate property.
 <asp:datagrid id="DataGrid1" runat="server" width="500px" AllowPaging="False"
                          ItemStyle-CssClass="tableItem" HeaderStyle-CssClass="tableHeader"
                          HeaderStyle-BackColor="#aaaadd" AutoGenerateColumns="False" 
                          DataKeyField="ProductID" ShowFooter="True" BorderWidth="0">
  <Columns>
       <asp:TemplateColumn headertext="Product ID">
            <ItemTemplate>
                     <asp:TextBox style="width:100px;" id="ProductID" runat="server"
                                                                  Text='<%# Container.DataItem("ProductID") %>' >
                     </asp:TextBox>
            </ItemTemplate>
       </asp:TemplateColumn>
       <asp:TemplateColumn headertext="Product Name">
            <ItemTemplate>
                     <asp:TextBox style="width:200px;" id="ProductName" runat="server"           
                                                                 Text='<%# Container.DataItem("ProductName") %>' >
                    </asp:TextBox>
             </ItemTemplate>
       </asp:TemplateColumn>
       <asp:TemplateColumn headertext="Quantity" FooterStyle-HorizontalAlign=Right  >
              <ItemTemplate>
                    <asp:TextBox style="width:100px;" id="Quantity" runat="server"
                                                                   Text='<%# Container.DataItem("QuantityPerUnit") %>' >
                    </asp:TextBox>
               </ItemTemplate>
               <FooterTemplate >
                         <asp:Label Runat=server ID="Label1" >Total&nbsp; </asp:Label>         
                   </FooterTemplate>           </asp:TemplateColumn>
        <asp:TemplateColumn headertext="Product Price" ItemStyle-HorizontalAlign="Right">
                <ItemTemplate>
                     <asp:TextBox style="width:100px;" id="ProductPrice" runat="server" 
                                                                    Text='<%# Container.DataItem("UnitPrice") %>' >
                     </asp:TextBox>      
                </ItemTemplate>
                <FooterTemplate>       
                           <asp:TextBox style="width:100px;" Runat=server ID="Textbox1">90.25             
                            </asp:TextBox>   
                    </FooterTemplate>       
           </asp:TemplateColumn>         
  </Columns>       
 </asp:datagrid>
As you see in the above code, to have controls in the footer item. You need to add controls to footertemplate property. In the code behind file, we have code to bind this datagrid from datasource.
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles  
                                                                                                                   MyBase.Load
    Dim connstr As String = "Integrated Security=SSPI;Initial Catalog=Northwind;Data Source=.\NetSDK"
    Dim cnn As New SqlConnection(connstr)
    Dim da As New SqlDataAdapter("select top 5 * from products", cnn)
    Dim ds As New DataSet
    da.Fill(ds, "Products")
    DataGrid1.DataSource = ds
    DataGrid1.DataBind()
End Sub
This method looks simple, if you know what controls you need to add in the footer item during design phase itself. But if dont know about controls you need to add during desing phase, then you need to go for next method where you can add the controls dynamically.

Adding Controls Dynamically

This method is very similar to the above explained method, but this method doesnt use footertemplate property to add controls. Instead this method adds control dynamically to footer template when the datagrid is created. So datagrid definition will be like this without footertemplate,
 <asp:datagrid id="DataGrid1" runat="server" width="500px" AllowPaging="False"
                          ItemStyle-CssClass="tableItem" HeaderStyle-CssClass="tableHeader"
                          HeaderStyle-BackColor="#aaaadd" AutoGenerateColumns="False" 
                          DataKeyField="ProductID" ShowFooter="True" BorderWidth="0">
  <Columns>
       <asp:TemplateColumn headertext="Product ID">
            <ItemTemplate>
                     <asp:TextBox style="width:100px;" id="ProductID" runat="server"
                                                                  Text='<%# Container.DataItem("ProductID") %>' >
                     </asp:TextBox>
            </ItemTemplate>
       </asp:TemplateColumn>
       <asp:TemplateColumn headertext="Product Name">
            <ItemTemplate>
                     <asp:TextBox style="width:200px;" id="ProductName" runat="server"           
                                                                 Text='<%# Container.DataItem("ProductName") %>' >
                    </asp:TextBox>
             </ItemTemplate>
       </asp:TemplateColumn>
       <asp:TemplateColumn headertext="Quantity" FooterStyle-HorizontalAlign=Right  >
              <ItemTemplate>
                    <asp:TextBox style="width:100px;" id="Quantity" runat="server"
                                                                   Text='<%# Container.DataItem("QuantityPerUnit") %>' >
                    </asp:TextBox>
               </ItemTemplate>
       
 </asp:TemplateColumn>
        <asp:TemplateColumn headertext="Product Price" ItemStyle-HorizontalAlign="Right">
                <ItemTemplate>
                     <asp:TextBox style="width:100px;" id="ProductPrice" runat="server" 
                                                                    Text='<%# Container.DataItem("UnitPrice") %>' >
                     </asp:TextBox>      
                </ItemTemplate>
       
  </asp:TemplateColumn>         
  </Columns>       
 </asp:datagrid>
Similar to the above method, in the page load we need to bind this datagrid. For adding controls dynamically, we need to override ItemCreated event of the DataGrid. Sourcecode for this will be,
Private Sub DataGrid1_ItemCreated(ByVal sender As ObjectByVal e As 
                    System.Web.UI.WebControls.DataGridItemEventArgs)  Handles DataGrid1.ItemCreated
    If (e.Item.ItemType = ListItemType.Footer) Then
        e.Item.Cells(2).Text = "Total&nbsp;"
        e.Item.Cells(2).HorizontalAlign = HorizontalAlign.Right
        Dim oTextbox As New TextBox
        oTextbox.Width = New Unit(100, UnitType.Pixel)
        oTextbox.Text = "90.3500"  'This can be changed to populate from some datasource.
        e.Item.Cells(3).Controls.Add(oTextbox)
    End If
End Sub
Here we are adding label control and textbox control in the corresponding cells. While adding controls, we can set the the properties like text,alignment for that controls before adding to the footer item.

Conclusion

In this article, we have seen how we can add controls like label and textbox to the datagrid footer. Applying the same concept, we can add any controls to the datagrid footer dynamically or during design mode.

Master Pages in ASP.NET Whidbey


This article is continuation to the article on Consistent Web Site Design Using Page Templates where you have seen how to maintain consistent web site design using page templates. In this article, you are going to see how simple to do that in ASP.NET Whidbey using ASP.NET Master Pages.

Master Pages Overview

ASP.NET master pages allow you to create a consistent layout for the pages in your application. A single master page defines the look and feel and standard behavior that you want for all the pages (or a group of pages) in your application. You can then create individual content pages that contain the content you want to display. When users request the content pages, they merge with the master page to produce output that combines the layout of the master page with the content from the content page. Master pages provide functionality that developers have traditionally created by copying existing code, text, and controls elements repeatedly, using framesets, using include files for common elements, using ASP.NET user controls, and so on.
Various advantages of Master Pages are
1. They allow you to centralize the common functionality of your pages so that you can make updates in just one place.
2. They make it easy to create one set of controls and code and apply the results to a set of pages. For example, you can use controls on the master page to create a menu that applies to all pages.
3. They give you fine-grained control over the layout of the final page by allowing you to control how the placeholder controls are rendered.
4. They provide an object model that allows you to customize the master page from individual content pages.

How it is working?

Before you can understand how master pages is working, you just the see code snippets of master page and content page. Then you can easily understand how master pages is working in ASP.NET. Here is the code for master page(MasterPage.Master)
<%@ master language="VB" compilewith="MasterPage.master.vb" classname="ASP.MasterPage_master" %><html>
<head runat="server">
<title>Untitled Page</title>
     <link type="text/css" rel="stylesheet" href=Style.css />
</head>
<body>
    <form runat="server">
<table height="20%" border="0" cellpadding="0" cellspacing="0" width="100%">
    <tr valign="middle">
        <td height="20%" width="70%" align="left" style="HEIGHT: 61px"><h1>   MSDN India    </h1>  </td>
    </tr>
    <tr valign="bottom">
        <td height="12%" width="75%">
            <asp:table id="Menu" runat="server"></asp:table>
        </td>
        <td valign="bottom" align="right" class="nUserName" width="70%" height="10%">
            <asp:label id="UserName" runat="server" font-bold="True"></asp:label>
       </td>
    </tr>   
    <tr class="nTabBar">
        <td width="100%" colspan="2" height="19%" align="right">
            <table border="0" cellpadding="0" cellspacing="0" width="100%" >
                <tr>
                    <td width="85%" align="right">&nbsp;</td>
                        <td width="3%" align="right">
                            <asp:image id="SignOut" runat="server" imageurl="Images\SignOut.gif"></asp:image>
                        </td>
                </tr>
            </table>
          </td>
    </tr>
</table>
<table width=100% height=80% border=1px >
    <tr>
            <td width=15% valign =top >
                 <table>
                    <tr>
                        <td>
                            <asp:hyperlink id="HyperLink1" runat="server"  navigateurl="MyDetailPage.aspx">
                                Menu1</asp:hyperlink>
                        </td>
                    </tr>
                   <tr>
                        <td>
                            <asp:hyperlink id="HyperLink2" runat="server" navigateurl="MyDetailPage.aspx">
                                                 

                              Menu2</asp:hyperlink>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <asp:hyperlink id="HyperLink3" runat="server"  navigateurl="MyDetailPage.aspx">
                                Menu3</asp:hyperlink>
                        </td>
                    </tr>
                  </table>
            </td>
            <td width=85% valign=top >
                    <asp:contentplaceholder id="ContentPlaceHolder1" runat="server" >
                    </asp:contentplaceholder>
           </td>
</tr>
          </table>
    </form>
    </body>
</html>

Here is the code for content page(mydetailpage.aspx)
<%@ page language="VB" master="~/MasterPage.master" compilewith="MyDetailPage.aspx.vb" classname="ASP.MyDetailPage_aspx" %>
<asp:content id="Content1" contentplaceholderid="ContentPlaceHolder1" runat="server">    <asp:label id="Label1" runat="server" font-bold="True">This is my content page.</asp:label>
</asp:content>
As you have seen, master page is an ASP.NET file with the extension .master, such as MasterPage.Master with a predefined layout that can include static text, HTML Elements, and server controls. The master page also contains all the top level elements like <form> elements. Since top level elements are included in master page, no need to include it in content pages. You can define the layout for your website in master page in which you can place your contents using content pages like mydetailpage.aspx.
On the master page you also include one or more content placeholders that define regions where replaceable content will appear. You define the content for the placeholders by creating individual content pages, which are ASP.NET pages that are bound to a specific master page. In the content page, you create the content for the page by adding Content controls and mapping them to content placeholder controls on the master page. For example, the master page might have content placeholder called ContentPlaceholder1 . In the content page, you can create a Content controls that is mapped to ContentPlaceholder1.
After creating Content controls, you add text and controls to them as you would with any page or user control. In a content page, anything not inside the Content controls except script blocks will cause a run-time. You can perform any tasks in a content page that you do in an ASP.NET page. For example, you can generate content for the Content control using server controls and database queries or other dynamic mechanisms. You can create multiple master pages to define different layouts for parts of your site, and a different set of content pages for each master page.
You use master pages by requesting the content page in the browser. When ASP.NET processes the request, it performs the following steps:
1. Fetches the page.
2. Checks whether the content page references a master page.
3. If so, fetches the master page associated with the content page.
4. Merges the contents into the content placeholders on the master page.
5. Renders the result to the browser.

Creating Master Pages using VS.NET Whidbey

     VS.NET Whidbey provides various support for VS.NET Whidbey. For example, when you develop content pages, it will show master pages layout in design view. So that it will be easier for you to develop content pages based on outside layout. When you select "Add New Item" option in a project, you can select which type of asp.net file you want from the list of options like "Master Page", "Master Page with Code separation", "Content Page", "Content Page with Code Separation". When you select content page in this list, it will give you option for selecting a master page to embed with this content page. Then in the design view of content page, you can drag and drop the element or server controls in the corresponding contentplace holder in master page layout.

Conclusion

In this article you have seen how to maintain consistent layout for a website using Master Pages in ASP.NEt Whidbey. This article is just an introduction to Master Pages, there are lots of other features in Master Pages like nested master pages, customizing master pages from content pages, event handling of master pages. With the help of article you can start with Master page, then you can try those features.

Generics Internals


In this article, i am going to give an overview about Generics in whidbey and then i will go deep into how exactly it is working.  Before we start on what is generics, we will take a small example and see how generics fits in that. Then we can easily understand what is generics is. In .NET 1.x, if i want to write a collection which will just store the data and list that data. We will create the class like this,
public class List
{
      object[] items;
      int count;
      public void add(object item) {...}
      public object this() {...}
If you see this class declaration, two things we need to understand. Since we dont know about the type of the object that we are going to work on, we declared the items array as objects. Since it is object array, it can store any data type. Other problem is, in the methods for adding and retrieving data we are sending and receiving object only. Because of this two problems, we couldnt do type check at compile and performance also degrading. For example,
List intList = new List(); intList.Add(1);         // Argument is boxed
intList.Add(2);         // Argument is boxed
intList.Add("Three");   // Should be an error 
int i = (int)intList[0];      // Cast required 
If you see this declaration and instatitation process, whenever we are trying to add a item into this collection. Integer type is converted to object type, hence boxing is occuring. Similarly when you trying to retrieve the the value from this collection, we need to explicitly type cast it. Next problem is even we can add string to to this collection, thought we want to add only integers. Since the array is declared as object and add method accepts object, we can add any data type to this collection. Hence type check is not there, we will get an error at runtime, when we try to cast string to int while retrieving. To overcome this problem, we can create specialized collection for each data type. Then you need to replicate the code in all the classes, that will be a overhead.
Instead of this type of collections, if we write a collection in such a way we will get data type as parameter to that class and we will work on that datatype. For example,
public class List<T>
{
      T[] items;
      int count;
      public void Add(T item) {...}
      public T This() {...}
Here we are getting data type with which we are going to work as parameter (T) to this collection and we are declaring array of that data type. Similary for retrieving and listing, we are using this datatype only. If you see this instatitation,
List<int> intList = new List<int>();  
intList.Add(1);         // No boxing
intList.Add(2);         // No boxing
intList.Add("Three");   // Compile-time error  
int i = intList[0];     // No cast required 
Since when we are declaring this collection, we are mentioning that we are going to work on Int. There is no boxing while adding and we no need to do any type casting while retrieving as compiler knows that we are going to work only on Int. Similary if we try to add String data type to this collection we will get compile time error. So using this methodology, we are writing general class for all data type but without compromising type safety, performance, or productivity. This is called Generics in .NET 2.0.
Generics permit classes, structs, interfaces, delegates, and methods to be parameterized by the types of data they store and manipulate. Generics are useful because they provide stronger compile-time type checking, require fewer explicit conversions between data types, and reduce the need for boxing operations and run-time type checks. Generics permit classes, structs, interfaces, delegates, and methods to be parameterized by the types of data they store and manipulate.

Constraints

In the generics example which we have seen before will just do data storage, but most the of generics class will do more work than that. For example, if we need to use compareto method  on generice type in Add method. Then we will write the code like this,
public class List<T>
{
   public void Add(T item)
      {
            if (item.CompareTo(x) < 0) {...}           // Error, no CompareTo method
            ...
      }

 }
During compilation of generic type, we dont know which type we are going to work on. Compiler cant assume that CompareTo method will be available on this datatype, so it will give compile time error. Only members that can be assumed to exist on the type parameter are those declared by type object, such as Equals, GetHashCode, and ToString; a compile-time error therefore occurs in the example above. It is of course possible to cast the key parameter to a type that contains a CompareTo method. For example, the key parameter could be cast to IComparable:
public class List<T>
{
      public void Add(T item)
      {
            ...
            if (((IComparable)item).CompareTo(x) < 0) {...}
            ...
      }
}
 
While this solution works, it requires a dynamic type check at run-time, which adds overhead. It furthermore defers error reporting to run-time, throwing an InvalidCastException if a item doesn’t implement IComparable. To provide stronger compile time check and reduce type casts, Generice provide an optional list of constraints to be supplied for each parameter. A type parameter constraint specifies a requirement that a type must fulfill in order to be used as an argument for that type parameter.
public class List<T> where K: IComparable
{
   public void Add(T item)
      {
            if (item.CompareTo(x) < 0) {...}           // Error, no CompareTo method
            ...
      }

You can optionally specify multiple constraints on the same type parameter. In such cases, the types passed in as type arguments must satisfy all the constraints. Because multiple inheritances is not allowed by the CLR, you can specify only one class type constraint for a type parameter. And since multiple interfaces can be implemented or inherited by the same type, you can specify multiple interface constraints on the same type parameter. You can specify only one New constraint on a type parameter. Note that different kinds of constraints can be specified on the same type parameter.
When both a class constraint and an interface constraint are present on a type parameter, then you can access only the class members directly from objects of the type parameter type. To access the interface members, you need to cast the objects to the constraint interface type. When no class constraint is present, but multiple interface constraints are present, you can access the members of all the interfaces from objects of the type parameter type. If any member names are ambiguous because they are present in multiple interfaces, then you can disambiguate them by casting the objects to the appropriate interface and then accessing the member.  

Generic Methods

In some cases a type parameter is not needed for an entire class, but only inside a particular method. Often, this occurs when creating a method that takes a generic type as a parameter. In that case you can have generic method.

Conclusion

In this article, we have seen what is generics and where it can be used. In the next part of this article, we are going to see how exactly generics is working in CLR, how it is differing from C++ templates. Then we i will explain about how much performance improvement we will get if we go for generics with some performance data.

Automating build Using Team Build


Every software development project requires a proper build process for delivering a quality product. The build process generally involves the following steps:
  1. Getting the source code of the whole application
  2. Building the whole application
  3. Validating the build by running automated tests 
  4. Reporting and releasing the build.
Generally, the build process involves many repetitive and time consuming manual steps. Automating these steps not only reduces time and resource utilization but also helps to implement other processes like Continuous Integration, nightly or daily builds. By this, you can always ensure a stable product at any point of time during the development.
Though there are many external products/tools for automating build process, till date, there isn’t any build tool from Microsoft. Usually programmers create scripts for automating various steps involved in the build process. However, with Visual Studio Team System [VSTS], Microsoft has released a new build automation tool called Team Build.
This article explores this new build automation tool from Microsoft and it explains how to use Team Build scripts to implement other processes, like nightly build and continuous integration.

VSTS Team Build

VSTS Team build is built on top of MSBuild. MSBuild is the new build platform released by Microsoft along with .NET Framework 2.0. Team Build internally uses MSBuild for building the source code.
For more details about MSBuild, refer this link:
VSTS Team Build integrates with various tools available in VSTS like Source Control Management, Work Item Tracking, Reporting and Testing tools. The first step in automating build process is creating a build script. VSTS Team Build provides a wizard for creating build scripts. Before you start working on VSTS Team Build, you need to have Visual Studio Team System Client installed on your machine.
To create a build script, open Team Explorer in Visual Studio Team System. Then select the project in team explorer for which you wish to create the build script. In the Team build section of that project, right click and choose “New build type..” option from the menu. Team build script creation wizard will popup, as shown in following figure.
Build script wizard will walk you through the following steps:
1. Selection.
In this step, by default, the team build provides a list of all the solution files checked into the source control for the current project. You can select the required solutions files for building.
Note: In Visual Studio, the solution file is used as a container file for holding related projects and its artifacts like source files, configuration files, etc.
2. Configuration
You can specify the configuration for your build here. For example, a simple configuration would be to specify whether it is a release or a debug build.
3. Location
Here, you will configure the build machine name, the location where you want to get the source files from, before the build and the location where the binaries will be placed after the build is successful.
4. Options
Here, you will specify the list of automated test that you want to run during build process. Build will be successful only when each automated test passes. You can also specify whether you want to perform the code analysis along with your test.
Team Build wizard creates a build script once all the above steps are completed. This script is an MSBuild Script which will be used by MSBuild Engine for building the whole application. A sample Team build (MSBuild) script is shown in Figure 2 .
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="DesktopBuild"     xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import   Project="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v8.0\TeamBuild\Microsoft.TeamFoundation.Build.targets" />
  <ProjectExtensions>
    <Description>
    </Description>
    <BuildMachine>neon</BuildMachine>
  </ProjectExtensions>
  <PropertyGroup>
    <TeamProject>PV-6</TeamProject>
    <BuildDirectoryPath>c:\siva\buildsource</BuildDirectoryPath>
    <DropLocation>\\xeon\binaries</DropLocation>
    <RunTest>false</RunTest>
    <WorkItemFieldValues>Priority=1;Severity=1</WorkItemFieldValues> 
    <RunCodeAnalysis>Never</RunCodeAnalysis>   
    <UpdateAssociatedWorkItems>true</UpdateAssociatedWorkItems>
  </PropertyGroup>
  <ItemGroup>   
    <SolutionToBuild Include="$(SolutionRoot)\SampleWindowsApp\SampleWindowsApp.sln" />
  </ItemGroup>
  <ItemGroup>   
    <ConfigurationToBuild Include="Release|Any CPU">
      <FlavorToBuild>Release</FlavorToBuild>
      <PlatformToBuild>Any CPU</PlatformToBuild>
    </ConfigurationToBuild>
  </ItemGroup>
  <ItemGroup>   
    <MetaDataFile Include="$(SolutionRoot)\SampleWindowsApp\SampleWindowsApp.vsmdi">
      <TestList> </TestList>
    </MetaDataFile>
  </ItemGroup>
  <ItemGroup>   
  </ItemGroup>
</Project>

Team Build Architecture

A pictorial representation of the Team Build architecture is shown in following figure.
Team Build architecture starts with the Team Foundation client from where the user will connect to Team Foundation and create a build script.
Note: Team Foundation is the server side component of Visual Studio Team System.
The build script is stored in the Team Foundation server. The Team Foundation server consists of two tiers. The Application Tier is where all the services like source control management service, build service, work item tracking service and other services reside. In Data Tier, all the data of these Team Foundation services are stored.
Team Build provides an option for a dedicated build server other than the Team Foundation server. In most of the software development projects, there will be a dedicated server for build. To support that process, team build also provides an option to install team build components on a separate machine. To know more about how to set up Team build server, refer the “Setting up the Build Server” section of this article. These build server components can also be deployed along with the Team Foundation server.
When the build is started from Team Foundation client, a call is made to the Team Foundation server and from there the build information is sent to the build server. Build server takes the build script from Team Foundation client and does the following job based on build script configurations.
  1. Gets the source code from Team Foundation source control management. From the configuration file, build server recognizes the solution files that need to be picked up from the source control management for building.
  2. Uses MSBuild engine to build the source code
  3. Uses source control management to label the source code with the current build number.
  4. If the build succeeds, Team build runs the tests specified in the build script to validate the build.
  5. If the build fails, Team Build automatically creates a bug work item and attaches the build information to the work item.
  6. Generates the reports for the build. Despite the failure or success of the build, the report is generated.
  7. If the build tasks succeed, Team Build places all the binary files of the build in a network share location as specified in the Build scripts.
  8. In the final step, Team Build will send the notifications to all the subscribers. You can subscribe to build events as described in the following section.

Subscribing to Build Events

By default, Team Foundation provides the following events notifications.
  1. Build status change Event
This event is fired whenever the build status is changed, build statuses are - pass, fail and stop.
  1. Build Success Event
This event is fired only when the build passes.
Based on your requirement, you can subscribe to these events. To subscribe to these events, open the team explorer and select the current project and choose Project Alerts option from Team menu in Visual Studio Team System.
In the project alerts window, you can see a list of events which you can subscribe. In this window, specify your email address and subscribe to the required event. Once the event is raised, you will receive a mail that contains an hyperlink which takes you to the report of that build.

Build the application

Once you create the Team build script using team build wizard, it is automatically stored in the Team Foundation server. You can view/edit the team build script from Team Builds section in Team Explorer window for a project. When you want to build that project, you can select the build script in team explorer window and build it from there.
The only drawback with this approach is that, you can’t automate the build process i.e. whenever you want to build your application, you will need to manually open Visual Studio Team system and run the build from team explorer.
Though VSTS Team build doesn’t provide direct support for running build scripts automatically, there are a few workaround for automating build script execution.
There are two types of requirements for automating the build process:
  • You might want to run the build script at a certain time. Build process like daily, nightly or weekly build comes under this category. These are called timely builds.
  • You might want to run the build script when somebody checks in some code in the source control management. This process is called continuous integration.
In the next few sections, we will see how to implement both these type of automation.

Timely Build

VSTS provides a command line utility TFSBuild.exe for running the build from command line. This command line utility is placed in the following location,
C:\Program Files\Microsoft Visual Studio 8\Common7\IDE
You can specify the foundation server name, build script name, project name and few other build related details as parameters to this utility. When you run it, it will give you the status report of the build in the command prompt as shown in the following figure.

You can use this command line utility to schedule the timely build. For scheduling, you need to use Windows OS scheduler feature. Using this option, you can schedule an application to run at any time.
Note: To access Windows Scheduler, Go to All Programs à Accessories à System Tools à Scheduled Tasks.

Continuous Integration

The next automated build requirement is continuous integration. Continuous integration is the strategy of making sure that changes to the project’s code base are built, tested and reported as soon as they are introduced. To know more about the process and benefits of continuous integration, check out this article by Martin Fowler,
Using our earlier automated approach, we can’t do continuous integration as we don’t know when the developer will check in the code. So we need some mechanism to identify the check in events.
Fortunately, VSTS Source Control Management services provides Check-In event which is similar to our Build Success Event which we have seen earlier. To get an event, we need to subscribe to that event. There are two types of subscriptions for all VSTS events:
1. Email notification subscription which we have seen previously when we dealt with Build Completion Event
2. Second type of event subscription is web service subscription i.e. when the event is raised in VSTS, TFS will call a method in a web service with that event information. We set the webservice location while subscribing for the event.
We can use the later option to implement continuous integration with VSTS, i.e. whenever a check-in happens; an event is fired by source control management service. During that time, notification will be sent to the subscribed web service. In this web service, we need to write the code for running the build script.
The next step is how to run the build script programmatically. It is not a recommended approach to run the build script programmatically using command line utility from web service. The only option we have is to use the build service provided by VSTS.
There are two types of build service available in Team build.
  1. BuildController Service
This service is used to control the build script execution. Using this script, you can run, stop and delete the build script.
  1. BuildStore Service
Using this service, you can monitor the build status or you can view the previous build results.
For implementing Continuous integration, we need to use the BuildController Service. The code for running the build script programmatically is shown in the following code snippet.
[SoapDocumentMethod("http://Microsoft.VisualStudio.Bis/Notify",
     RequestNamespace = "http://Microsoft.VisualStudio.Bis")]
    [WebMethod]
    public void Notify(string eventXml, string tfsIdentityXml)
    {
        BuildController.BuildController buildCtrl = new BuildController.BuildController();
        BuildParameters buildParam = new BuildParameters();
        // I have hard coded the values for foundation server, project and build type here.
        // You can alter this to pick these values from database or config files.

        buildParam.TeamFoundationServer = "http://XEON:8080";
        buildParam.TeamProject = "PV-6";
        buildParam.BuildType ="BuildScript";
        buildParam.BuildDirectory = @"c:\Siva\buildsource";
        buildParam.BuildMachine ="Neon";
        buildParam.DropLocation =@"\\xeon\binaries";             
        buildCtrl.Credentials = System.Net.CredentialCache.DefaultCredentials;       
        string buildUri = buildCtrl.StartBuild(buildParam);      
}
If you look at the above code, you see that we need to create the instance of buildcontroller service, pass buildparameters, and then run the build script by calling the StartBuild method in build controller service. You can write your custom code after you start the build. For example, you might want to send a mail to your project manager about the build or you can create a work item in case the build fails.
The method name in this web service needs to be Notify. Once you subscribe to Check-in events, this method is called when the check-in event fires. For subscribing to check-in event, we need to use a utility BisSubscribe.exe available in the following location.
C:\Program Files\Microsoft Visual Studio 8\Common7\IDE\PrivateAssemblies
Parameter required for this command line utility are,
Bissubscribe /eventType CheckinEvent /address http:////16.138.29.206/BuildService/continuousIntegration.asmx  /deliveryType Soap /userId domainname\username /domain http://teamfoundationame:portnumber
Run this utility to subscribe to the check-in event. You will be specifying the web service name during subscription, so VSTS Eventing Service will call this web service when Check-In Event fire.

Setting up the Build Server

As seen earlier, VSTS Team build provides an option to have a dedicated build server. To provide this option, Team build components are provided separately in Visual Studio Team Server installation script. You can find the Team build component in a separate folder named bb. To install team build component, run thesetup.exe in that folder.
To verify whether team build is installed in the build server, look for TeamBuild service in services console window of the Window OS.

Summary

Continuous Integration is one of the key processes in Extreme Programming (XP) methodology. This process is getting adapted widely in all kinds of software development projects. With tools like VSTS Team Build, this process can be implemented very easily. If at all, you feel continuous integration might be an overhead in your development, then you should at least switch to timely build process, like daily build or nightly build.