Tuesday 17 June 2014

Using XML Data Source Control in Asp.net and binding to grid and controlling events to it.

This article also explains how to make use of XML datasource control in your website for a grid and filter the data according to your selection in dropdown list.
1. Filtering XmlDataSource based on data in XML Tag.
2. Filtering XmlDataSource based on data in XML Attribute.
Below is My XML Code
<employees>
  <employee city="Kansas" id="1">
    <employeename>Roddam Ramesh</employeename>
    <country>USA</country>
  </employee>
  <employee city="Hyderabad" id="2">
    <employeename>Vishwas</employeename>
    <country>India</country>
  </employee>
  <employee city="MaryVille" id="3">
    <employeename>Dheeraj</employeename>
    <country>USA</country>
  </employee>
  <employee city="MaryVille" id="4">
    <employeename>Anil Kumar</employeename>
    <country>USA</country>
  </employee>
  <employee city="Hyderabad" id="5">
    <employeename>Satish</employeename>
    <country>India</country>
  </employee>
  <employee city="Miami" id="6">
    <employeename>Balaji</employeename>
    <country>USA</country>
  </employee>
  <employee city="Sydney" id="7">
    <employeename>Hari Krishna</employeename>
    <country>AUS</country>
  </employee>
  <employee city="Delhi" id="8">
    <employeename>samanth</employeename>
    <country>India</country>
  </employee>
  <employee city="Bombay" id="9">
    <employeename>Karan</employeename>
    <country>India</country>
  </employee>
</employees>



Set the DataSourceId and Path: 
DataSourceID: - Id of the XmlDataSource control.
XPath: - Path to the Tag that needs to be populated inside the GridView

<asp:XmlDataSource ID="XmlDataSource1" runat="server" DataFile="~/Employees.xml">
</asp:XmlDataSource>
<asp:GridView ID="GridView1" runat="server" XPath="/Employees/Employee" DataSourceID="XmlDataSource1"
    AutoGenerateColumns="false" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White">
    <Columns>
        <asp:TemplateField HeaderText="Id" HeaderStyle-Width="50">
            <ItemTemplate>
                <%# XPath("@Id") %>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Name" HeaderStyle-Width="100">
            <ItemTemplate>
                <%# XPath("EmployeeName") %>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="City" HeaderStyle-Width="100">
            <ItemTemplate>
                <%# XPath("@City") %>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Country" HeaderStyle-Width="100">
            <ItemTemplate>
                <%# XPath("Country") %>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

For City and Country drop down Events use the following code which will filter your data acoording to the selection by the user on the drop down.

protected void CountryChanged(object sender, EventArgs e)
{
    ddlCities.SelectedIndex = -1;
    string country = ddlCountries.SelectedItem.Value;
    if (country != string.Empty)
    {
        XmlDataSource1.XPath = "/Employees/Employee[ Country='" + country + "']";
    }
    else
    {
        XmlDataSource1.XPath = "/Employees/Employee";
    }
}

protected void CityChanged(object sender, EventArgs e)
{
    ddlCountries.SelectedIndex = -1;
    string city = ddlCities.SelectedItem.Value;
    if (city != string.Empty)
    {
        XmlDataSource1.XPath = "/Employees/Employee[ @City='" + city + "']";
    }
    else
    {
        XmlDataSource1.XPath = "/Employees/Employee";
    }
}

Here are the different outputs:





Tuesday 22 October 2013

Memory Management in asp.net

