Friday, 9 December 2016

Excel connection string

FileUpload1.SaveAs(fileLocation);

     //Check whether file extension is xls or xslx

        if (fileExtension == ".xls")
     {
          connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" fileLocation ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
       }
          else if (fileExtension == ".xlsx")
        {
            connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" fileLocation ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
           }

Upload / Import excel with bulk import

Drag a button control in aspx page and find it button_click event and write these code inside
protected void Button1_Click(object sender, EventArgs e)
    {string path = string.Concat((Server.MapPath("~/temp/" FileUpload1.FileName)));
            FileUpload1.PostedFile.SaveAs(path);
            OleDbConnection OleDbcon = new OleDbConnection("Provider=Microsoft.Ace.OLEDB.12.0; Data Source =" path "; Extended Properties=Excel 12.0;");
            OleDbCommand cmd = new OleDbCommand("Select * from [Sheet1$]", OleDbcon);
            OleDbDataAdapter objAdapter1 = new OleDbDataAdapter(cmd);

            OleDbcon.Open();
            OleDbDataReader dr = cmd.ExecuteReader();
            // SqlConnection con =new  SqlConnection(connection.cstr);
            SqlConnection con = new SqlConnection(connection.cstr);
            con.Open();
           // string con_str = @"Data Source=SANDEEP-PC\\SQLEXPRESS;Initial Catalog=Tmndx;Integrated Security=True";
            SqlBulkCopy bulkInsert = new SqlBulkCopy(con);
            bulkInsert.DestinationTableName = "country_code";
            bulkInsert.WriteToServer(dr);
            OleDbcon.Close();

            Array.ForEach(Directory.GetFiles((Server.MapPath("~/temp/"))), File.Delete);
            Label1.ForeColor = Color.Green;
            Label1.Text = "Successfully Inserted";
        }
        else
        {
            Label1.ForeColor = Color.Red;
            Label1.Text = "Please Select the File";
        }
    }

Popup form using Ajax Model Pop Up Extender in Ap.net C#

<asp:Button ID="btnShowPopup" runat="server" Style="display: none" />
            <asp:ModalPopupExtender ID="ModalPopupExtender1" runat="server" TargetControlID="btnShowPopup"
                PopupControlID="pnlpopup" CancelControlID="btnCancel" BackgroundCssClass="modalBackground">
            </asp:ModalPopupExtender>
            <asp:Panel ID="pnlpopup" runat="server" BackColor="White" Height="300px" Width="400px"
                Style="display: none">
                <table width="100%" style="border: Solid 3px #D55500; width: 100%; height: 100%"
                    cellpadding="0" cellspacing="0">
                    <tr style="background-color: #D55500">
                        <td colspan="2" style="height: 10%; color: White; font-weight: bold; font-size: larger"
                            align="center">
                            Pay EMI
                        </td>
                    </tr>
                    <tr>
                        <td align="right" style="width: 45%">
                            EMI ID:
                        </td>
                        <td>
                            <asp:Label ID="lblID" runat="server"></asp:Label>
                        </td>
                    </tr>
                    <tr>
                        <td align="right" style="width: 45%">
                            Buyer Name:
                        </td>
                        <td>
                            <asp:Label ID="lblbuyername" runat="server"></asp:Label>
                        </td>
                    </tr>
                    <tr>
                        <td align="right">
                            EMI No:
                        </td>
                        <td>
                            <asp:Label ID="lblemino" runat="server"></asp:Label>
                        </td>
                    </tr>
                    <tr>
                        <td align="right">
                            EMI Amount:
                        </td>
                        <td>
                            <asp:Label ID="lblamount" runat="server"></asp:Label>
                        </td>
                    </tr>
                    <tr>
                        <td align="right">
                            Payment Date:
                        </td>
                        <td>
                            <asp:TextBox ID="txtpaiddate" runat="server" />
                        </td>
                    </tr>
                    <tr>
                        <td>
                        </td>
                        <td>
                            <asp:Button ID="btnUpdate" CommandName="Update" runat="server" Text="Pay" OnClick="btnUpdate_Click" />
                            <asp:Button ID="btnCancel" runat="server" Text="Cancel" />
                        </td>
                    </tr>
                </table>
            </asp:Panel>



in code behind button event on which pop has to be displayed

protected void LinkButton3_Click(object sender, EventArgs e)
    {
        LinkButton lnkbtn = sender as LinkButton;
        GridViewRow gvrow = lnkbtn.NamingContainer as GridViewRow;               
        this.ModalPopupExtender1.Show();      
    }

