Pages

Wednesday, September 21, 2011

Garbage Collection in .NET

The .NET Framework's garbage collector manages the allocation and release of memory for your application. Each time you create a new object, the common language runtime allocates memory for the object from the managed heap.

Fundamentals of Memory
     - Each process has its own separate virtual address space.
     - By default, on 32- bit computers, each process has 2 gb user-mode virtual address space.
     - As an application developer, you work only with virtual address space and never manipulate physical memory directly. The garbage collector allocates and frees virtual memory for you on the managed heap.
     - Virtual memory can be in three states:
               - Free: The block of memory has no references to it and is available for allocation.
               - Reserved: The block of memory is available for your use and cannot be used for any other allocation request. However, you cannot store data to this memory block until it is committed.
               - Committed: The block of memory is assigned to physical storage.
    - Virtual address space can get fragmented.  When a virtual memory allocation is requested, the virtual memory manager has to find a single free block that is large enough to satisfy that allocation request. 
      - You can run out of memory if you run out of virtual address space to reserve or physical space to commit.  In the common language runtime (CLR), the garbage collector serves as an automatic memory manager. It provides the following benefits:

 Fundamentals of Garbage Collection:

              - Enables you to develop your application without having to free memory.
              - Allocates objects on the managed heap efficiently.
              - Reclaims objects that are no longer being used, clears their memory, and keeps the memory available for future allocations. 
             - Provides memory safety by making sure that an object cannot use the content of another object

Conditions for a Garbage Collection:
        Garbage collection occurs when one of the following conditions is true:
              - The system has low physical memory.
              - The memory that is used by allocated objects on the managed heap surpasses an acceptable threshold. This means that a threshold of acceptable memory usage has been exceeded on the managed heap. This threshold is continuously adjusted as the process runs.
               - The GC.Collect method is called.

The Managed Heap:
       - After the garbage collector is initialized by the CLR, it allocates a segment of memory to store and manage objects. This memory is called the managed heap, as opposed to a native heap in the operating system.
       - There is a managed heap for each managed process. All threads in the process allocate objects on the same heap.
       - To reserve memory, the garbage collector calls the Win32 VirtualAlloc function, and reserves one segment of memory at a time for managed applications. The garbage collector also reserves segments as needed, and releases segments back to the operating system by calling the Win32 VirtualFree function.
       - The fewer objects allocated on the heap, the less work the garbage collector has to do.
         - When a garbage collection is triggered, the garbage collector reclaims the memory that is occupied by dead objects. The reclaiming process compacts live objects so that they are moved together, and the dead space is removed, thereby making the heap smaller.
         - The intrusiveness (frequency and duration) of garbage collections is the result of the volume of allocations and the amount of survived memory on the managed heap.
      - The heap can be considered as the accumulation of two heaps: the large object heap and the small object heap.The large object heap contains objects that are 85,000 bytes and larger.        


Generations:
      - The heap is organized into generations so it can handle long-lived and short-lived objects. Garbage collection primarily occurs with the reclamation of short-lived objects that typically occupy only a small part of the heap. There are three generations of objects on the heap:
         Generation 0:
               - Youngest generation.
               - Contains short lived objects.
               - Example - Temporary variables / Local variable.
               - GC occurs most frequestly.
         Generation 1:
               - Contains short lived objects and servs as a buffer between short lived and long lived objects
         Generation 2:
               - Contains long lived objects
               - Example - Server application that contains static data that live for the duration of the process.
     - Collecting a generation means collection objects in that generation and all its younger generation.

     - The allocation of objects starts with Generation 0. when the Generation 0 is filled completely, a collect method is called and reclaims the unused memory. And now these objects are moved to Generation 1 in a continous memory allocation (thus utilising the memory the best way.). Similarly the Generation 1 objects are moved to Generation 2.


What happens during a Garbage Collection:
Phases:
     -Making Phase:
            Finds and creates a list of all live objects.
     -Relocating Phase:
            Updates the references to the objects taht will be compacted.
     -Compacting Phase:
            Reclaims the space occupied by the dead objects and compacts the surviving ojects.
    The large object heap is not compacted, as this would increase memory usage over an unacceptable leangth of time.


