cookieChoices = {};
Showing posts with label ASP Examples. Show all posts
Showing posts with label ASP Examples. Show all posts

Thursday, 20 March 2014

ASP Excel to Sql Database Example

First Create a Excel Sheet with Column name are same as Sql table Column Names





Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table>
            <tr>
                <td>
                    <span style="color: Red">*</span>Attach Excel file
                </td>
                <td>
                    <asp:FileUpload ID="fileuploadExcel" runat="server" />
                </td>
            </tr>
            <tr>
                <td>
                </td>
                <td>
                    <asp:Button ID="btnSend" runat="server" Text="Export" OnClick="btnSend_Click" />
                </td>
            </tr>
        </table>
        <asp:GridView ID="GridView1" runat="server">
        </asp:GridView>
    </div>
    </form>
</body>
</html>

Default.aspx.cs

protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnSend_Click(object sender, EventArgs e)
    {
        String strConnection = "Data Source=.;Min Pool Size=1;Max Pool Size=500;Initial Catalog=Demo_Assign;User Id=sa;Password=******;Connection Timeout=500;";
        //file upload path
        string path = fileuploadExcel.PostedFile.FileName;
        //Create connection string to Excel work book
        string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;Persist Security Info=False";
        //Create Connection to Excel work book
        OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
        //Create OleDbCommand to fetch data from Excel
        OleDbCommand cmd = new OleDbCommand("Select EmployeeID,EmployeeName,Title,City,Phone from [Sheet1$]", excelConnection);
        excelConnection.Open();
        OleDbDataReader dReader;
        dReader = cmd.ExecuteReader();
        SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);
        //Give your Destination table name
        sqlBulk.DestinationTableName = "Emp";
        sqlBulk.WriteToServer(dReader);
        excelConnection.Close();
    }

Make Sure Visual Studio wiil run in Administrator mode only...

Monday, 11 November 2013

Log error in a text file in ASP.Net

It’s good practice to log all the error into a file or database so in future you can check, how your application is working, and is there any issue which is not caught by Q.A. team.
Really it's helpful to understand and caught the issues after deploying the application on production server.
Create a method to log the error into a file:
public void LogError(Exception ex, String source)
{
   try
   {
       String LogFile = HttpContext.Current.Request.MapPath("/Errorlog.txt");
       if (LogFile != "")
       {
           String Message = String.Format("{0}{0}=== {1} ==={0}{2}{0}{3}{0}{4}{0}{5}"
                    , Environment.NewLine
                    , DateTime.Now
                    , ex.Message
                    , source
                    , ex.InnerException
                    , ex.StackTrace);
           byte[] binLogString = Encoding.Default.GetBytes(Message);

           System.IO.FileStream loFile = new System.IO.FileStream(LogFile
                     , System.IO.FileMode.OpenOrCreate
                     , System.IO.FileAccess.Write, System.IO.FileShare.Write);
           loFile.Seek(0, System.IO.SeekOrigin.End);
           loFile.Write(binLogString, 0, binLogString.Length);
           loFile.Close();
        }
   }
   catch { /*No need to catch the error here. */}
}
We are using two parameter 1. Exception and 2. String (source where we will pass the page url so we can understand on which page this error occured).
We are loging page URL, Error Message, InnerException and StackTrace. It's enough to understand the reason and page to fix the code.
You can create this method anywhere either in Business Logic Layer or on the Global.asax file itself.
Now open the Global.asax file and in Application_Error method add following lines
void Application_Error(object sender, EventArgs e) {
    // Code that runs when an unhandled error occurs
    Exception ex = Server.GetLastError();
    LogError(ex, HttpContext.Current.Request.Path);
    Server.ClearError();
}
Add a file on the root with name "Errorlog.txt" and give read and write permission to it so new error can be write in this file, on develpment machine no need to give the read write permission becuase it already have it.
Now your application will log every error in your application to a text file name "Errorlog.txt" on the root of the application.

Log error in a text file in ASP.Net

