Sunday, December 2, 2012

How to create excel from data table

Use following function
Following code is used to create / generate excel sheet from data table. you not need to change anything just pass the data table and file name in function.

private static void ExporttoExcel(DataTable table, string reportName)
            HttpContext.Current.Response.Buffer = true;
            HttpContext.Current.Response.ContentType = "application/ms-excel";
            HttpContext.Current.Response.Write(@"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.0 Transitional//EN"">");
            HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + reportName + "");

            HttpContext.Current.Response.Charset = "utf-8";
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1250");
            //sets font
            HttpContext.Current.Response.Write("<font style='font-size:10.0pt; font-family:Calibri;'>");
            //sets the table border, cell spacing, border color, font of the text, background, foreground, font height
            HttpContext.Current.Response.Write("<Table border='1' bgColor='#ffffff' " +
              "borderColor='#000000' cellSpacing='0' cellPadding='0' " +
              "style='font-size:10.0pt; font-family:Calibri; background:white;'> <TR>");
            //am getting my grid's column headers
            int columnscount = table.Columns.Count; //table.Rows.Count - 1;// GridView_Result.Columns.Count;

            for (int j = 0; j < columnscount; j++)
            {      //write in new column
                //Get column headers  and make it as bold in excel columns
            foreach (DataRow row in table.Rows)
            {//write in new row
                for (int i = 0; i < table.Columns.Count; i++)


Mahesh Kumar Sharma

Saturday, November 17, 2012

How to rearrange data columns

We can change the ordinal of data column


How to create one data table from other datatable

You can create copy of existing data table and than remove unwanted data columns from data table
Following is code:

DataTable dtSourceCopy = dtSource.Copy();
                    DataColumnCollection columnsArray = dtSourceCopy .Columns;
                    foreach (var item in columnsArray)
                        if (!selectedColumns.Contains(item.ToString()))

How to remove all items form listbox

Following code can be used to move lists item from one to other and
Move up or down in same listbox.

It requires the jQuery lib.

Just bind values in source list box and copy paste following script and html in your screen.


 /*Move up or down the list items*/
        function MoveItemUpDown(updown) {
            $("[id$=ListBoxDestination] > option:selected").each(function () {
                if (updown == 'up') {
                else if (updown == 'down') {
            return false;
        function MoveItemsFromSourceToDesitnationListBox(SourceListBoxId, DestinationListBoxId) {
            //Move items from one listbox to other list box
            $("[id$=" + SourceListBoxId + "] > option:selected").each(function () {
                $(this).remove().appendTo("[id$=" + DestinationListBoxId + "]").removeAttr('selected');
            //Remove selected attributes from options
            $("[id$=" + SourceListBoxId + "] > option:selected").each(function () {
            $("[id$=" + DestinationListBoxId + "] > option:selected").each(function () {
            return false;
        function SetSelectedVlauesAndOrder() {
            //Save selected items in destination listbox
            var destinationValues = '';
            $("[id$=ListBoxDestination] > option").each(
          function () {
              destinationValues = destinationValues + "," + $(this).val();
            return false;


                    <asp:ListBox Height="300px" Width="180px" ID="ListBoxSource" runat="server" SelectionMode="Multiple">
                <td style="padding:0 10px;">
                    <asp:Button ID="ButtonMoveToDesitnation" OnClientClick="return MoveItemsFromSourceToDesitnationListBox('ListBoxSource','ListBoxDestination')"
                        Text=" >>" runat="server" />
                    <br />
                    <asp:Button ID="ButtonMoveToSource" OnClientClick="return MoveItemsFromSourceToDesitnationListBox('ListBoxDestination','ListBoxSource')"
                        Text=" <<" runat="server" />
                    <asp:ListBox Height="300px" Width="180px" ID="ListBoxDestination" runat="server"
                    <asp:HiddenField ID="HiddenFieldListBoxItemsId" runat="server" />
                <td  style="padding:0 10px;">
                    <asp:Button ID="ButtonMoveItemUp" Text="^ ^" runat="server" OnClientClick=" return MoveItemUpDown('up')" />
                    <br />
                    <asp:Button ID="ButtonMoveItemDown" Text="v v" runat="server" OnClientClick=" return MoveItemUpDown('down')" />

Monday, September 10, 2012

repcale all words in javascript in single statement

To replacing all matches at once just put a "g" at the end of the regular expression.

<script type="text/javascript">
var personName = "Mahesh";
var myOldString = "Hello [name]! [name] you are selected. We have a t-shirt with your [name]";
var myNewString = myOldString.replace(/[name]/g, personName

Saturday, August 4, 2012

Thursday, July 19, 2012

how to convert xsd to c# class

how to convert xsd file in to c#
Step 1 open follwoing location
C:\Program Files\Microsoft Visual Studio 9.0\VC
(where the Visual studion command prompt marking.above path is ideally for vs-2008 )
Step 2 Paste your xsd files.
Step 3 Open command prompt from Visual studio
Step 4 write command
 xsd /c a.xsd a1.xsd
 if you have more than one xsd for proxy class write all files name with space.
        here /c tells that proxy file should be generated in c#.

Monday, March 5, 2012

Remove one list from other list without loop

var integers = new List<int> { 1, 2, 3, 4, 5 };
            var remove = new List<int> { 1, 3, 5 };
            integers.RemoveAll(i => remove.Contains(i));
            List<string> lis1 = new List<string>() { "1", "2", "3", "4", "5" };
            List<string> lis2 = new List<string>() { "1", "3", "5", "0" };

Mahesh K. Sharma

Sunday, March 4, 2012

Office automation setting on server

Retrieving the COM class factory for component with CLSID{000209ff-0000-0000-c000-000000000046} failded due to following error: 80070005 Or document object is null

DCOM Configuration
1.      Click Start -> Run
2.      Enter DCOMCNFG and press OK. This will open the DCOMCNFG window.
3.      Browse down the tree to Console Root -> Component Services -> Computers -> My Computer
4.      Right click on "My Computer" and select properties
5.      Select the "Default Properties" tab
a.      Enable Distributed COM on this computer - Option is checked
b.      Default Authentication Level - Set to Connect
c.       Default Impersonation Level - Set to Identify
6.      Select the "COM Security" tab
7.      Click on Access Permissions ' Edit Default
a.      Add "Anonymous", "Everyone", "Interactive", "Network", "System" with Local and Remote access permissions set.
8.      Click on Launch and Activation Permissions ' Edit Default
a.      Add "Anonymous", "Everyone", "Interactive", "Network", "System" with Local and Remote access permissions set.
9.      Click on OK
10.  Close the DCOMCNFG window

If server is
Create desktop folder in following location



Mahesh K Sharma
Server was Windows 2008 R2, with service pack 1.

Wednesday, February 22, 2012

set and remove impersonation programmatically / runtime

/// <summary>
    /// <Description> This code is from </Description>
    /// </summary>
    public class CallImpersonation
        public const int LOGON32_LOGON_INTERACTIVE = 2;
        public const int LOGON32_PROVIDER_DEFAULT = 0;
        WindowsImpersonationContext impersonationContext;
        public static extern int LogonUserA(String lpszUserName, String lpszDomain,
            String lpszPassword,
            int dwLogonType,
            int dwLogonProvider,
            ref IntPtr phToken);
        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern int DuplicateToken(IntPtr hToken, int impersonationLevel,
            ref IntPtr hNewToken);
        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern bool RevertToSelf();
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        public static extern bool CloseHandle(IntPtr handle);
        /// <summary>
        /// Turn on the impersonation
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="domain"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public bool ImpersonateValidUser(String userName, String domain, String password)
            WindowsIdentity ident = WindowsIdentity.GetCurrent();
            WindowsPrincipal user = new WindowsPrincipal(ident);
            WindowsIdentity tempWindowsIdentity;
            IntPtr token = IntPtr.Zero;
            IntPtr tokenDuplicate = IntPtr.Zero;
            if (RevertToSelf())
                if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
                    LOGON32_PROVIDER_DEFAULT, ref token) != 0)
                    if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
                        tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
                        impersonationContext = tempWindowsIdentity.Impersonate();
                        if (impersonationContext != null)
                            return true;
            if (token != IntPtr.Zero)
            if (tokenDuplicate != IntPtr.Zero)
            return false;
        /// <summary>
        /// Trunoff the impersonation.
        /// </summary>
        public void UndoImpersonation()
        /// <summary>
        /// <Description>Get the credential for impersonation</Description>
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="domain"></param>
        /// <param name="password"></param>
        /// <param name="client"></param>
        /// <param name="key"></param>
        /// <param name="eBase"></param>
        /// <returns></returns>
        public bool GetImpersonateCredentials(out string userName, out string domain, out string password, string client, int key, ErgoBase eBase)
            ErgoBase ebase = eBase;
                string fetchForExistingSql = "SELECT egemimp_guid,domainName,username,password_ue FROM egem_impersonation " +
                  "WHERE client = @client " +
                  "AND valid=   @valid " +
                  "AND status = @status ";
                ebase.Db.AddParameter("@client", client);
                ebase.Db.AddParameter("@valid", 1);
                ebase.Db.AddParameter("@status", "N");
                System.Data.DataTable dtforRegisteredusers = ebase.Db.GetDataTable(fetchForExistingSql);
                if (dtforRegisteredusers.Rows.Count > 0)
                    domain = dtforRegisteredusers.Rows[0]["domainName"].ToString();
                    userName = dtforRegisteredusers.Rows[0]["username"].ToString();
                    password = EmploymentSettings.Decrypt(dtforRegisteredusers.Rows[0]["password_ue"].ToString(), key);
                    return true;
                    domain = string.Empty;
                    userName = string.Empty;
                    password = string.Empty;
                    return false;
            catch (Exception ex)
                throw ex;

Tuesday, February 21, 2012

BitFlag and checkboxes

  <asp:CheckBox ID="CheckBox1" runat="server" />
        <asp:CheckBox ID="CheckBox2" runat="server" />
        <asp:CheckBox ID="CheckBox3" runat="server" />
        <asp:CheckBox ID="CheckBox4" runat="server" />
 <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />

In code behind:

 public enum BitFlag : byte
            First = 1,
            Second = 2,
            Third = 4,
            Fourth = 8
        public  void CheckFlag(BitFlag bFlag)
            if ((bFlag & BitFlag.First) == BitFlag.First)
                CheckBox1.Checked = true;
            if ((bFlag & BitFlag.Second) == BitFlag.Second)
                CheckBox2.Checked = true;
            if ((bFlag & BitFlag.Third) == BitFlag.Third)
                CheckBox3.Checked = true;
            if ((bFlag & BitFlag.Fourth) == BitFlag.Fourth)
                CheckBox4.Checked = true;

   protected void Button1_Click(object sender, EventArgs e)
            BitFlag bFlag = new BitFlag();//= BitFlag.First;
            if (CheckBox1.Checked)
                bFlag |= BitFlag.First;
            if (CheckBox2.Checked)
                bFlag |= BitFlag.Second;
            if (CheckBox3.Checked)
                bFlag |= BitFlag.Third;
            if (CheckBox4.Checked)
                bFlag |= BitFlag.Fourth;



Monday, February 20, 2012

Set Div Scroll bar postion by code.

Hi in follwoing example we set the div scrollbar postion by passing predefined value. we can calculate this value depend on our requirement.
How to retrive current scroll top of div?
Add follwoing event in div
Implement function and store scrolltop in hiddenfield.
function MaintanDivScrollPosition(sender) {"input[type=hidden][id$=HiddenFieldScrollTopDivContentPage]").val($(sender)[0].scrollTop);


        <title>OnScroll Example</title>
        <script type="text/javascript">
            function CallOnLoad () {
               document.getElementById("divrelative").scrollTop = 500;
    <body onload="CallOnLoad()">
        <div id="divrelative" style="overflow:scroll;height:200px;">
         <P>Line 1</p>
         <P>Line 2</p>
         <P>Line 3</p>
         <P>Line 4</p>
         <P>Line 5</p>
         <P>Line 6</p>
         <P>Line 7</p>
         <P>Line 8</p>
         <P>Line 9</p>
         <P>Line 10</p>
         <P>Line 11</p>
         <P>Line 12</p>
   <P>Line 14</p>
         <P>Line 15</p>
         <P>Line 16</p>
         <P>Line 17</p>
         <P>Line 18</p>
         <P>Line 19</p>
         <P>Line 20</p>
         <P>Line 21</p>
         <P>Line 22</p>

Monday, January 23, 2012

JQuery and update panel.

JQuery and update panel.

We faced problem when we have update panel and using .ready function of jquery.
than on asysnc request of update panel Jquery .ready is not fired than we have to use add_load of sys.Application class of scrip manager library.

$(document).ready(function IwillCallWhenPgeIsReady(
//IF you have update panel than it will never call on async request
Update Panel:
Sys.Application.add_load(function() {});

Best Practices for Deployment of ASP.NET Applications Production

Best Practices for Deployment of ASP.NET Applications Production

Compress file.
Compress JavaScript & aspx HTML file before deployment. This will reduce the size of file which optimizing rendering time.

Caching of static data.
Set the Cache of static content like images. or web page which have no user specific.

Set httpRuntime executionTimeout
If application may be accessed by slow internet connection then it wise step to increase execution time out.
We can set it on Web config file
<httpRuntime executionTimeout="seconds" />

Build Mode release
When application is about to deplaoy than builds it by release mode.
In release mode we have less information of error.

deployment retail

Set retail="true" in your machine.config
<deployment retail="true"/>

1. It will force the 'debug' flag in the web.config to be false, 
2. It will disable page output tracing, and 
3. It will force the custom error page to be shown to remote users rather than the actual exception or error message.

Create a new application pool for your site
When setting up your new site for the first time do not share an existing application pool.  Create a new application pool which will be used by only by the new web

It also force an application restart in case you forget to do this for a deployment