Types of Garbage Collection:
     - Workstation Garbage Collection:
              - Which is for all client workstation and stand alone PCs.
              - Can be concurrent or non concurrent.
              - Concurrent garbage collection enables managed threads to continue operations during a garbage collection.
              - Starting with .Net framework 4, background garbage collection replaces concurrent garbage collection.
      - Server Garbage Collection:
              - Which is intended for server applications that need high throughput and scalability.
              - Always non concurrent.


Configuring Garbage Collection:
       - To specify the type of garbage collectionuse  <gcServer> element with attribute enabled set to false/true. Default it is set to false. Thus workstation.
       - To specify concurrency / non concurrency, use <gcConcurrent > element with enable attribute set to false / true. Default it is enabled.
     




 

Tuesday, September 20, 2011

Methods to pass values between ASP.Net web pages

Whether or not the source and target pages in same applciation, the data can be passed by following methods
               1. Using query string
               2. Using Get HTTP Post information from the source page

Query string:
     - Can add values to the qusery string at the end of URL.
     - Never pass sensitive data using query string, as its always visible in the URL.
     - To retrieve the value S= Request.QueryString["QueryStringName"];    

Get HTTP Post information from the Source Page:
     - When the source page uses the HTTP Post action to navigate, can retrieve posted values from the FormCollection in the target page.
     - Can get only the post values, cannot read values of arbitarary controls on the page.

When the Source and Target are in same application, data can be passed by the following methods:
                1. Using session state
                2. Using Public property values from source page
                3. Getting control information from the source page in the same application.

Session state:
     - Informations in the session state are available to all pages in the current application, for the specified time.
     - Takes server memory.
     - Stored until the session is expired, which can be more overheaf than you want for simple passing information to teh next page.
     - To store and retrieve
               Session["SessionName"] = "Value";
               Value = Session["SessionName"].ToString();

Getting Public property values from Source page:
    - Add public properties in the source page that expose information you want to share between pages.
    - Read values of the properties in the target page.
    - It works in 2 situations:
            - When the source page cross posts to the target page.
            - When you call the Transfer method to transfer exception from the source to the target page on the server.

Getting control information from the Source page:
    - Can use this strategy if the source page does not expose public properties containing the information you want.
    - Ex. TextBox txt = (TextBox)PreviousPage.FindControl("id");

Methods to Redirect users to another page in ASP.Net

Using ASP.Net one can redirect to another page via the following methods:

            1. using Hyperlinks
            2. using Cross PAge Posting
            3. using Browser redirect Method
            4. using Server Transfer.

Hyperlinks:
   Charactaristics:
          - Performs new request on the target page.
          - Does not pass current page informations to the target page.
          - Requires users initiation
          - Can redirect to any page - Not just pages within application.
          - Can share information between pages using query string.
  Usage:
          - For navigation without any additional processing, as in menus or links of links.
          - When navigation should be under user control.

Cross Page Posting:
   Characteristics:
          - Post current page information to target page.
          - Makes post information available in target page.
          - Requires user initiation.
          - Can redirect to any page - Not just pages within application.
          - Enables the target page to read public properties of the source page, if the pages are in same application.
   Usage:
          - To pass current page information to target page (As in multi page forms)
          - When navigation should be under user control.

Browser Redirect:
    Characteristics:
          - Performs a new HTTP GET request on the target page.
          - Passes the query string, if any, to target page.( In IE the max size is  2048)
          - Provides programmatic and dynamic control over the target URL and query string.
          - Can redirect to any page - Not just pages within the application.
          - Can share information between source and target pages useing session state.
    Usage:
          - For conditional navigation when you want to control the target URL and control when navigation takes place.

Server Transfer:
     Characteristics:
          - Trasfers control to a new page that renders in place of the source page.
          - Redirects only to target pages taht are in the same web applciation as the source page.
          - Enables to read values and public properties from source page.
          - Doesnot update browser information with information about the target page. Pressing the refresh or back buttons in the browser can result in unexpected behaviour.
     Usage:
          - For conditional navigation, when you want to control when navigation takes place and you want access to the context of teh source page.
          - Best used when URL is hidden from the user.

Thursday, September 15, 2011