It’s good practice to log all the error into a file or database so in future you can check, how your application is working, and is there any issue which is not caught by Q.A. team.
Really it's helpful to understand and caught the issues after deploying the application on production server.
Create a method to log the error into a file:
public void LogError(Exception ex, String source)
{
   try
   {
       String LogFile = HttpContext.Current.Request.MapPath("/Errorlog.txt");
       if (LogFile != "")
       {
           String Message = String.Format("{0}{0}=== {1} ==={0}{2}{0}{3}{0}{4}{0}{5}"
                    , Environment.NewLine
                    , DateTime.Now
                    , ex.Message
                    , source
                    , ex.InnerException
                    , ex.StackTrace);
           byte[] binLogString = Encoding.Default.GetBytes(Message);

           System.IO.FileStream loFile = new System.IO.FileStream(LogFile
                     , System.IO.FileMode.OpenOrCreate
                     , System.IO.FileAccess.Write, System.IO.FileShare.Write);
           loFile.Seek(0, System.IO.SeekOrigin.End);
           loFile.Write(binLogString, 0, binLogString.Length);
           loFile.Close();
        }
   }
   catch { /*No need to catch the error here. */}
}
We are using two parameter 1. Exception and 2. String (source where we will pass the page url so we can understand on which page this error occured).
We are loging page URL, Error Message, InnerException and StackTrace. It's enough to understand the reason and page to fix the code.
You can create this method anywhere either in Business Logic Layer or on the Global.asax file itself.
Now open the Global.asax file and in Application_Error method add following lines
void Application_Error(object sender, EventArgs e) {
    // Code that runs when an unhandled error occurs
    Exception ex = Server.GetLastError();
    LogError(ex, HttpContext.Current.Request.Path);
    Server.ClearError();
}
Add a file on the root with name "Errorlog.txt" and give read and write permission to it so new error can be write in this file, on develpment machine no need to give the read write permission becuase it already have it.
Now your application will log every error in your application to a text file name "Errorlog.txt" on the root of the application.

Friday, 20 September 2013

Encrypt and decrypt username,password and store in Sql Server database using asp.net C#,Vb

Introduction: In this article I am going to explain with example How to encrypt and decrypt or we can say encode and decode login credentials e.g. username and password and store in Sql Server Database using Asp.net with both C# and Vb.Net Language.
 