Formatting asp.net label when the value is sourced from a query string

lbltotalamount.Text = String.Format("{0:N0}", int.Parse(Request.QueryString["tp"])); 

url routing in VS 2010 for asp.net c#


Step 1: work only on VS2010 and above

 In order to implement URL Routing we will need to register the routes that we need to use in our application.
In order to do that I have created a method named RegisterRoutes and it has been called inside the Application_Start event inside the Global.asax file. This method will allow us to add routes to handle so that we can create our own custom URLs.

<%@ Application Language="C#" %>
<%@ Import Namespace="System.Web.Routing" %>

<script runat="server">
    void Application_Start(object sender, EventArgs e)
    {
        RegisterRoutes(System.Web.RouteTable.Routes);
    }
  
    static void RegisterRoutes(RouteCollection routes)
    {
        routes.MapPageRoute("Customers", "Customers", "~/Customers.aspx");
    }
</script>

for more info visit.

Wednesday, 30 November 2016

Show Image Loader while processing data in Asp.net C# using Ajax UpdatePanel Animation Extender and JavaScript

<script type="text/javascript">
     function InProgress() {
         var panelProg = $get('divProgress');
         panelProg.style.display = '';

         var lbl = $get('<%# this.lblText.ClientID %>');
         lbl.innerHTML = '';
     }

     function onComplete() {
         var panelProg = $get('divProgress');
         panelProg.style.display = 'none';
     }     
    </script>
    <style type="text/css">
        .popup
        {
            border: 0px solid #6b6a63;
            width: 100%;
            height: 100%;
            position: fixed;
            background-color: rgba(0, 0, 0, .1);
            z-index: 99999;
            top: 0;
            bottom: 0;
            left: 0;
            right: 0;
        }
        .prgimg
        {
 
           top: 0;

            bottom: 0;
            left: 0;
            right: 0;
            margin: 35% 0 0 0%;
            z-index: 9999999999;
        }
    </style>

========================================================================================
 <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <asp:UpdatePanel ID="full" runat="server" UpdateMode="Conditional">
        <ContentTemplate>
        <asp:Label ID="lblText" runat="server" />
                <div id="divProgress" style="display:none;" class="popup">
                     <asp:Image ID="LoadingImage" runat="server" ImageUrl="~/images/loader.gif" />                   
                </div>       
        </ContentTemplate>
                <Trigger>
                </Trigger>
    </asp:UpdatePanel>
===========================
 <asp:UpdatePanelAnimationExtender ID="UpdatePanelAnimationExtender1" TargetControlID="full" runat="server">
        <Animations>
            <OnUpdating>                     
               <Parallel duration="0">
                    <ScriptAction Script="InProgress();" />
                    <EnableAction AnimationTarget="Button1" Enabled="false" />     
                    <EnableAction AnimationTarget="LinkButton1" Enabled="false" />        
                    <EnableAction AnimationTarget="LinkButton2" Enabled="false" />              
                </Parallel>
            </OnUpdating>
            <OnUpdated>
                <Parallel duration="0">              
                    <ScriptAction Script="onComplete();" />
                    <EnableAction AnimationTarget="Button1" Enabled="true" />
                    <EnableAction AnimationTarget="LinkButton1" Enabled="true" />        
                    <EnableAction AnimationTarget="LinkButton2" Enabled="true" />   
                </Parallel>
            </OnUpdated>
        </Animations>
        </asp:UpdatePanelAnimationExtender>


split , separated string and bind in gridview in asp.net c#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Net.NetworkInformation;
using System.Data.SqlClient;
using System.Data;
using System.Text;
using System.Web.UI.HtmlControls;
using System.Collections;
using System.Runtime.InteropServices;
using System.Management;
using System.Security.Cryptography;

public partial class test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {

            generatedatatable();
           
        }
    }

    public void generatedatatable()
    {
        try
        {
                  method 1: separate comma and pipe ("," and "|") attached string
            ArrayList List = new ArrayList();             
            //string TstStr = "1,dt3435,26/5/2012 ~ 2,dt738,27/5/2012 ~ 3,dt892,26/5/2012";
            string query = "Select Specification From Menu_new_date where S_no='54'";
            string TstStr = Convert.ToString(connection.scalar(query));
            string[] SplittedString = TstStr.Split('|');
            foreach (string str in SplittedString)
            {
                string ConcatStr = "";
                string[] SubSplit = str.Trim().Split(',');
                foreach (string s in SubSplit)
                {
                    ConcatStr = s " ";
                }
                List.Add(ConcatStr);
            }

            DataTable dt = new DataTable();
            DataColumn dc = new DataColumn("Nutrition", typeof(string));
            //DataColumn dc1 = new DataColumn("Quantity", typeof(string));      
            dt.Columns.Add(dc);
            //dt.Columns.Add(dc1);
            for (int i = 0; i < List.Count; i )
            {
                dt.Rows.Add();
                dt.Rows[i][0] = List[i];
            }
            ------------------------------------------------------------------------------------------

                Method:2  separate comma  (",") attached string in one row with dynamically crate no of column as per the comma
               
            ArrayList List = new ArrayList();
            //string TstStr = "1,dt3435,26/5/2012 ~ 2,dt738,27/5/2012 ~ 3,dt892,26/5/2012";
            string query = "Calories 212 Kcal,Total fat 5.7 g,Saturated fat 0.8 g,Polyunsaturated fats 1 g,Monounsaturated fats 3.4 g,Total                 carbohydrate 25.2 g,Dietary fibre 4.3 g,Sugars 2.3 g,Protein 17.4 g";
            //string TstStr = Convert.ToString(connection.scalar(query));
            string TstStr = query;
            string abc="";
            string[] SplittedString = TstStr.Split(',');
            foreach (string str in SplittedString)
            {
                 abc =str;
                 List.Add(abc);
            }

            DataTable dt = new DataTable();
            //DataColumn dc = new DataColumn("Nutrition", typeof(string));
            //DataColumn dc1 = new DataColumn("Quantity", typeof(string));      
           
            //dt.Columns.Add(dc1);
            dt.Rows.Add();
            for (int i = 0; i < List.Count; i )
            {
                DataColumn dc = new DataColumn("Nutrition" i, typeof(string));
                dt.Columns.Add(dc);
               
               
                dt.Rows[0][i]= List[i];
              
             
            }

            GridView1.DataSource = dt;
            GridView1.DataBind();
            ------------------------------------------------------------------------------------------------

                Method:3  separate comma  (",") attached string in multiple row

            ArrayList List = new ArrayList();
            string TstStr = "1,dt3435,26/5/2012 ~ 2,dt738,27/5/2012 ~ 3,dt892,26/5/2012";
            string query = "Calories 212 Kcal,Total fat 5.7 g,Saturated fat 0.8 g,Polyunsaturated fats 1 g,Monounsaturated fats 3.4 g,Total                 carbohydrate 25.2 g,Dietary fibre 4.3 g,Sugars 2.3 g,Protein 17.4 g";
            string TstStr = Convert.ToString(connection.scalar(query));
            string TstStr = query;
            string abc = "";
            string[] SplittedString = TstStr.Split(',');
            foreach (string str in SplittedString)
            {
                abc = str;
                List.Add(abc);
            }

            DataTable dt = new DataTable();
            DataColumn dc = new DataColumn("Nutrition", typeof(string));
            DataColumn dc1 = new DataColumn("Quantity", typeof(string));      

          
            dt.Columns.Add(dc);
            for (int i = 0; i < List.Count; i )
            {                             
                dt.Rows.Add();
                dt.Rows[i][0] = List[i];
            }
                //create gridview dynamically and add this gridview to any div where to show data
            GridView grid = new GridView();
            grid.DataSource = dt;
            grid.DataBind();
            nutri.Controls.Add(grid);
               
        //bind splitted string to available gridview
            GridView1.DataSource = dt;
            GridView1.DataBind();

                        
Nutrition
Calories 212 Kcal
Total fat 5.7 g
Saturated fat 0.8 g
Polyunsaturated fats 1 g
Monounsaturated fats 3.4 g
Total carbohydrate 25.2 g
Dietary fibre 4.3 g
Sugars 2.3 g
Protein 17.4 g


            --------------------------------------------------------------------------------------------------------
         Method:4  separate  comma and pipe ("," and "|") attached string in multiple row
            DataTable values = new DataTable();
            values.Columns.Add("Nutrition", typeof(string), null);
            values.Columns.Add("Quantity", typeof(string), null);

            string query = "Select Specification From Menu_new_date where S_no='54'";
            string TstStr = Convert.ToString(connection.scalar(query));
            values = TstStr.Split('|').Select(s =>
            {
                var fields = s.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                var row = values.NewRow();
                if (fields.Length == 2)
                {
                    row[0] = fields[0].Trim();
                    row[1] = fields[1].Trim();                  
                }
                return row;
            }).CopyToDataTable();

            GridView1.DataSource = values;
            GridView1.DataBind();
        }
        catch (Exception ex)
        {
            Label1.Text= ex.Message;
        }
    }
   
}