Association Aggregation & Composition

These terms signify the relationships between classes. These are the building blocks of object oriented programming and very basic stuff.


Association
Association is a relationship between two objects. In other words, association defines the multiplicity between objects. You may be aware of one-to-one, one-to-many, many-to-one, many-to-many all these words define an association between objects. Aggregation is a special form of association. Composition is a special form of aggregation.
Example: A Student and a Faculty are having an association.

Aggregation
Aggregation is a special case of association. A directional association between objects. When an object ‘has-a’ another object, then you have got an aggregation between them. Direction between them specified which object contains the other object. Aggregation is also called a “Has-a” relationship.

Composition
Composition is a special case of aggregation. In a more specific manner, a restricted aggregation is called composition. When an object contains the other object, if the contained object cannot exist without the existence of container object, then it is called composition.
Example: A class contains students. A student cannot exist without a class. There exists composition between class and students.

Difference between aggregation and composition
Composition is more restrictive. When there is a composition between two objects, the composed object cannot exist without the other object. This restriction is not there in aggregation. Though one object can contain the other object, there is no condition that the composed object must exist. The existence of the composed object is entirely optional. In both aggregation and composition, direction is must. The direction specifies, which object contains the other object.

Example: A Library contains students and books. Relationship between library and student is aggregation. Relationship between library and book is composition. A student can exist without a library and therefore it is aggregation. A book cannot exist without a library and therefore its a composition.

AutoEventWireup attribute in ASP.Net

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
The ASP.NET page framework supports an automatic way to associate page events and methods. If the AutoEventWireup attribute of the Page directive is set to true, the page framework calls page events automatically, specifically the Page_Init and Page_Load methods. In that case, no explicit Handles clause or delegate is needed.


• AutoEventWireup is an attribute in Page directive.

• AutoEventWireup is a Boolean attribute that indicates whether the ASP.NET pages events are auto-wired.

• AutoEventWireup will have a value true or false. By default it is true.

There is no event or method associated with Page_Load. Those events whose inline event is not there but that should be executed, for that purposed AutoEventWireup="true".

Disadvantages of AutoEventWireup attribute
• AutoEventWireup uses fixed naming convention for the events. Page events handlers have specific predictable names. This limits your flexibility in how you name event handlers.

• If you do set AutoEventWireup to true, Visual Studio will generate code to bind the events and the page framework will automatically call events based on their names. This can result in the same event code being called twice when the page runs. As a consequence, you should always leave AutoEventWireup set to false when working in Visual Studio.

• Another disadvantage is that performance is adversely affected, because ASP.NET searches for methods at run-time. For a Web site with high traffic volumes, the impact on performance could be significant.

AutoEventWireup="true" target is for page events only. In case of AutoEventWireup method are not case sensitive. (Page_Load or page_load both will work).

If AutoEventWireup="false" but still you want to executed Page event (Page_Load). In this you have to explicitly code for it.

<form id="form1" runat="server" onload="Page_Load">

Thursday, September 8, 2011

Difference between ADO and ADO.net

ADO - ActiveX Data Object.
The old ADO is evolved to ADO.Net in .Net Framework.

Differences are as follows:
1. ADO use connected data usage while ADO.Net uses disconnected data environment.
2. ADO uses OLE DB to access data and it  is COM based while ADO.Net uses xml as data formate for transmitting data to and from database and web application.
3. ADO Recordset has single table or a query result. While ADO.Net dataset can have multiple tables from any database.
4. ADO is sometimes problamatic, as Firewall prohibits many types of request. While in ADO.Net there is no such problems as xml is completly firwall proof.
5. In ADO we can't generate relation, while in ADO.Net we can generate relations.
6. In ADO's we cant generate SQL statements whereas in ADO.Net we can generate SQL statements.
7. In ADO's we can't send multiple transactions in a single instance whereas in ADO.Net we can send multiple transactions using single instance.

Wednesday, September 7, 2011

Difference between a.Equals(b) and a==b

Both '.Equals()' and '==' are used for comparison and returns a boolean value(true/false).
Differences are as follows:

1. '==' is used for Value type comparision.
       Ex. int a = 5;
             int b = 5;
             a==b => returns true
             a.Equals(b) => returns true

