Pages

Thursday, December 8, 2011

Generate Thumbnail Images and Maintain Aspect Ratio

public class ThumbnailGenerator
    {
        /// <summary>
        /// Generates the thumbnail of given image.
        /// </summary>
        /// <param name="actualImagePath">The actual image path.</param>
        /// <param name="thumbnailPath">The thumbnail path.</param>
        /// <param name="thumbWidth">Width of the thumb.</param>
        /// <param name="thumbHeight">Height of the thumb.</param>
        public static void Generate(string actualImagePath, string thumbnailPath, int thumbWidth, int thumbHeight)
        {
            Image orignalImage = Image.FromFile(actualImagePath);
 
            // Rotating image 360 degrees to discart internal thumbnail image
            orignalImage.RotateFlip(RotateFlipType.Rotate180FlipNone);
            orignalImage.RotateFlip(RotateFlipType.Rotate180FlipNone);
 
            // Here is the basic formula to mantain aspect ratio
            // thumbHeight   imageHeight     
            // ----------- = -----------   
            // thumbWidth    imageWidth 
            //
            // Now lets assume that image width is greater and height is less and calculate the new height
            // So as per formula given above
            int newHeight = orignalImage.Height * thumbWidth / orignalImage.Width;
            int newWidth = thumbWidth;
 
            // New height is greater than our thumbHeight so we need to keep height fixed and calculate the width accordingly
            if (newHeight > thumbHeight)
            {
                newWidth = orignalImage.Width * thumbHeight / orignalImage.Height;
                newHeight = thumbHeight;
            }
 
            //Generate a thumbnail image
            Image thumbImage = orignalImage.GetThumbnailImage(newWidth, newHeight, null, IntPtr.Zero);
 
            // Save resized picture
            var qualityEncoder = System.Drawing.Imaging.Encoder.Quality;
            var quality = (long)100; //Image Quality 
            var ratio = new EncoderParameter(qualityEncoder, quality);
            var codecParams = new EncoderParameters(1);
            codecParams.Param[0] = ratio;
            //Right now I am saving JPEG only you can choose other formats as well
            var codecInfo = GetEncoder(ImageFormat.Jpeg);
 
            thumbImage.Save(thumbnailPath, codecInfo, codecParams);
 
            // Dispose unnecessory objects
            orignalImage.Dispose();
            thumbImage.Dispose();
        }
 
        /// <summary>
        /// Gets the encoder for particulat image format.
        /// </summary>
        /// <param name="format">Image format</param>
        /// <returns></returns>
        private static ImageCodecInfo GetEncoder(ImageFormat format)
        {
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.FormatID == format.Guid)
                {
                    return codec;
                }
            }
            return null;
        }
    }

Call as :
ThumbnailGenerator.Generate(@"C:\images\Picture.jpg", @"C:\images\PictureThumb.jpg", 100, 150);

Print contents of Div using Javascript

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <script language="javascript" type="text/javascript">
        function printDiv(divID) {
            //Get the HTML of div
            var divElements = document.getElementById(divID).innerHTML;
            //Get the HTML of whole page
            var oldPage = document.body.innerHTML;
           
            //Reset the page's HTML with div's HTML only
            document.body.innerHTML = "<html><head><title></title></head><body>" + divElements + "</body>";
           
            //Print Page
            window.print();
           
            //Restore orignal HTML
            document.body.innerHTML = oldPage;
           
            //disable postback on print button
            return false;
        }
    </script>
    <title>Div Printing Test Application by Zeeshan Umar</title>
</head>
<body>
    <form runat="server">
    <asp:Button ID="btnPrint" runat="server" Text="Print" OnClientClick="return printDiv('div_print');" />
    <div id="garbage1">I am not going to be print</div>
    <div id="div_print"><h1 style="color: Red">Only Zeeshan Umar loves Asp.Net will be printed :D</h1></div>
    <div id="garbage2">I am not going to be print</div>
    </form>
</body>

Wednesday, December 7, 2011

Asp.net Cache Sliding Expiration and Absolute Expiration

Asp .Net provides two different ways to expire the cache on the basis of time. Here are two aproaches:-
  1. Sliding Expiration
  2. Absolute Expiration 
