Difference between interface and abstract class in c#

Abstract class: An abstract class cannot be instantiated. The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share. For example, a class library may define an abstract class that is used as a parameter to many of its functions, and require programmers using that library to provide their own implementation of the class by creating a derived class.

Interface : An interface contains only the signatures of methods, properties, events or indexers. A class or struct that implements the interface must implement the members of the interface that are specified in the interface definition. In the following example, class ImplementationClass must implement a method named SampleMethod that has no parameters and returns void.

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 Modfiers An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as public An 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 Constants No fields can be defined in interfaces An abstract class can have fields and constrants defined
Read More »

Difference between String and Stringbuilder in Asp.net,C#

String
 

String is immutable, Immutable means if you create string object then you     cannot modify it and It always create new object of string type in memory.
 
Example
 

 string strValue = "Hello Friend";
 // create a new string instance instead of changing the old one
 strValue += "Are
You ";
 strValue += "Ready ?";
 
Stringbuilder
 

StringBuilder is mutable, means if create string builder object then you can perform any operation like insert, replace or append without creating new instance for every time.it will update string at one place in memory does not create new space in memory.

Example
 

 StringBuilder sbValue = new StringBuilder("");
 sbValue.Append("
Hello Friend");
 sbValue.Append("Are You
Ready ?");
 string strValue = sbValue.ToString();
 



String
StringBuilder
immutable
mutable
Performance wise string is slow because every time it will create new instance
Performance wise stringbuilder is high because it will use same instance of object to perform any action
don’t have append keywor
can use append keyword
belongs to System namespace
belongs to System.Text namespace


Read More »

ASP.NET Page Life Cycle

       An important article on the different methods and order they are executed during the load of an .aspx web page. ASP.NET.
In this article, we are going to discuss the different methods and order they are executed during the load of an .aspx web page.

        When a visitor first requests an .aspx page on your server, the server sends it to the HTTP Pipeline. The HTTP Pipeline handles all processes involved in converting all of the application code into HTML to be interpreted by the browser. The first class initiated is called HttpRuntime. This class finds a free HttpApplication object to start processing the request. The HttpApplication object then runs the appropriate handler assigned in the web.config and machine.config files for the requested extension.
The extension .aspx can be handled by the HandlerClass or HandlerFactory class. The HttpApplication objects starts the IHttpHandler interface which begins processing the application code by calling the processRequest() method.

      The processRequest() method then calls the FrameworkInitialize() method which begins building the control trees for the requested page. Now the processRequest() method cycles through the page’s life cycle in the order listed below.

PreInit 

   Use this event for the following:
  1. Check the IsPostBack property to determine whether this is the first time the page is being processed.
  2. Create or re-create dynamic controls.
  3. Set a master page dynamically.
  4. Set the Theme property dynamically.
  5. Read or set profile property values.
  6. Note: If the request is a postback, the values of the controls have not yet been restored from view state. If you set a control property at this stage, its value might be overwritten in the next event.







Init
  1. Raised after all controls have been initialized and any skin settings have been applied.
  2. Use this event to read or initialize control properties.

InitComplete
  1. Raised by the Page object.
  2.  Use this event for processing tasks that require all initialization be complete.
 PreLoad 
  1. Use this event if you need to perform processing on your page or control before the Load event.
  2. After the Page raises this event, it loads view state for itself and all controls, and then processes any postback data included with the Request instance.

 Load
  1. The Page calls the OnLoad event method on the Page, then recursively does the same for each child control, which does the same for each of its child controls until the page and all controls are loaded.
  2. Use the OnLoad event method to set properties in controls and establish database connections.

 Control events
  1. Use these events to handle specific control events, such as a Button control's Click event or a TextBox control's TextChanged event. 
  2. Note:In a postback request, if the page contains validator controls, check the IsValid property of the Page and of individual validation controls before performing any processing.
 LoadComplete 
  1. Use this event for tasks that require that all other controls on the page be loaded.
PreRender 
Before this event occurs:
  1. The Page object calls EnsureChildControls for each control and for the page.
  2. Each data bound control whose DataSourceID property is set calls its DataBind method. For more information, see Data Binding Events for Data-Bound Controls below.
The PreRender event occurs for each control on the page. Use the event to make final changes to the contents of the page or its controls.

 SaveStateComplete 
  1. Before this event occurs, ViewState has been saved for the page and for all controls. Any changes to the page or controls at this point will be ignored.
  2. Use this event perform tasks that require view state to be saved, but that do not make any changes to controls.

 Render 
  1. This is not an event; instead, at this stage of processing, the Page object calls this method on each control. All ASP.NET Web server controls have a Render method that writes out the control's markup that is sent to the browser.
  2. If you create a custom control, you typically override this method to output the control's markup. However, if your custom control incorporates only standard ASP.NET Web server controls and no custom markup, you do not need to override the Render method.

 Unload 
  1. This event occurs for each control and then for the page. In controls, use this event to do final cleanup for specific controls, such as closing control-specific database connections.
  2. For the page itself, use this event to do final cleanup work, such as closing open files and database connections, or finishing up logging or other request-specific tasks.
  3. Note:During the unload stage, the page and its controls have been rendered, so you cannot make further changes to the response stream. If you attempt to call a method such as the Response.Write method, the page will throw an exception.


Read More »

Replace Desired Charecter in String

Following is The function ,Use to replace the special Charecters in String by "_". 


 protected static string replaceBadChars(string input)  
     {  
       StringBuilder sb = new StringBuilder(input);  
       string[] chars = new string[27] { "%", " ", "&", "!", "`", "$", "*", "(", ")",  
         "{", "}", "[", "]", "/", "\\", "|", ";", "'", "\"", "<", ">", "?", "+", "#", "=", ".", "-" };  
       foreach (string st in chars)  
       {  
         sb.Replace(st, "_");  
       }  
       return sb.ToString();  
     }  
Read More »

How to add & access Connectionstring in .net


In app.config or web.config add the following code


 <configuration>  
  <connectionStrings>  
   <add name="Conn" connectionString ="Data Source=.\sqlexpress;Initial Catalog=SAM;User Id=sa;  
   Password=abc;integrated Security=true"/>  
  </connectionStrings>  
 </configuration>  


In codebehind file (.cs file) add the follwing line to access the connection string from config file

 string constring = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString.ToString();  


Note: for ConfigurationManager class add assembly refrence to refrence folder
Read More »

Download the pdf file on the server store in folder


Take link button in update panel.
Apply trigger to Link Button.
Write the Follwing Code in the link button click event.


 System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;  
         response.Clear();  
         response.AddHeader("Content-Disposition", "attachment; filename=" + "ABC.pdf" + ";");  
         response.ContentType = "application/excel";  
         response.TransmitFile("~//Downloadable//ABC.pdf");  
         response.End();  


Note: You can change 'response.ContentType = "application/excel";' for excel document,also change file name that u want to download from server folder(eg.ABC.pdf to ABC.csv).
Read More »

Add Resoluion Specific Media CSS

Add The follwing Code to Css file include the Class in that
you can change min & max width as per requirement.

@media screen and (min-width: 1100px) and (max-width:1300px)
{
         .abc
         {

          }
            #xyz
           {

            }
}
Read More »

How to Add Check Box Select,Select All, Unselect and Unselect All Functionality in Gridview Column


First Add Check Box column in Gridview as Follows
 <asp:GridView runat="server" ID="grv" AutoGenerateColumns="false" GridLines="Vertical"  
     BorderWidth="0" AllowPaging="true" PagerStyle-HorizontalAlign="Center" OnRowCreated="grvClassCaption_RowCreated">  
     <Columns>  
       <asp:TemplateField HeaderStyle-HorizontalAlign="Center" HeaderText="Select All" ItemStyle-HorizontalAlign="Center"  
         HeaderStyle-CssClass="GridHeader" ItemStyle-Width="200px">  
         <HeaderTemplate>  
           <asp:CheckBox ID="chkHeader" runat="server" Text="Select All" Onclick="SetCheckBoxes(this)" />  
         </HeaderTemplate>  
         <ItemTemplate>  
           <asp:CheckBox ID="chkBox" runat="server" Text="Select" Onclick="ChangeHeader()" />  
         </ItemTemplate>  
       </asp:TemplateField>  
       <asp:TemplateField HeaderStyle-HorizontalAlign="Center" HeaderText="Name" ItemStyle-HorizontalAlign="Center"  
         HeaderStyle-CssClass="GridHeader" ItemStyle-VerticalAlign="Top" ItemStyle-CssClass="GridColumn"  
         ItemStyle-Width="200px">  
         <ItemTemplate>  
           <asp:Label ID="lblName" runat="server" Text='<%# Eval("Name")%>'></asp:Label>  
         </ItemTemplate>  
       </asp:TemplateField>  
     </Columns>  
   </asp:GridView>  
   <div>  
     <asp:Button ID="Button1" runat="server" Text="SAVE" OnClick="BtnSave_Click" />  
   </div>  

And ADD Following Script to the header of page
 <script type="text/javascript">  
     function ChangeHeader()  
     {  
       var Parent = document.getElementById("<%=grv.ClientID %>");  
       var chkList = Parent.getElementsByTagName('input');  
       chkList[0].checked = true;  
       for (i = 1; i < chkList.length; i++) {  
         if (!chkList[i].checked) {  
           chkList[0].checked = false;  
         }  
       }  
     }  
     function SetCheckBoxes(chkHeader)   
     {  
       var Parent = document.getElementById("<%=grv.ClientID %>");  
       var chkList = Parent.getElementsByTagName('input');  
       if (chkHeader.checked) {  
         for (i = 0; i < chkList.length; i++) {  
           chkList[i].checked = true;  
         }  
       }  
       else {  
         for (i = 0; i < chkList.length; i++) {  
           chkList[i].checked = false;  
         }  
       }  
     }  
 </script>  

On SAVE button click Check the check box Condition
  protected void BtnSave_Click(object sender, EventArgs e)  
     {  
         int count = 0;  
         for (int i = 0; i < grv.Rows.Count; i++)  
         {  
           GridViewRow row = grv.Rows[i];  
           bool isChecked = ((CheckBox)row.FindControl("chkBox")).Checked;  
           if (isChecked)  
           {  
             count++;  
           }  
         }  
         if (count != 0)  
         {  
           SaveData(); //save the data to database  
         }  
 }  
Read More »

How to Apply IE Specific CSS in ASP.net Application

First add the following meta tags on master page or content page ,where we are using particular CSS class.

 <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />

 <!--[if IE 8 ]> <html class="ie8"> <![endif]-->

For eg. Class abc 

And in CSS file write class as follows
And write browser specific properties in this class.

.ie8 .abc
{

//class style here

}
Read More »

Function To Convert Object of List Type into Datatable Object


public DataTable ConvertToDataTable<T>(IList<T> data)
        {
            PropertyDescriptorCollection properties =
               TypeDescriptor.GetProperties(typeof(T));
          
            foreach (PropertyDescriptor prop in properties)
            {
              
                table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
              
            }
            foreach (T item in data)
            {
                DataRow row = table.NewRow();
                foreach (PropertyDescriptor prop in properties)
                    row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
                table.Rows.Add(row);
            }
            return table;
        }
Read More »

Create And Export Excel File in Asp.net


 /* IT EXPORT DATA FROM DATA TABLE */


 protected void btnExportfromDt_Click(object sender, EventArgs e)
        {
            string strFilename = "StudDetails.xls";
            Export(LoadData(), strFilename);
        }
        protected void Export(DataTable dtEmp,string filename)
        {
            string attachment = "attachment; filename="+filename;
            Response.ClearContent();
            Response.AddHeader("content-disposition", attachment);
            Response.ContentType = "application/vnd.ms-excel";
            string tab = string.Empty;
            foreach (DataColumn dtcol in dtEmp.Columns)
            {
                Response.Write(tab + dtcol.ColumnName);
                tab = "\t";
            }
            Response.Write("\n");
            foreach (DataRow dr in dtEmp.Rows)
            {
                tab = "";
                for (int j = 0; j < dtEmp.Columns.Count; j++)
                {
                    Response.Write(tab + Convert.ToString(dr[j]));
                    tab = "\t";
                }
                Response.Write("\n");
            }
            Response.End();
        }

Note :For Visual Studio 10 use Trigger Tag For Update Panel To Download The File;
Read More »

How to generate Database Script in SQL Server 2005/08


 Open SQL Server  Management Studio.

1. Right-click the database (note not the table)

2. Choose Tasks > Generate Scripts

3. In the Choose Objects pane, select the table you want to script

4. In the Set Scripting Options pane, click Advanced.

5. In the Types of Data to Script option, choose Schema and Data. (If you also want indexes, etc. make sure they are also chosen)

Click your way through the remaining screens and you're done.
Read More »