2. '==' returns true for Value type, only when both the value and the data types are same. .Equals() method returns true if the values are the same. the data type can be different.
      Ex. int a = 5;
            string b = "5";
            a.Equals(b) => Will compile succesfully, and internally the string b will be converted to object types and compare.
            a == b => Will give compilation error.
       By using '==' we cannot compare two objects.
       But .Equals() enables to compare both the objects internally.

3. For Value Type, both '==' and '.Equals()' compare two objects by value.

4. For Reference Type, '==' performs an identity comparison. ie. it will return true only if both references point to the same object. '.Equals()' performs and value comparison.i.e it will return true if the references point to the object that are equivalent.
        Ex. StringBuilder s1 = new StringBuilder("Yes");
              StringBuilder s2 = new StringBuilder("Yes");
              s1 == s2 => returns false.
              s1.Equals(s2) => returns true;

5. Recommendations:
       For Value type - use '=='
       For Reference type - use '.Equals()'

Tuesday, September 6, 2011

Error Handling in .NET

Following explains the guidelines of Error handling in .Net.

Exception:
     An exception is unexpected error or problem.

Exception Handling:
     Method to handle error and solution to recover from it, so that program works smoothly.

Try Block:
     -> Try Block consist of code that might generate error.
     -> Try Block must be associated with one or more catch block or by finally block.
     -> Try Block need not necessarily have a catch Block associated with it but in that case it must have a finally Block associate with it.

Catch Block:
     -> Catch Block is used to recover from error generated in try Block.
     -> In case of multiple catch Block, only the first matching catch Block is executed.
    -> When you write multiple catch block you need to arrange them from specific exception type to more generic type.
    -> When no matching catch block are able to handle exception, the default behavior of web page is to terminate the processing of the web page.

Finally Block:
     -> Finally Block contains the code that always executes, whether or not any exception occurs.
     -> When to use finally Block? - You should use finally block to write cleanup code. i.e. you can write code to close files, database connections, etc.
     -> Only One finally block is associated with try block.
     -> Finally block must appear after all the catch block.
     -> If there is a transfer control statement such as goto, break or continue in either try or catch block the transfer happens only after the code in the finally block is executed.
     -> If you use transfer control statement in finally block, you will receive compile time error.
 
Throw Statement:
     -> A throw statement is used to generate exception explicitly.
     -> Avoid using throw statement as it degrades the speed.
     -> Throw statement is generally used in recording error in event log or sending an email notification about the error.

Using Statement:
      -> Using statement is used similar to finally block i.e. to dispose the object.
      -> Using statement declares that you are using a disposable object for a short period of time. As soon as the using block ends, the CLR release the corresponding object immediately by calling its dispose() method

Is it a best practice to handle every error?
      -> No, it is not best practice to handle every error. It degrades the performance.
      -> You should use Error Handling in any of following situation otherwise try to avoid it.
            -> If you can able to recover error in the catch block
            -> To write clean-up code that must execute even if an exception occur
            -> To record the exception in event log or sending email.

Difference between catch(Exception ex) and catch:

try
{

}
catch(Exception ex)
{
     //Catches all cls-compliant exceptions
}
catch
{
     //Catches all other exception including the non-cls compliant exceptions.
}

Managing Unhandled Exception:
       You can manage unhandled exception with custom error pages in asp.net. You should configure the element in web.config file. It has two attributes:

            Mode Attribute: It specifies how custom error page should be displayed. It contains 3 values.
                  On - Displays custom error pages at both the local and remote client.
                  Off - Disables custom error pages at both the local and remote client.
                  RemoteOnly - Displays custom error pages only at the remote client, for local machine it displays default asp.net error page. This is default setting in web.config file.
           DefaultRedirect: It is an optional attribute to specify the custom error page to be displayed when an error occurs.
     You can display custom error page based on http error statusCode using error element inside the customeError element, in case the no specific statusCode match it will redirect to defaultRedirect page.


      < customErrors mode="RemoteOnly" defaultRedirect="~/DefaultErrorPage.htm" >
           < error statusCode="403" redirect="NoAccess.htm" />
           < error statusCode="404" redirect="FileNotFound.htm" />
      </customErrors >
     