1. Absolute Expiration
Absolute expiration means that your data will be removed from cache after fixed amount of time either it is accessed or not. Generally we use it when we are displaying data which is changing but we can afford to display outdated data in our pages.  Mostly I put all of my dropdown values in cache with Absolute Expiration. Here is how you can code:-


 
DataTable dt = GetDataFromDatabase();
Cache.Insert("AbsoluteCacheKey", dt, null,
DateTime.Now.AddMinutes(1), //Data will expire after 1 minute
System.Web.Caching.Cache.NoSlidingExpiration);

2. Sliding Expiration
Sliding expiration means that your data will be removed from cache if that is not accessed for certain amount of time. Generally we store that data in this cache mode which is accessed many time on certain occasions. For example if you go in account settings section of a site, then you will be frequently accesing account information in that section. But most of the time you wont be using account setting's related data so there is no point of storing that data in cache. In such scenarios sliding expiration should be used. here is how you can save data in cache with sliding expiration:-
DataTable dt = GetDataFromDatabase();
Cache.Insert("SlidingExpiration", data, null,
System.Web.Caching.Cache.NoAbsoluteExpiration,
TimeSpan.FromMinutes(1));//Data will be cached for 1 mins

Hopefully this information will be useful for you

Friday, November 25, 2011

Code for displaying columns of the gridview based on the columns checked in the Listbox.

Here is the code for displaying columns of the gridview based on the columns checked in the Listbox. This will by default display one column in the gridview and one checkbox ticked in checkbox list. On selecting other checkboxes i.e. firstname, last name, age,gender the columns become visible in the gridview.
<div>
<asp:CheckBoxList ID="chkColumns" runat="server">
</asp:CheckBoxList>
<asp:Button ID="btnShow" runat="server" Text="Show" OnClick="btnShow_Click" />
</div>
<a href="javascript:void(0);">Click</a>
<asp:GridView ID="GridView1" AutoGenerateColumns="false" runat="server">
<Columns>
    <asp:BoundField DataField="id" HeaderText="id" />
</Columns>
</asp:GridView>

    public static DataTable dt;// = new DataTable();
    public static ArrayList existing = new ArrayList();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            createtable();
        }
    }
    private void createtable()
        {
            dt = new DataTable();
            dt.Columns.Add("id");
            dt.Columns.Add("firstname");
            dt.Columns.Add("lastname");
            dt.Columns.Add("age");
            dt.Columns.Add("gender");
            object[] d1 = {"1","a","a1","10","M" };
            object[] d2 = { "2", "b", "b1", "20", "F" };
            object[] d3 = { "3", "c", "c1", "30", "M" };
            object[] d4 = { "4", "d", "d1", "40", "F" };
            dt.Rows.Add(d1);
            dt.Rows.Add(d2);
            dt.Rows.Add(d3);
            dt.Rows.Add(d4);
            GridView1.DataSource = dt;
            GridView1.DataBind();
            bindCheckbox();
            AddVisibleColumnsToArray();
            MarkCheckedInArrayForVisibleColumns();
        }
    private void bindCheckbox()
        {
            chkColumns.DataSource = dt.Columns;
            chkColumns.DataBind();
    }
    private void AddVisibleColumnsToArray()
        {
            GetColumnByDBName(GridView1);
        }
        private void MarkCheckedInArrayForVisibleColumns()
        {
            foreach (ListItem item in chkColumns.Items)
            {
                if (existing.Contains(item.Value))
                    item.Selected = true;
            }
        }
    protected void btnShow_Click(object sender, EventArgs e)
        {
            ArrayList arr =new ArrayList();
            HideGridviewColumns(GridView1,arr);
            foreach (ListItem item in chkColumns.Items)
            {
                if (item.Selected)
                {
                    BoundField b = new BoundField();
                    b.DataField = item.Value;
                    b.HeaderText = item.Value;
                    GridView1.Columns.Add(b);
                }
            }
            GridView1.DataSource = dt;
            GridView1.DataBind();
            AddVisibleColumnsToArray();
            MarkCheckedInArrayForVisibleColumns();
    }
    public void GetColumnByDBName(GridView aGridView)
        {
            existing.Clear();
            System.Web.UI.WebControls.BoundField DataColumn;
   
            for (int Index = 0; Index < aGridView.Columns.Count; Index++)
            {
                DataColumn = aGridView.Columns[Index] as System.Web.UI.WebControls.BoundField;
   
                if (DataColumn != null)
                {
                    if (DataColumn.Visible)
                    {
                        if (!existing.Contains(DataColumn.HeaderText))
                            existing.Add(DataColumn.HeaderText);
                    }
                }
            }
        }
   