The article/code snippet includes various points that should be given time for effective memory management. It does not give solutions but gives an inside into what options are there.

  1. Effective use of Caching.
    The main reasons for caching are performance related. Memory in ASP.NET is still a very limited resource. Do not waste it by caching anything more than a couple of minutes unless it is very expensive to regenerate. Various types of caching are:
    • Page Level Output Caching: : This keeps a copy of the HTML that was sent in response to a request in memory. Subsequent requests are then sent the cached output until the cache expires. Thus round way trips are saved to memory and response time improves.
    • Fragment caching, User Control Output Caching: There are situation where caching the entire page is not feasible. Only certain parts of the page are customized for the user. In such scenarios, fragment caching is used. Menus and other layout elements, especially ones that are dynamically generated from a data source, should be cached with this technique.


  2. Type Sizing
    Memory usage ultimately depends on the types defined and used by the assemblies in your program. Here the important point is what types to be used since, the bytes occupied by .NET data types is fixed. bool takes 1 byte, double 8, decimal 16, Int32 takes 2 byte, etc... So nothing much can be done about these. The concern is structures, references. The size of a reference type is the size of its fields rounded up to the next 4-byte boundary, plus 8 bytes of overhead. So a reference type will always occupy at least 12 bytes. A Structure size is computed as the sum of the sizes of its fields but is problematic if you need to store a reference to the type, since frequent boxing can memory and CPU cycles.
  3. Pooling
    Once an application is up and running, memory utilization is affected by the number and size of objects the system requires. Object pooling reduces the number of allocations, and therefore the number of garbage collections, required by an application. Pooling is quite simple: an object is reused instead of allowing it to be reclaimed by the garbage collector. Objects are stored in some type of list or array called the pool, and handed out to the client on request. This is especially useful when an instance of an object is repeatedly used, or if the object has an expensive initialization aspect to its construction such that it's better to reuse an existing instance than to dispose of an existing one and to create a completely new one from scratch. Let's consider a scenario in which object pooling would be useful. Consider a loop wherein you want to compare the values in the record with a static value.
    The code might contain a loop that does something like this:

    <script type=&quot;syntaxhighlighter&quot; class=&quot;brush: csharp&quot;>
    <![CDATA[
    while (IsRecordAvailable()){
        Employee record = GetNextRecord();
        ... // process record
    }]]>
    </script> 

    In this loop, a new employee Record is returned each time the loop is executed. The most obvious implementation of the GetNextRecord method would create a new object each time it is called, requiring the object to be allocated, initialized, eventually garbage collected, and finalized if the object has a finalizer. When using an object pool, the allocation, initialization, collection, and finalization only occur once, reducing both the memory usage and the processing time that is required.
    In some situations, the code could be rewritten to take advantage of a Clear method on the type with code like this:

    Employee record = new Employee ();
    while (IsRecordAvailable())
    {
        record.Clear();
        FillNextRecord(record);
        ... // process record
    }


  4. Garbage Collection.

    You should almost never call GC.Collect() manually. And by almost I mean once in a lifetime, not once per application, and certainly not once per function call. I occasionally call GC.Collect() for testing purposes just to see if memory has been released. Normally you would never call it. The GC is self-balancing and by calling GC.Collect() you are disrupting that balance.


  5. Managed Heap.

    When you initialize a new process, the runtime .NET environment reserves a contiguous address space for the process. This reserved address space is called the managed heap. The managed heap maintains a pointer to the address where the next object in the heap will be allocated. Initially, this pointer is set to the managed heap's base address. All reference types are allocated on the managed heap. When an application creates the first reference type, memory is allocated for the type at the base address of the managed heap. When the application creates the next object, the garbage collector allocates memory for it in the address space immediately following the first object. As long as address space is available, the garbage collector continues to allocate space for new objects in this manner. Allocating memory from the managed heap is faster than unmanaged memory allocation.


  6. Session handling.

    ASP.NET provides various modes of session state storage. This can be changed by the programmer using the mode attribute of tag in your web application’s Web.config file. Below is a sample of this tag:
    < sessionState mode="InProc"
        stateConnectionString="tcpip=127.0.0.1:42424"
        sqlConnectionString="data source=127.0.0.1;Trusted_Connection=yes"
        cookieless="false" 
        timeout="20" />
    

    AttributeOptionDescription
    mode
    Specifies where to store the session state.

    OffDisables session state management.

    InProcSession state is stored locally in memory of ASP.NET worker process.

    StateServerSession state is stored outside ASP.NET worker process and is managed by Windows service. Location of this service is specified by stateConnectionString attribute.

    SQLServerSession state is stored outside ASP.NET worker process in SQL Server database. Location of this database is represented by sqlConnectionString attribute.


    We access Session data through a property named Session. This Session property is an object of HttpSessionState class in System.Web.SessionState namespace.