Events fired on Unhandled Exception
      Two events fire in successive order on unhandled exception
             Page.Error() Event - Performing error handling at page level.
            Application.Error() Event - Performing error handling at application level.

Page.Error() Event
       Lets display error message for divide by error instead of display custom error page.
       Add the Page_Error() Event
protected void Page_Error(object sender, EventArgs e)
{
       Response.Write("Error: " + Server.GetLastError().Message + "");
       Server.ClearError();
}
      Server.GetLastError() method is used to display last error, while Server.ClearError() will clear the last exception and does not fire the subsequent error events. For this reason, you will notice that custom error page is not displayed even though there is unhandled error, and a default error message is displayed.

Application.Error() Event
      Application.Error Event is used to handle unhandled exception of entire application. This event lies in Global.asax file. You can use this event to send email for error or generate a text file or recording error information in database, etc.
      Here we will generate a text file in MyError directory of application and send email of same error to web master.
      So lets begin by adding namespace to global.asax
      For adding namespace to global.asax make use of import statement.

<%@ Import Namespace="System.IO" %>

<%@ Import Namespace="System.Net" %>
<%@ Import Namespace="System.Net.Mail" %>

       Now, add following code to Application_Error Event in Global.asax for generating error text file and sending error reporting email to webmaster in asp.net

void Application_Error(object sender, EventArgs e)
{
       Exception err = (Exception)Server.GetLastError().InnerException;
       //Create a text file containing error details
       string strFileName = "Err_dt_" + DateTime.Now.Month + "_" + DateTime.Now.Day
                  + "_" + DateTime.Now.Year + "_Time_" + DateTime.Now.Hour + "_" +
                  DateTime.Now.Minute + "_" + DateTime.Now.Second + "_"
                  + DateTime.Now.Millisecond + ".txt";
       strFileName = Server.MapPath("~") + "\\MyError\\" + strFileName;
       FileStream fsOut = File.Create(strFileName);
       StreamWriter sw = new StreamWriter(fsOut);
       //Log the error details
       string errorText = "Error Message: " + err.Message + sw.NewLine;
       errorText = errorText + "Stack Trace: " + err.StackTrace + sw.NewLine;
       sw.WriteLine(errorText);
       sw.Flush();
       sw.Close();
       fsOut.Close();
       //Send an Email to Web Master
       //Create Mail Message Object with content that you want to send with mail.
       MailMessage MyMailMessage = new MailMessage         ("dotnetguts@gmail.com","vivek_on_chat@yahoo.com",
       "Exception:" + err.Message, errorText);
        MyMailMessage.IsBodyHtml = false;
        //Proper Authentication Details need to be passed when sending email from gmail
        NetworkCredential mailAuthentication = new
        NetworkCredential("dotnetguts@gmail.com", "password");
       //Smtp Mail server of Gmail is "smpt.gmail.com" and it uses port no. 587
       //For different server like yahoo this details changes and you can
       //get it from respective server.
       SmtpClient mailClient = new SmtpClient("smtp.gmail.com",587);
       //Enable SSL
       mailClient.EnableSsl = true;
       mailClient.UseDefaultCredentials = false;
       mailClient.Credentials = mailAuthentication;
       mailClient.Send(MyMailMessage);
}

      On running the program and generating exception will create error file in MyError directory and will send email stating error to web master, And it will display custom error page to user

Difference between Close() and Dispose()

The basic difference between Close() and Dispose() is, when a Close() method is called, any managed resource can be temporarily closed and can be opened once again. It means that, with the same object the resource can be reopened or used. Where as Dispose() method permanently removes any resource ((un)managed) from memory for cleanup and the resource no longer exists for any further processing.

Generally the Dispose() is called in finally block.

vb script to execute the given URL and read the html code

The following script executes the give URL and returns the html code of it.

dim xmlhttp, url
url = "http://www.google.com"
set xmlhttp = CreateObject("MSXML2.ServerXMLHTTP")
xmlhttp.open "GET", url, false
xmlhttp.send ""
WScript.Echo xmlhttp.responseText
set xmlhttp = nothing


now store this as .vbs and execute