Tuesday, November 22, 2011

Get XML node and node attribute value

XmlDocument webConfig = new XmlDocument();
        webConfig.Load(HttpContext.Current.Server.MapPath(@"~\web.config"));
        XmlNode node = webConfig.SelectSingleNode("/configuration/system.web/authentication/forms");
        node.Attributes["timeout"].Value;

        node.Value;

       

Forms Authentication for folders with different login page

Folder Structure:

Admin(Folder)
--Default.aspx
--Login.aspx
--Web.Config
User(Folder)

--Default.aspx
--Login.aspx
--Web.Config
Default.aspx
Login.aspx
Web.Config


The problem is as follows:
If a visitor try to access a page in Admin folder he must be redirected to login page located in Admin folder, here his username and password will be checked in SQL Server table, if authenticated then he will be redirected to Default page and he can access any page in Admin folder, but not the pages in User folder
Note: login page in Admin folder and login page in User folder are different.
Same scenario is for User folder

Solution:Here are the steps to follow:
1. Put following lines in /Admin/Web.config file<configuration>
 <location path="Login.aspx">
  <system.web>
   <authorization>
    <allow users="?"/>
   </authorization>
  </system.web>
</location>
</configuration>
2. Put following lines in /User/Web.config file
<configuration>
 <location path="Login.aspx">
  <system.web>
   <authorization>
    <allow users="?"/>
   </authorization>
  </system.web>
 </location>
</configuration>
3. Put following lines in Web.config file (root). Here Login.aspx page is placed at the root path (Note: loginUrl here is the Login page located on the root path)
<authentication mode="Forms">
 <forms name="login" timeout="120" slidingExpiration="false" loginUrl="Login.aspx"></forms>
</authentication>
<location path="Admin">
 <system.web>
  <authorization>
 <allow roles="Admin"/>
 <deny users="*"/>
  </authorization>
 </system.web>
</location>
  <location path="User">
    <system.web>
      <authorization>   
        <allow  roles="User"/>
        <deny users="*"/>
      </authorization>
    </system.web>
  </location>
  <location path="Default.aspx">
    <system.web>
      <authorization>
        <allow users="*"/>
      </authorization>
    </system.web>
  </location>
4. Put following code only in the Login.aspx page located on the root path
protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["ReturnUrl"] != null && Request.QueryString["ReturnUrl"].ToString().Length > 0)
        {
            string returnUrl = Request.QueryString["ReturnUrl"].ToString();
            if (returnUrl.ToLower().Contains("/user/"))
            {
                Response.Redirect(string.Format("~/user/Login.aspx?ReturnUrl={0}", returnUrl));
            }
            if (returnUrl.ToLower().Contains("/admin/"))
            {
                Response.Redirect(string.Format("~/admin/Login.aspx?ReturnUrl={0}", returnUrl));
            }
        }
    }
5. On the Login.aspx page under Admin & User folder do the authentication and put following line at the end of button click.HttpContext.Current.Response.Redirect(FormsAuthentication.GetRedirectUrl(userName, createPersistentCookie));

6. And finally put following code for both signOut and redirect accordingly.
 FormsAuthentication.SignOut();
        Response.Redirect("~/admin/Login.aspx");
        or
        FormsAuthentication.SignOut();
        Response.Redirect("~/user/Login.aspx");


Hoping that this might help!       
 


Friday, November 11, 2011

Hide Gridview column

