Pages

Friday, November 18, 2011

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

Friday, August 26, 2011

Abstract Class and Interface

Abstract Class:
     An abstract class is a special kind of class that cannot be instantiated. i.e. It only allows other class to inherit from but it cannot be instantiated.

    Advatage:
         Enforces certain hierarchies for all the subclasses. ie. It is a kind of contract that forces all the subclasses to carry on the same hierarchies or standards.

Interface:
    An interface is not a class. It is an entity that is defined by the name interface. An interface has no implementation. It is only the signature or just definition of the methods without the body. It is a kind of contract that is used to define the hierarchies for all the subclasses or it defines specific set of methods and arguments. As c# does not support multiple inheritance, interface are used to implement multiple inheritance.

Purpose of Abstract class and Interface:
    When we create an interface, we basically create a set of methods without any implemention which must be overridden by the inherited class. Advantage is that, it provides a way for a class to be part of two classes: one from inheritance hirearchy and one from the interface.
    When we create an abstract class, we are creating a base class that might have one or more implemented methods and atleast one or more methods are left without implementing and declared abstract. The purpose of an abstract class is to provide a base class definition of how aset of derived class will work.

Interface and Abstract class - Comparison

Feature


Interface


Abstract Class

Multiple inheritance

A class may inherit several interfaces.

A class may inherit only one abstract class.

Default implementation

An interface cannot provide any code, just the signature.

An abstract class can provide complete, default code and/or just the details that have to be overridden.
Access ModfiersAn interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as publicAn abstract class can contain access modifiers for the subs, functions, properties

Core VS Peripheral

Interfaces are used to define the peripheral abilities of a class. In other words both Human and Vehicle can inherit from a IMovable interface.

An abstract class defines the core identity of a class and there it is used for objects of the same type.

Homogeneity

If various implementations only share method signatures then it is better to use Interfaces.

If various implementations are of the same kind and use common behaviour or status then abstract class is better to use.

Speed

Requires more time to find the actual method in the corresponding classes.

Fast

Adding functionality (Versioning)

If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method.

If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.
Fields and ConstantsNo fields can be defined in interfacesAn abstract class can have fields and constrants defined

Tuesday, July 12, 2011

Delegates and Anonymous Methods in c#.net

Anonymous Method:
        It is a method without any name.i.e. A normal method is one which will have a name, a return type, optionally arguments and an access modifier. So an anonymous method is a feature to have methods without name.

Where should i use an Anonymous method??
        Anonymous method could be used in place where there is a use of delegate.

Delegate:
        A delegate is similar to function pointer in C++ and C. A function pointer in C is a variable that points to a function. Similarly a delegate is a reference type in .net that is used to call the methods of similar signature as of the delegate.
Ex.
void PrintName(string name)
{
       Response.Write("Name is " +  name  + "<\br>");
}
To call the above method using delegate, we should declare a delegate with similar signature.
Ex.
delegate void DelegateTest(string n);

Before calling we should initialize or register the delegate with the method.
Ex. 
DelegateTest del = new DelegateTest (this.PrintName);

Finally, can call the function by,
Del("Malathy");

The difference between the function pointer in C language and a delegate is, at a given time a function pointer can point to a single funtion only. But delegate are by default they are multicast delegate. ie. they can be used to call multiple functions at a time.

Ex. Consider the function,
void PrintAddress(string address)
{
       Response.Write("City he lives is " + address);
}
To call both PrintName and PrintAddress using delegate, declare as follows.
DelegateTest del = new DelegateTest (this.PrintName);
del += new DelegateTest (this.PrintAddress);
del("Chidambaram");

Now the output is,
Name is Chidambaram.
City he lives is Chidambaram.

By the use of += operator we add new methods to delegates. Thus += operator is used to register a function and -= will remove the registration from the delegate.

Delegate del = new DelegateTest(this.PrintName);
del += new DelegateTest(this.PrintAddress);
del -=  new DelegateTest(this.PrintAddress);
del("Chidambaram");

Now the output is
Name is Chidambaram.

The other difference between a delegate and a function pointer is, a delegate is a type safe, ie.it will throw a compilation error if a method with different signature is assigned to the delegate.

Other than the above examples, the delegates are used in event handling, for callbacks ets. For example, in Webform designer code in VS, there will be,
btnCheck.Click += new EventHandler(this.btnCheck_Click);
Here the event handler is a delegate that is registered with btnCheck_Click event.

Anonymous Methods
        The syntax consists of the keyword delegate, an optional parameter list and method body enclosed in parenthesis.