Encrypt and Decrypt user Name and Password and save in sql server database using asp.net
Click on the image to enlarge
Description: In previous article I explained How to Encrypt Query String in asp.net(C#, VB) | Encrypting and Decrypting Query String in asp.net(C#, VB) and How to Encrypt connection string in web.config | How to Decrypt connection string in web.config and Encrypt and Decrypt connectionString in web.config file using code in asp.net.
Now in this article I will store/save User Name and Password in the Sql Server Database in encrypted form. Also the Encrypted credentials i.e. user Name and Password will be binded in the first Grid View and In the second Grid View decrypted credentials will be binded as shown in the demo image above.

Implementation: Let’s create an asp.net web application to understand the concept of encrypting and decrypting username and password.
  • First of all we need to create a DataBase in Sql Server. So create a Database and name it “MyDatabase” or whatever you want. Create a table with the fields and Data type as shown below and name it “Tb_Login”.

Column Name
Data Type
Id
Int(Primary Key so set is identity=true)
Name
varchar(100)
UserName
varchar(100)
Password
varchar(100)


  • Now In the web.config file create the connection string to connect the web application with the database as:
<connectionStrings>
    <add name="conStr" connectionString="Data Source=LocalServer;Initial Catalog=MyDataBase;Integrated Security=True"/>
  </connectionStrings>
 
Source Code
  • In the <Form> tag of the design page (.aspx) place 3 TextBox control, a label and Two Button controls from the standard category of the visual studio’s toolbox, 3 RequiredFieldValidator validation controls for each textbox from the validation Category, and also place Two GridView data controls from the Data category and design the page as shown below.      
<div>
    <fieldset style="width:400px;">
    <legend>
    Signup form
    </legend>
    <table>
       <tr>
    <td>Name: </td><td>
        <asp:TextBox ID="txtName" runat="server"></asp:TextBox><asp:RequiredFieldValidator
            ID="rfvName" runat="server" ErrorMessage="Please enter Name"
               ControlToValidate="txtName" Display="Dynamic" ForeColor="Red"
               SetFocusOnError="True"></asp:RequiredFieldValidator></td>
    </tr>
    <tr>
    <td>User Name: </td><td>
        <asp:TextBox ID="txtUserName" runat="server"></asp:TextBox><asp:RequiredFieldValidator
            ID="rfvuserName" runat="server"
            ErrorMessage="Please enter User Name" ControlToValidate="txtUserName"
            Display="Dynamic" ForeColor="Red" SetFocusOnError="True"></asp:RequiredFieldValidator></td>
    </tr>
       <tr>
    <td>Password: </td><td>
        <asp:TextBox ID="txtPwd" runat="server" TextMode="Password"></asp:TextBox><asp:RequiredFieldValidator
            ID="rfvpwd" runat="server"
               ErrorMessage="Please enter  Password" ControlToValidate="txtPwd"
               Display="Dynamic" ForeColor="Red" SetFocusOnError="True"></asp:RequiredFieldValidator></td>
    </tr>
       <tr>
    <td>&nbsp;</td><td>
        <asp:Button ID="btnSubmit" runat="server" Text="Submit"onclick="btnSubmit_Click"/>
         <asp:Button ID="btnReset" runat="server" Text="Reset" CausesValidation="False"
               onclick="btnReset_Click" /></td>
    </tr>
    <tr>
    <td colspan="2">
        <asp:Label ID="lblSignUpStatus" runat="server" Text="" style="color: #006600"></asp:Label></td>
    </tr>
    </table>
    </fieldset>
    <br />
     <fieldset style="width:400px;">
    <legend>Encrypted Credentials in GridView</legend>
    <asp:GridView ID="grdEncryptedCredentials" runat="server"
            AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333"
            GridLines="None" Width="362px">
            <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
        <Columns>
        <asp:BoundField HeaderText="Name" DataField="Name" />
        <asp:BoundField HeaderText="User Name" DataField="UserName" />
        <asp:BoundField HeaderText="Password" DataField="Password" />
        </Columns>
            <EditRowStyle BackColor="#999999" />
            <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
            <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333"/>
            <SortedAscendingCellStyle BackColor="#E9E7E2" />
            <SortedAscendingHeaderStyle BackColor="#506C8C" />
            <SortedDescendingCellStyle BackColor="#FFFDF8" />
            <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
        </asp:GridView>
    </fieldset>
        <br />
     <fieldset style="width:400px;">
        <legend>Decrypted Credentials in GridView</legend>
        <asp:GridView ID="grdDecryptedCredentials" runat="server"
            AutoGenerateColumns="False" BackColor="#DEBA84" BorderColor="#DEBA84"
            BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2"
             Width="369px">
        <Columns>
        <asp:BoundField HeaderText="Name" DataField="Name" />
        <asp:BoundField HeaderText="User Name" DataField="UserName" />
        <asp:BoundField HeaderText="Password" DataField="Password" />
        </Columns>
                    <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
                    <HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
                    <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
                    <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
                    <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White"/>
                    <SortedAscendingCellStyle BackColor="#FFF1D4" />
                    <SortedAscendingHeaderStyle BackColor="#B95C30" />
                    <SortedDescendingCellStyle BackColor="#F1E5CE" />
                    <SortedDescendingHeaderStyle BackColor="#93451F" />
        </asp:GridView>
        </fieldset>
    </div>


C#.Net Code for encrypting and decrypting username and password and save in Sql Server Database 
  • In the code behind file (.aspx.cs) write the code as:
First include these following namespace also:

using System.Security.Cryptography;
using System.IO;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

Then write the code as:

 SqlConnection con = newSqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            BindEncryptedCredentials();
            BingDecryptedCredentials();
        } 
    }

    private void BindEncryptedCredentials()
    {      
        SqlCommand cmd = new SqlCommand("select * from Tb_Login", con);
        try
        {           
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }
            SqlDataAdapter adp = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            adp.Fill(dt);

            if (dt.Rows.Count > 0)
            {              
                grdEncryptedCredentials.DataSource = dt;
                grdEncryptedCredentials.DataBind();
            }
            else
            {
                grdEncryptedCredentials.DataSource = null;
                grdEncryptedCredentials.DataBind();
            }
        }
        catch (Exception ex)
        {
            Response.Write("Error occured :" + ex.Message.ToString());
        }
        finally
        {
            cmd.Dispose();
            con.Close();
        }    
    }

    private void BingDecryptedCredentials()
    {
        SqlCommand cmd = new SqlCommand("select * from Tb_Login", con);
        try
        {
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }
            SqlDataAdapter adp = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            adp.Fill(dt);
       
            if (dt.Rows.Count > 0)
            {
                for ( int i = 0; i < dt.Rows.Count; i++)
                {
                    string uName = dt.Rows[i]["userName"].ToString();
                    string pwd = dt.Rows[i]["Password"].ToString();
                  
                    dt.Rows[i]["userName"]= Decrypt(uName);
                    dt.Rows[i]["Password"] = Decrypt(pwd);
                }
                dt.AcceptChanges();
                grdDecryptedCredentials.DataSource = dt;
                grdDecryptedCredentials.DataBind();           
            }    
            else
            {
                grdDecryptedCredentials.DataSource = null;
                grdDecryptedCredentials.DataBind();
            }
        }
        catch (Exception ex)
        {
            Response.Write("Error occured :" + ex.Message.ToString());
        }
        finally
        {
            cmd.Dispose();
            con.Close();
        }
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        string uName = string.Empty;
        string uPwd = string.Empty;
        SqlCommand cmd = new SqlCommand("insert into Tb_Login(Name,UserName,Password) values (@Name,@UserName,@Password)", con);
        if (con.State == ConnectionState.Closed)
        {
            con.Open();
        }
        try
        {
            uName = Encrypt(txtUserName.Text.Trim());
            uPwd = Encrypt(txtPwd.Text.Trim());
            cmd.Connection = con;
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.AddWithValue("@Name", txtName.Text.Trim());
            cmd.Parameters.AddWithValue("@UserName", uName);
            cmd.Parameters.AddWithValue("@Password", uPwd);
            cmd.ExecuteNonQuery();
            lblSignUpStatus.Text = "Record Successfully submitted";
            Clear_Controls();          
            BindEncryptedCredentials();
            BingDecryptedCredentials();        
        }
        catch (Exception ex)
        {
            Response.Write("Error occured: " + ex.Message.ToString());           
        }
        finally
        {
            uName = string.Empty;
            uPwd = string.Empty;
            con.Close();
            cmd.Dispose();
        }
    }       
   
    public string Encrypt(string str)
    {
        string EncrptKey = "2013;[pnuLIT)WebCodeExpert";
        byte[] byKey = { };
        byte[] IV = { 18, 52, 86, 120, 144, 171, 205, 239 };
        byKey = System.Text.Encoding.UTF8.GetBytes(EncrptKey.Substring(0, 8));
        DESCryptoServiceProvider des = new DESCryptoServiceProvider();
        byte[] inputByteArray = Encoding.UTF8.GetBytes(str);
        MemoryStream ms = new MemoryStream();
        CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey, IV),CryptoStreamMode.Write);
        cs.Write(inputByteArray, 0, inputByteArray.Length);
        cs.FlushFinalBlock();
        return Convert.ToBase64String(ms.ToArray());
    }

    public string Decrypt(string str)
    {
        str = str.Replace(" ""+");
        string DecryptKey = "2013;[pnuLIT)WebCodeExpert";
        byte[] byKey = { };
        byte[] IV = { 18, 52, 86, 120, 144, 171, 205, 239 };
        byte[] inputByteArray = new byte[str.Length];

        byKey = System.Text.Encoding.UTF8.GetBytes(DecryptKey.Substring(0, 8));
        DESCryptoServiceProvider des = new DESCryptoServiceProvider();
        inputByteArray = Convert.FromBase64String(str.Replace(" ""+"));
        MemoryStream ms = new MemoryStream();
        CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV),CryptoStreamMode.Write);
        cs.Write(inputByteArray, 0, inputByteArray.Length);
        cs.FlushFinalBlock();
        System.Text.Encoding encoding = System.Text.Encoding.UTF8;
        return encoding.GetString(ms.ToArray());
    }

    private void Clear_Controls()
    {
        txtName.Text = string.Empty;
        txtPwd.Text = string.Empty;
        txtUserName.Text = string.Empty;       
        txtName.Focus();
    }

    protected void btnReset_Click(object sender, EventArgs e)
    {
        Clear_Controls();
        lblSignUpStatus.Text = string.Empty;
    }