Wednesday 25 September 2013

Hiding and Displaying div tag content in real time using Jquery.

Hi Viewers,

This article describes about hiding and displaying the division tags using JQuery with out any postback to the page.
There are many situations you need to hide the div(block of code) in the real time and This can be achieved using JQuery.
This example demonstrate the three scenarios of registering user.
  1. Register Directly.
  2. Register Via Facebook Account.
  3. Register Via Gmail Account.
Download the example from the below link and debug it. This kind of examples are commonly used in any web application and it is very helpful interview question.

Download Link:  Hiding and Displaying div tag Content in real time using Jquery.
Make this Page as Start-up Page: HidingandDisplayingDiv.aspx 

Apart from that it also includes the other example: Real Time ASP.Net Dropdown Binding implementation in web application
ReferenceLink: http://realtimeaspdotnet.blogspot.in/2013/09/real-time-aspnet-dropdown-binding.html



Register Directly


Register With Facebook Account






Register With Gmail Account



Generated Output


In order to get the above result:
  • Create 3 radio buttons by specifying the group name.
  • Create three <div> blocks with unique id.
    • In the above Example there are three <div> with unique Ids
      • <div id="RegisterDiv" style="float: left; width: 100%; display: none; margin-top: 10px;" >
      •    <div id="RegisterFacebookDiv" style="float: left; width: 100%; display: none; margin-top: 10px;">
      •  <div id="RegisterGmailDiv" style="float: left; width: 100%; display: none; margin-top: 10px;">
  • For each radio button specify the onclick="Register('RegisterGmail');"  function and implement the Register method in java script.
  • Place All the controls in <divs> that needs to be rendered on the page.

  •    <script lang="javascript" type="text/javascript">
            function Register(value) {
                if (value == "Register") {
                    $("#RegisterDiv").css('display', 'block');
                    $("#RegisterFacebookDiv").css('display', 'none');
                    $("#RegisterGmailDiv").css('display', 'none');

                }
                else if (value == "RegisterFacebook") {
                    $("#RegisterDiv").css('display', 'none');
                    $("#RegisterFacebookDiv").css('display', 'block');
                    $("#RegisterGmailDiv").css('display', 'none');
                }
                else if (value == "RegisterGmail") {
                    $("#RegisterDiv").css('display', 'none');
                    $("#RegisterFacebookDiv").css('display', 'none');
                    $("#RegisterGmailDiv").css('display', 'block');
                }
            }
        </script>
  • Include Latest Jquery java script file. <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
  • function Register(value) function checks the value and based on the value it hides and displays the <div>
  • These <Divs> can be displayed or can be hide by using   $("#DivisionID").css('display', 'block');