Ex.
delegate(Optional parameters)
{
     Body of the method.
}

Where to use Anonymous Methods??
       The anonymous representation to implement the PrintName method will be,
delegate void DelegateTest(string n);
protected void Page_Load(object sender, EventArgs e)
{
     DelegateTest PrintName = delegate (String Name)
     {
           Response.Write("Name is " + Name );
     };
}
 
Can be called by
PrintName("Malathy");

And the outpt is
Name is Malathy.

Similar to delegate, we can use += operator to call multiple methods.
Ex.
delegate void DelegateTest (string n);
protected void Page_Load(Object sender, EventArgs e)
{
      DelegateTest test = delegate (StringName)
      {
             Response.Write("Name is " + Name );
      };
      test += delegate (String Address)
      {
            Response.Write("City he lives is " + Address);
      };
      test("Chidambaram");
}

The output is
Name is Chidambaram
City he lives is Chidambaram

An anonymous method without any argument will be like,

delegate void DelegateTestWithoutParam();
protected void Page_Load (object sender, EventArgs e)
{
      DelegateTestWithoutParam delparam = delegate()
      {
            Response.Write("Parameterless anonymous method");
            Response.Write("Name is Malathy");
      };
      delparam();
}

Here the output will be,
Name is Malathy.


Use of Anonymous Methods in Event Handling:
        We can use anonymous methods for events like button click, .
Ex.
btnCheck.Click += new EventHandler(this.btnCheck_Click);
Here btnClick is expecting a delegate and hence we can use anonymous methods. So the event can be written as,
protected void Page_Load(object sender, EventArgs e)
{
       btnClick.Click += delegate(object s, EventArgs ee)
       {
             Response.Write ("Name is Malathy");
        };
}

Here the output on clicking the button is
Name is Malathy.

Important Notes:
1. If a variable is declared outside the anonymous method then, it can be accessed inside the anonymous method.
2. Variables declared inside the anonymous methods are not accessible outside the anonymous method.
3. When a anonymous mehtod is declares without parenthesis, then it can be assigned to a delegate with any signature.


In short:
    We can define an anonymous method as a method without name which allows us to define the body inline.

Why should we use Anonymous Method???
     We can reduce the code by preventing delegate instantiation and registering it methods.
      It increases the readability and maintainability of our code by keeping the caller of the method and the method itself as close to one another as possible.

Thursday, July 7, 2011

Retrieve unique column values from a datatable

This blog explains how to retrieve unique column values from the given System.datatable.

For example assume that the datatable contains the values as follows:
Now when you want to retrieve the unique values of Col3, then it can be achieved as follows.

This code returns the unique column values of the "Col3". Thus the datatable dt2 contains the unique values of  column "Col3" from the dt table.

Retrieve the Filtered records in the form of datatable from the given system.datatable.

In some cases we require to retrieve the records from system.datatable using some Filter criteria and store back in a new datatable. This can be done by the following code.
For example assume that the datatable dt contains the values as follows.
Now to add filter to the dt we use, dt.Select("Filter condition"); But this would return as array of rows only. But when you want return records as datatable we get the help of DataSet as follows:
Thus we get the resultant records in the form of datatable. :) :)

Wednesday, July 6, 2011

Basics of DBMS

Data Base Management System:
        DBMS are collection of tools to manage databases. The four basic functions performed by all DBMS are
            1. Create, Modify, Delete data structures, e.x. tables
            2. Add, Modify, Delete data.
            3. Retrieve data selectively.
            4. Generate reports based on data.

Database:
       A database is a collection of related tables. It can also include other objects like queries, forms and reports. The structure of database is the relationships between its tables.

Components of Database:
       Databases are composed of related tables, which in turn are composed of fields and records.
Field:
       Field is an area( within a record) reserved for a specific piece of data.
       Fields are defined by
               - Field name
               - Data type
               - Field size.
Record:
       It is the collection of values for all the fields pertaining to one entity.
Table:
       It is a collection of related records. In a table records are represented as rows and fields are represented as columns.

Relationships:
       There are 3 types of relationships which can exist between tables:
              - One to One
              - One to Many
              - Many to Many
        Most common relationships in a relational database are One to Many and Many to Many
        Example of One to Many - Customer table and Order table. Each order has only one customer, but a customer can take many orders. They contain 2 tables - the "one" table and "many" table
        Example of Many to Many -  Order and Purchase tables.An order can contain many products and a product can be on many orders. They contain 3 tables.two "one" tables, both in One to Many relationship with the third table.

Database Normalization:
       Normalization is the process of efficiently organizing data in a database.