static public void HideGridviewColumns(GridView aGridView,ArrayList arrColumnName)
    {
        System.Web.UI.WebControls.BoundField DataColumn;
        if (arrColumnName.Count > 0)
        {
            for (int Index = 0; Index < aGridView.Columns.Count; Index++)
            {
                DataColumn = aGridView.Columns[Index] as System.Web.UI.WebControls.BoundField;

                if (DataColumn != null)
                {
                    DataColumn.Visible = !arrColumnName.Contains(DataColumn.HeaderText);

                }
            }
        }
        else
        {
            for (int Index = 0; Index < aGridView.Columns.Count; Index++)
            {
                DataColumn = aGridView.Columns[Index] as System.Web.UI.WebControls.BoundField;

                if (DataColumn != null)
                {
                    DataColumn.Visible = false;
                }
            }
        }
    }

Get ColumnIndex By DataColumn and HeaderText in Gridview

static public int GetColumnIndexByDBName(GridView aGridView, String ColumnText)
    {
        System.Web.UI.WebControls.BoundField DataColumn;

        for (int Index = 0; Index < aGridView.Columns.Count; Index++)
        {
            DataColumn = aGridView.Columns[Index] as System.Web.UI.WebControls.BoundField;

            if (DataColumn != null)
            {
                if (DataColumn.DataField == ColumnText)
                    return Index;
            }
        }
        return -1;
    }

static public int GetColumnIndexByHeaderText(GridView aGridView, String ColumnText)
    {
        TableCell Cell;
        for (int Index = 0; Index < aGridView.HeaderRow.Cells.Count; Index++)
        {
            Cell = aGridView.HeaderRow.Cells[Index];
            if (Cell.Text.ToString() == ColumnText)
                return Index;
        }
        return -1;
    }

Thursday, October 27, 2011

Send email from classic asp using CDO