That`s all.

Please share this useful information with other.If you are interested in reading my articles click on Join this site button located below blog archive.

Sunday 22 September 2013

Increasing Performance of ASP.Net web application.

Hi Viewers,

This article describes  techniques to increase the performance of Asp.Net web application.

While developing large application performance is the major factor. Performance plays crucial role in development of any application. There are many ways to increase the performance of the application.Some of them are discussed below.
  1.  Page Level and Server controls:
  2.  State Management Level:
  3.  Data Access Level: 
  4.   Web Application Level:
  • Page Level and Server controls:
    • Avoid unnecessary round trips to the server.
      • use Microsoft Ajax and partial-page rendering to accomplish tasks in browser code.
    • use IsPostBack Property of page object to avoid unnecessary processing.
      • Avoid executing code on each postback if it only has to run the first time the page is requested.
    • while developing custom server controls. design them to render client script for some of their functionality.
      • Creating Custom Client Script by Using the Microsoft Ajax Library.
    • Use Server.Transfer and cross-page posting to redirect between ASP.NET pages in the same application.(For accessing controls and their values from the source page).
    • Leave buffering on unless you have a specific reason to turn it off .  
      • There is a significant performance cost for disabling buffering of ASP.NET Web pages.
  •  State Management:
    •   Use View state of control when it is required.
      • By default, view state is enabled for all server controls. Disable it , by setting  EnableViewState property to false, as in the following example:
        <asp:datagrid enableViewState="false" datasource="..." runat="server"/>
    • Avoid using view state encryption unless you have to.
      • View state encryption prevents users from reading view-state values in the hidden view-state form field.
    • Select appropriate session-state provider for your application
      • Asp.Net provides various ways to store data in a session.Based on the requirement and conditions of the application select appropriate session storage. Example:in-process session state, out-of-process session and creating custom session also possible.
    • Disable session state when you are not using it.
      • To disable session state for a page, set the EnableSessionState attribute in the @ Page directive to false, as in the following example:
        <%@ Page EnableSessionState="false" %>
        To disable it at application level,Use this property in web.config. 
         <sessionState mode="Off" /> 
        
        
  •  Data Access Level:
    • Use SQL Server and stored procedures for data access:
      • SQL Server is the recommended choice for data storage to create high-performance, scalable Web applications.
    • Use the SqlDataReader class for a fast forward-only data cursor:
      • The SqlDataReader class creates a forward-only, read-only data stream that is retrieved from a SQL Server database. 
    • Cache data and page output whenever possible:
      • use caching if there is no dynamic content request for every page request.
    • Use SQL cache dependency appropriately.
      • Use Table-based polling feature provided by SQL Server. In table-based polling, if any data in a table changes, all cache items that are dependent on the table are invalidated
    • Use data source paging and sorting instead of UI:
      • Don`t pull all the data from the database. use paging concepts and retrieve the number of records that are necessary to display.
    • Balance the security benefit of event validation with its performance cost.
    • Use SqlDataSource control caching, sorting, and filtering .
        
  •  Web Application Level:
    • Preload the application.
      • initial start up response time can be improved by preloading.
    • Precompile Web site projects. 
      • Initially project is batch compiled upon first request and this batch compilation compiles all pages in a directory to improve memory and disk usage.So  Precompile the whole project before deploying it into the server.
    • Disable debug mode
      • Disable debug mode before you deploy a production application.
    • Tune the configuration files for the Web server computer and for specific applications.
    • Recycle processes periodically.
    • Set the number of threads per worker process.
    • For applications that rely extensively on external resources, enable Web gardening on multiprocessor computers.    

    Thursday 19 September 2013

    Real Time ASP.Net Dropdown Binding implementation in web application

    Hi viewers,

    This is my 4th post and i think you people will feel very interesting while reading this article and you will improve coding skills after debugging the code.

    Please download the code and debug it. i am sure you will get lot more knowledge on real time web application development. you will find the structure of web application,using of master pages,re-usability of code and  things related to naming conventions,Entity creations,Data accesssing and lot more.

    Download LINK: real time asp.net dropdown binding download

    In the above link you can find the example of how a drop down is binded in real time web application development with the entities. In this example i will use only one method for binding thousands of drop downs across the application.Don`t get shocked,this is possible and i love this quote "Write once and use it many times". In the example only one drop down is binded but you can bind "n" number of drop downs by calling only one method. 

    Look at the method in the downloaded example:

                     ToggleControlOnlyBlank(ByRef workingddl As DropDownList, ByRef workinglist As Object,  ByVal intItemCount As Int16,  ByVal ddlvalue As String, ByVal ddlText As String,  ByVal enabled As Boolean, ByVal addBlankText As Boolean, ByVal autoPostBack As Boolean, ByVal Visible As Boolean, _Optional ByVal defaultValue As Integer = Nothing)




    i am making this method as shared method and placing it in a common utility class. So that it is accessible across the application and not necessary to create an object to call this method every time. In the same way you can re-use the code for different purposes.

    Why Common utility class?
                        Because it is very meaningful when we place all the methods which are frequently used in the application.

    i hope you will enjoy this while debugging the code.

    Please comment it if you have any queries. I will respond to your queries in my free time.

    Tuesday 17 September 2013

    Different ways to achieve code re-usability in real time Asp.Net



    Most of the people know inheritance is the major way for re-usability of code. Apart from that their are other ways of code re-usability. This article is very useful for the people who are preparing for interviews as well as the employees who are working in software industry.

    This article describes  how people re-use the code in software Industry. This article is little big so don`t get hesitate to read this article. You will find very helpful information with an example.
    1. Using Master Pages. (Example .Master Pages in asp.net).
    2. Using User Controls. (Example: .ascx  Custom Controls ).
    3. Using Singleton Classes. (To prevent identical objects from being created)
    4. Using Entities. (Re-usability of Entities are very important in real time implementations).
    5. Inheritance and Shared Methods. (is-a Relationship and Has-a Relationship)
    6. Creating COM Components. (.dll class libraries interoperability between languages)

      Master Pages
      :
      • To create a set of controls that are common across all the web pages and attaching them to all the web pages.
      • A centralized way to change the above created set of controls which will effectively change all the web pages.
      • Changing the UI elements dynamically on master page from content pages based on user choice.
      • Nested Master Pages are also Possible. 

      Using of Master Pages: 
      • Whenever you create "Master pages" use content place holders inside master page where you can specify the controls to be rendered.
      • Use Same Content place holders id in the derived page and create your customized content in that content place holder.

      Normally in software industry Master Pages are placed in the below path
      Path= ~/Assets/masterpages/MasterPage.master

      In Any Real time development Must and should you master pages and it is recommended.
      MasterPagesMerge graphic


      User Controls: In addition to using Web server controls in your ASP.NET Web pages, you can create your own custom, reusable controls using the same techniques you use for creating ASP.NET Web pages. These controls are called user controls.
      • User controls are containers into which you can put markup and Web server controls. You can then treat the user control as a unit and define properties and methods for it.
      •  Custom controls. A custom control is a class that you write that derives from control or web control.
        A user controls differs from an ASP.NET Web page in these ways:
        • The file name extension for the user control is .ascx.
        • Instead of an @page directive, the user control contains an @control directive that defines configuration and other properties.
        • User controls cannot run as stand-alone files. Instead, you must add them to ASP.NET pages, as you would any control.
        • The user control does not have html, body, or form elements in it. These elements must be in the hosting page.
       Use this tag in a page for registering the user control in a page:
      <%@ Register TagPrefix="Grid" TagName="RequestData" Src="~/Users/Controls/ConnectionControl.ascx" %> 
      Use this tag as many times you want to use this control in your page
       <Grid:RequestData ID="rgInbox" runat="server" />
       
      How to Access Page Methods from user controls and Vice Verse?
                   Page methods can be accessed from user control using Reflection and finding the control or value in user control can be accessed in page by using  Me.Parent.FindControl("controlname").                          
                                                             
      Singleton Classes: To Make sure to create only one instance and  there is a global access point to that object then singleton classes play an important role. This is one design pattern. Now i am just giving an idea how to create singleton class. Example:Garbage Collection.
      singleton Class
      Imports System
      Public Class Singleton
          Private Shared instance As Singleton
           Private Sub New()
             MyBase.New
           End Sub
      
           Public Shared ReadOnly Property GetInstance As Singleton
             Get
                  If(instance Is Nothing) Then
                      instance = New Singleton
                  End If
                  Return instance
              End Get
           End Property
      
      End Class
      How to create an instance?
      Singleton.GetInstance()-----Use ClassName.MethodName

      Using Entities : Like Methods and Classes class entities can be reused.

      User.vb: This class consists of user properties with setter() and getter() methods.
      • user class properties: UserName,FirstName,LastName,Address,Mobile,DateOfBirth.

      Account.vb: This class consists of Account properties with setter() and getter() methods.
      • Account class properties: AccountId, AccountName, AccountType, AccountCreated, AccountUpdated.

      How to Re-use Entities?
      • Here to re-use User class entities in Account class as mentioned below
        public property AccountDetails as User
        For accessing in application you can use:  AccountDetails.UserName or AccountDetails.FirstName.

      Inheritance and Shared Methods:
      Inheritance is a process of inheriting properties and methods from parent class to child class. If an object is created to the child class then parent class constructor will be called first and  child class method will be executes.

      1. Single Inheritance
      2. Hierarchical Inheritance
      3. Multi Level Inheritance
      4. Hybrid Inheritance
      5. Multiple Inheritance

      All the types of inheritance can be achieved in Object Oriented Programming except Multiple Inheritance. Multiple inheritance can be implemented using Interfaces.

      Major People feel difficulty to explain the below question in interview
      Why Multiple inheritance is not possible?
                   
                    Reason 1: Problem around Diamond problem, consider a class A has run() method and then B and C derived from A and has there own run() implementation and now class D derive from B and C using multiple inheritance and if we refer just run() compiler will not be able to decide which run() it should invoke. This is also called Diamond problem because structure on this inheritance scenario is similar to 4 edge diamond, see below
                A run()
              /      \
            /          \
         B run()     C run()
            \          /
              \     /
               D run()
                 Even if we remove the top head of diamond class A and allow multiple inheritances we will see this problem of ambiguity.

                  Reason 2: Multiple inheritances does complicate the design and creates problem during casting, constructor chaining etc and given that there are not many scenario on which you need multiple inheritance its wise decision to omit it for the sake of simplicity. Also .net avoids this ambiguity by supporting single inheritance with interfaces. Since interface only have method declaration and doesn’t provide any implementation there will only be just one implementation of specific method hence there would not be any ambiguity.

      Shared Methods : Shared methods are majorly used in any application they re-use these methods many types in the application like making all the string safer while retrieving it from database and using common methods to bind controls like dropdown control.

      Example: Creating shared method for binding the drop down and re-use it whenever necessary to bind the different drop downs in the application. Concept of  "Write Once and use Many times."

      COM Components: Component Object Model is a method to facilitate communication between different applications and languages. The interesting thing in COM components and  widely accepted interoperability standard and explains the way the memory should be organized for all the objects.

      Creating COM Components
      • Create a new Class Library project.
      • Create a new interface, say IManagedInterface, and declare the methods required. Then provide the Guid (this is the IID) for the interface using the GuidAttribute defined in System.Runtime.InteropServices. The Guid can be created using the Guidgen.exe. [Guid("3B515E51-0860-48ae-B49C-05DF356CDF4B")]
      • Define a class that implements this interface. Again provide the Guid (this is the CLSID) for this class also.
      • Mark the assembly as ComVisible. For this go to AssemblyInfo.cs file and add the following statement [assembly: ComVisible (true)]. This gives the accessibility of all types within the assembly to COM.
      • Build the project. This will generate an assembly in the output path. Now register the assembly using regasm.exe (a tool provided with the .NET Framework)- regasm \bin\debug\ComInDotNet.dll \tlb:ComInDotNet.tlb This will create a TLB file after registration.
      • Alternatively this can be done in the Project properties -> Build -> check the Register for COM interop.
      Please share this helpful information with your friends.

      My next post will be on real time dropdown binding with an example and re-using the code to bind thousands of   dropdowns in web application.

    Saturday 14 September 2013

    The Structure of an Asp.Net real time web application

    Hi Viewers

    This page describes the structure of a real time web application and the steps to be followed for creating such structure.

    A real time web application has a layered structure as described below
    1. Data Access Object Layer (DAO) : To interact with data base and get the data tables and put it into a list with the help of entity objects.
      Example:  list(of MySampleApplication.Sample.Entities.User.User)
      This list is returned to the implementation layer and the implementation layers handovers the list to the asp.net application layer and there we bind it to grid or drop downs or to other data controls.
    2. Entities Layer: Consists of Entity class properties.These properties can only be accessed through set and get method as Properties are declared with Private keyword.
    3. Interface Layer:  Consists of all user defined interfaces which are implemented in implementation layer.
    4. Implementation Layer: Consists of Implementation of interfaces and creation of an object of DAO to call the methods in DAO class.
    5. Utilities: Consists of the shared classes and the methods that are most frequently called in application.
      Example:Making string safer,checking for  nulls,connection methods and other common methods


    Description for the above structure and the used design pattern will be posted later . Please have a look at below Real time structure and its implementation.


    You can download the sample application from the below link:

    Link : https://drive.google.com/folderview?id=0BxHH0xtw0daaclZNdHFtb3g1Ync&usp=sharing

    My next post will be on "Code Re-usability in asp.net."

    Please share this helpful information with your friends.