Goals:
       - Eliminating redundant data
       - Ensuring data dependencies make sense.

Normal Forms:
       The database community has developed a series of guidelines for ensuring that databases are normalized. These are referred to as normal forms and are numbered from one through five.
First Normal Form:
        - Eliminates duplicate columns from the same table.
        - Create separate table for each group of related data and identify each row with a unique column or set of columns (Primary key).
Second Normal Form:
        Address the concept of removing duplicate data.
        - Should be in first normal form.
        - Remove subsets of data that apply to multiple rows of a table and place them in separate tables.
        - Create relationships between these new tables and their predecessors through the use of foreign keys.
Third Normal Form:
        - Meet all requirements of second normal form.
        - Remove columns that are not dependent on the primary key.

Tuesday, July 5, 2011

Method To Check For Record Existence Before Inserting in DB.

In some data base management applications, while creating a new record, we would require to check for any duplication's. i. before inserting we need to check whether the record already exist or not.
This could be handled in 3 different ways.

For example say you need to add new department details. and before inserting check whether the depart already exist or not by using the department name.

Method 1:
     - From code behind (.cs) file, make a call to DB and execute a select statement with where condition to the department name. And in the .cs file have a if condition and check for the no of rows in the returned value.
     - If the row count is 0, then make a call to insert the record.
     - If the row count is more than 1, then return a message saying record already exist.

Method 2: This works out only when the DB is normalized. ie. the table should have a primary key.
     - From the code behind make a call to insert the record, and have this part inside the try catch block. Now if the record doesn't exist, then it gets added successfully, else it throws an exception of primary key constraint. Now this could be got in catch block and give a message saying the record already exist.

Method 3: works out when we use stored procedure for inserting.
     - In the SP, have an "if not exists" condition before the execution of insert command.
ex.

     - We just need to have IF NOT EXISTS condition before insert. Similar to having a if condition in the stored procedure.

Building DAL using Strongly typed data-sets in ASP.Net and SQL Server.

This post explains an sample of implementing strongly typed data set using ASP.Net and SQL server as back-end database.
for an example, we create a DAL class using class library template and add the required strongly typed data set and the code behind to access.
Finally to access these DAL methods, we create a reference of this in our web application and then call the required methods.

Now to implement DAL, the steps are as follows:
1. Create a Class library project and name it as DAL.
2. Include Strongly typed Data set:
        - right click on the project and give Add - > new item.
        - Under Data templates, select DATASET template and specify the name as Sample, and finally give add.

        - Now it includes a new data set (Sample.xsd) to the project.
3. Create connection to SQL server and include the table, queries, stored procedures.
        - To include a store procedure or a query for a corresponding table in sql server, we need to create a data table and table adapter.
        - All attribute details gets stored in the data table and the methods which define the query execution or the stored procedure execution are defined in the table adapter.
        - To add a new table adapter, right click on the xsd, and give Add-> Table Adapter.
       - Now specify the Connection string to get connected with the data base. The already used connection string gets populated in the Connection string drop down. If the required connection string does not exist in the drop down list, then click on the "New Connection" and make a new connection. Then click on next.
 
       - Need to choose the command type. Here we have three options. One - to create a new query, second -  to create a new stored procedure, and finally use the existing stored procedure defined in the corresponding   data base server.Select the required one. For sample, i select the Use existing stored procedure.Then click on Next.

       - Now we need to specify the stored procedures to the commands. Here we have 4 types of command types. Those are the Select, Insert, Update, Delete. And the stored procedures that exist in the given server gets binded to the drop down list of each command.   Every table adapter should contain at least one select command. i.e No table adapter exist without an select command.
         For this sample i just select one of the read stored procedure for the select command.

      -  Specify the methods to be generated. Also give the method name. By default we have Fill and Get methods. For our example, i select only the Get method, and give the method name as "ReadEmployees". And click on next.

      - In the final wizard just click on Finish. This will generate the specified get method, also the default select and update methods. One can access these methods using the object of table adapter.

       - This results in creating a new data table and table adapter along with the methods defined.

  4.Include a class to access the methods defined in the table adapter.
           - Right click the project and give Add - > New item. And select Class under Code template. Name this class as Datahelper.cs
           - Define this class as public as it could be accessible from other class as well.
           - Declare user defined static methods which executes the methods defined in the table adapter.
           - To access the methods, we need to declare an object of the table adapter and this object contains all the methods defined. The returned value is fetched and passed.
           - A sample code snippet resembles as follows

 Similarly it could be done for insert, update and delete.

Thus this makes DAL ready. And it could be used from any class by having a reference to it.