<% 
 Dim myMail,HTML,msg
 dim dbn
 dbn="../yourdbpath/Database.mdb"

 ID = Request("ID")
 fromAddress = Request.Form("fromAddress")
 Set cn = Server.CreateObject("ADODB.Connection")

 cn.provider="microsoft.jet.oledb.4.0"
 cn.connectionstring=server.mappath(dbn)
 cn.open
 'cn.Open cstring

 q = "SELECT * FROM users WHERE userid LIKE '" & fromAddress & "'"
 Set rs = cn.Execute(q)

 if rs.EOF then
  Response.write "<font color=""brown"" >Sorry! You have entered wrong Email Address or Email address not in the list.  </font>"
 else
  password=rs("password")

  msg = "User password helper! " & chr(10) & chr(10)
  msg = msg & "Please Use below password to login to user area " & Title & chr(10)
  msg = msg & "EmailAddress: " & fromAddress & chr(10)
  msg = msg & "Password: " & password & chr(10)

  Set myMail = Server.CreateObject("CDO.Message") 
  Dim cdoConfig 
  Set cdoConfig = myMail.Configuration 
  With cdoConfig.Fields 
  .Item("
http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 
  .Item("
http://schemas.microsoft.com/cdo/configuration/smtpserver") = "mail.server.com" 
  .Item("
http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25 
  '*** Authentication ***' 
  .Item ("
http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1 
  .Item ("
http://schemas.microsoft.com/cdo/configuration/sendusername") = "username" '*** User ***' 
  .Item ("
http://schemas.microsoft.com/cdo/configuration/sendpassword") = "password" '*** Password ***' 
  .Item ("
http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = 30 
  .Update 
  End With 

  myMail.Configuration = cdoConfig
  myMail.From = "from@site.com"
  myMail.To   = fromAddress
  myMail.Subject =   "User password !"
  myMail.HTMLBody = msg 

  myMail.Send 
  Set myMail = Nothing 
  Response.write "<font color=""brown"" >Your pasword has been sent to your Email Address.. Pls check after some time. In case any problem Please contact the administrator </font>"
 end if
%> 

Wednesday, October 19, 2011

Add or Remove apostrophe to cell in active excel sheet

Option Explicit
Sub DeathToApostrophe()
    Dim s As Range, temp As String
    If MsgBox("Are you sure you want to remove all leading apostrophes from the entire sheet?", _
    vbOKCancel + vbQuestion, "Remove Apostrophes") = vbCancel Then Exit Sub
    Application.ScreenUpdating = False
    For Each s In ActiveSheet.UsedRange
        If s.HasFormula = False Then
             'Gets text and rewrites to same cell without   the apostrophe.
            s.Value = s.Text
        End If
    Next s
    Application.ScreenUpdating = True
End Sub


Sub AddApostrophes()
    Dim cel As Range
    Dim strw As String
    
    strw = "You cannot undo this task."
    strw = strw & " You may want to save your work to a new file."
    strw = strw & " Press OK to proceed, Cancel to quit."
    If vbCancel = MsgBox(strw, vbOKCancel + vbCritical, "Task Cannot Be Undone") Then Exit Sub
    
    For Each cel In ActiveSheet.UsedRange
        cel.Value = "'" & cel.Value
    Next cel
End Sub


How to use
  1. Copy above code.
  2. In Excel press Alt + F11 to enter the VBE.
  3. Right-click desired file on left.
  4. Choose Insert -Module.
  5. Paste code into the right pane.
  6. Press Alt + Q to close the VBE.
  7. Save workbook before any other changes. 
Test the code
  1. Ensure Active sheet is the desired sheet.
  2. Press Alt + F8.
  3. Choose 'DeathToApostrophe'.
  4. Press 'Run'.
  5. Confirm with 'Ok' to run.

Tuesday, August 2, 2011

Create dynamic GridView

using System;
using System.Web.UI;
using System.Web.UI.WebControls;

public class TemplateHandler : ITemplate
{
    void ITemplate.InstantiateIn(Control container)
    {
        Button  cmd= new Button();
        cmd.ID = "cmd";
        cmd.Text = "HI";
        cmd.Click += new EventHandler(Dynamic_Method);
        container.Controls.Add(cmd);
    }

    protected void Dynamic_Method(object sender, EventArgs e)
    {
        ((Button)sender).Text = "Hellooooo";
    }
}

protected void Page_Load(object sender, EventArgs e)
    {
        DataTable dt = new DataTable();

        dt.Columns.Add("FirstName");
        dt.Columns.Add("LastName");
        dt.Columns.Add("Age", typeof(System.Int32));

        DataRow oItem = dt.NewRow();
        oItem[0] = "Shawpnendu";
        oItem[1] = "Bikash";
        oItem[2] = 32;
        dt.Rows.Add(oItem);

        oItem = dt.NewRow();
        oItem[0] = "Bimalendu";
        oItem[1] = "Bikash";
        oItem[2] = 27;
        dt.Rows.Add(oItem);

        GridView gv = new GridView();
        gv.AutoGenerateColumns = false;

        BoundField nameColumn = new BoundField();
        nameColumn.DataField = "FirstName";
        nameColumn.HeaderText = "First Name";
        gv.Columns.Add(nameColumn);

        nameColumn = new BoundField();
        nameColumn.DataField = "LastName";
        nameColumn.HeaderText = "Last Name";
        gv.Columns.Add(nameColumn);

        nameColumn = new BoundField();
        nameColumn.DataField = "Age";
        nameColumn.HeaderText = "Age";
        gv.Columns.Add(nameColumn);

        // Here is template column portion
        TemplateField TmpCol = new TemplateField();
        TmpCol.HeaderText = "Click Me";
        gv.Columns.Add(TmpCol);
        TmpCol.ItemTemplate = new TemplateHandler();        

        gv.DataSource = dt;
        gv.DataBind();

        Form.Controls.Add(gv);
    }

Monday, June 13, 2011

Steps to remove empty lines using Visual Studio i.e format the coding

Steps to remove empty lines using Visual Studio i.e format the coding in .cs or .vb file
Start Visual Studio and follow these steps.
1.Click Ctrl-H (quick replace)
2. Tick "Use Regular Expressions"
3. In Find specify ^$\n

4. In Replace box delete everything.
5 Click "Replace All"
All empty lines will be deleted.



Regular expression for empty line consist of  
Beginning of line ^
End of line $
Line break \n


A regex to remove blank lines that are/aren't *really* blank (i.e. they do/don't have spaces):  
^:b*$\n

Thursday, June 9, 2011

Validating textbox using single CustomValidator Control in GridView

The below code validates all the textboxes in a Gridview using a single CustomValidator control

function isValidDate(sText) {
var reDate = /(?:0[1-9]|[12][0-9]|3[01])\/(?:0[1-9]|1[0-2])\/(?:19|20\d{2})/;

if(sText.length==0)
return false;
else
return reDate.test(sText);
}
function isValidDecimalValue(sValue)
{
var reDecimal = /^\d{1,12}(\.(\d{1,2}))?$/;
return reDecimal.test(sValue);
}

function validateForm(source, value)
{
var isXDDateError = false;
var isGrossError = false;
var objError = document.getElementById("<%= spnError.ClientID %>");
objError.innerHTML="";
isXDDateError=ValidateDateValue();
isGrossError=ValidateGross();

if(isXDDateError || isGrossError)//Both false
{
value.IsValid = false;
}
else
value.IsValid = true;
}

function ValidateGross()
{
var obj = document.getElementsByTagName("input");
var objError = document.getElementById("<%= spnError.ClientID %>");
var objSpan, isError = false;
for(i=0; i<obj.length; i++)
{
if(obj[i].name.indexOf("txtGross") > 0)
{
if(!isValidDecimalValue(obj[i].value))
{
isError = true;
if(obj[i].parentNode != null)
{
for(j=0; j < obj[i].parentNode.childNodes.length; j++)
{
objSpan = obj[i].parentNode.childNodes[j];
if( objSpan != null && objSpan.id != undefined)
{
if(objSpan.id.indexOf("spnGross") == 0)
{
objSpan.innerText = "*";
}
}
}
}
}
else
{
if(obj[i].parentNode != null)
{
for(j=0; j < obj[i].parentNode.childNodes.length; j++)
{
objSpan = obj[i].parentNode.childNodes[j];
if( objSpan != null && objSpan.id != undefined)
{
if(objSpan.id.indexOf("spnGross") == 0)
{
objSpan.innerText = "";
}
}
}
}
}
}
}
if(isError)
{
if(objError.innerHTML.length>0)
objError.innerHTML+="* Please enter a value for Gross.</br>"
else
objError.innerHTML="* Please enter a value for Gross.</br>"
objError.display="block";
}

return isError;
}

<span id="spnError" runat="server" style="color:Red"></span>
<asp:CustomValidator ID = "CustomValidator1" runat = "server" ClientValidationFunction = "validateForm"></asp:CustomValidator>
<asp:Button ID="btnSave" CausesValidation="true" runat="server" Visible="true" class="tdsButton" Text="Save"
align="right" OnClick="btnSave_Click" />
<asp:GridView ID="HoldingsGrid" runat="server">
<Columns>
<asp:TemplateField HeaderText="Gross" SortExpression="SortOnGross">
<ItemTemplate>
<asp:Label ID="lblGross" runat="server" Text='<%# Bind("PAYMENT_GROSS_LOCAL_CUST") %>' />
<asp:TextBox ID="txtGross" runat="server" />
<span id="spnGross" style="color:Red" ></span>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

Validate date using Javascript dd/mm/yyyy

<html>
<head>
<title>Date Example</title>
<script type="text/javascript">
    function isValidDate(sText) {
        var reDate = /(?:0[1-9]|[12][0-9]|3[01])\/(?:0[1-9]|1[0-2])\/(?:19|20\d{2})/;
        return reDate.test(sText);
    }
    function validate() {
        var oInput1 = document.getElementById("txt1");
        if (isValidDate(oInput1.value)) {
            alert("Valid");
        else {
            alert("Invalid!");
        }
    }
</script>
</head>
<body>
    <P>Date: <input type="text" id="txt1" /><br />
    example: 06/07/2005<br />
    <input type="button" value="Validate" onclick="validate()" /></p>
</body>
</html>

Monday, May 30, 2011

Importank Links

Uploading Excel file to SQL Server using SqlBulkCopy

string strConnection = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnUpload_Click(object sender, EventArgs e)
{
//Create connection string to Excel work book
string excelConnectionString
=@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Details.xls;
Extended Properties=""Excel 8.0;HDR=YES;""";

//Create Connection to Excel work book
OleDbConnection excelConnection =new OleDbConnection(excelConnectionString);

//Create OleDbCommand to fetch data from Excel
OleDbCommand cmd = new OleDbCommand("Select [ID],[Name],[Location] from [Detail$]",excelConnection);

excelConnection.Open();
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();

SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);
sqlBulk.DestinationTableName = "Details";
sqlBulk.ColumnMappings.Add("ID", "ID");
sqlBulk.ColumnMappings.Add("Name", "Name");
sqlBulk.WriteToServer(dReader);
}

Import Gmail Contacts in Asp.Net

First of all download Google Data API and install to get following dlls
1. Google.GData.Client
2. Google.GData.Contacts
3. Google.GData.Extensions
Put these 3 dlls in BIN folder of application also add reference to your project for them.

using Google.Contacts;
using Google.GData.Client;
using Google.GData.Contacts;
using Google.GData.Extensions;
<b>Email: </b>

<asp:TextBox ID="txtEmail" runat="server"> </asp:TextBox>
<b>Password : </b>
<asp:TextBox ID="txtPassword" runat="server" TabIndex="1" TextMode="Password">
</asp:TextBox>
<asp:Button ID="btnContacts" runat="server"  onclick="btnContacts_Click"
TabIndex="2" Text="Import Contacts"  Width="125px" />
<asp:ListBox ID="lstContacts" runat="server" Height="176px" Width="229px">
 </asp:ListBox>

protected void btnContacts_Click(object sender, EventArgs e)
    {
        //Provide Login Information
        RequestSettings rsLoginInfo = new RequestSettings("", txtEmail.Text, txtPassword.Text);
        rsLoginInfo.AutoPaging = true;

        // Fetch contacts and dislay them in ListBox
        ContactsRequest cRequest = new ContactsRequest(rsLoginInfo);
        Feed <contact> feedContacts = cRequest.GetContacts();
        foreach (Contact gmailAddresses in feedContacts.Entries)
        {
            Console.WriteLine("\t" + gmailAddresses.Title);
            lstContacts.Items.Add(gmailAddresses.Title);
            foreach (EMail emailId in gmailAddresses.Emails)
            {
                Console.WriteLine("\t" + emailId.Address);
                lstContacts.Items.Add(" " + emailId.Address);
            }
        }

    }

Display Auto Number Column in Gridview

<asp:TemplateField HeaderText="Serial Number">
    <ItemTemplate>
        <%# Container.DataItemIndex + 1 %>
    </ItemTemplate>

Check NULL value at serverside using EVAL in Itemtemplate Gridview

<ItemTemplate>
<asp:Label ID="Label1" runat="server" 
           Text='<%# CheckNull(Eval("Location")) %>'>
</asp:Label>
</ItemTemplate>
protected string CheckNull(object objGrid)    
{ if (object.ReferenceEquals(objGrid, DBNull.Value))        
{ return "No Record Found"; }        
else { return objGrid.ToString(); }     
}

Merge gridview headers

Here is the code to merge header of the gridview













<asp:GridView ID="grvMergeHeader" runat="server">
<Columns>
<asp:BoundField DataField="DepartMentID"HeaderText="DepartMentID"SortExpression="DepartMentID" />
<asp:BoundField DataField="DepartMent"HeaderText="DepartMent"SortExpression="DepartMent" />
<asp:BoundField DataField="Name"HeaderText="Name"SortExpression="Name" />
<asp:BoundField DataField="Location"HeaderText="Location"SortExpression="Location" />
</Columns>
</asp:GridView>

protected void grvMergeHeader_RowCreated
(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
GridView HeaderGrid = (GridView)sender;
GridViewRow HeaderGridRow =
new GridViewRow(0, 0, DataControlRowType.Header,
DataControlRowState.Insert);
TableCell HeaderCell = new TableCell();
HeaderCell.Text = "Department";
HeaderCell.ColumnSpan = 2;
HeaderGridRow.Cells.Add(HeaderCell);

HeaderCell = new TableCell();
HeaderCell.Text = "Employee";
HeaderCell.ColumnSpan = 2;
HeaderGridRow.Cells.Add(HeaderCell);

grvMergeHeader.Controls[0].Controls.AddAt
(0, HeaderGridRow);
}
}