Thursday, November 7, 2013

A potentially dangerous Request.Form value was detected from the client

if you are getting this error then we need to add validaterequest="false" line in web page like

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

Tuesday, November 5, 2013

encrypt and decrypt connectionstring in web config

string connectionString = "data source=123.456.789.00,1234\\abcdb;database=databasename;uid=sa;pwd=123";
            Byte[] a = System.Text.ASCIIEncoding.ASCII.GetBytes(connectionString);
            string encryptedConnectionString = Convert.ToBase64String(a);
         
            Byte[] b = Convert.FromBase64String(ConfigurationSettings.AppSettings["defaultConnection"]);          
            string decryptedConnectionString = System.Text.ASCIIEncoding.ASCII.GetString(b);

http://www.codersource.net/2010/02/03/securing-connection-strings-in-asp-net/

Thursday, July 11, 2013

Asp.Net C# Example - How To Use SqlBulkCopy To Insert Huge Number Of Records Into Database

If We Get Huge Number Of Records To Insert Into Database In Less Time Then We Use 'SqlBulkCopy' In   C#. The Example Of How To Use SqlBulkCopy In C# To Insert Excel Sheet Records Into Database.

Create A Table : 'EXCEL_TABLE' In Sql Server

CREATE TABLE EXCEL_TABLE
(
UID INT IDENTITY(1,1),
UNAME VARCHAR(200)
)

And The Design Page In Visual Studio 2008 is:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
 
    <table width="100%" border="0" cellspacing="0" cellpadding="0">
        <tr>
            <td align="center" valign="middle" bgcolor="#f8efeb" style="height: 20px">
                <table width="100%" border="0" cellspacing="0" cellpadding="0">
                    <tr>
                        <td width="46%" align="left">
                            <table width="250" border="0" cellspacing="0" cellpadding="0">
                                <tr>
                                    <td width="5">
                                    </td>
                                    <td width="350">
                                       
                                        <a href="#">
<asp:Label ID="lblTitle" runat="server" Text="Import Data"></asp:Label></a><span class="rar">>></span>
                                    </td>
                                </tr>
                            </table>
                        </td>
                        <td align="right" valign="middle" colspan="2">
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
        <tr>
            <td align="center">

            </td>
        </tr>
        <tr>
            <td align="center">

                <table id="tabErrMess" visible="false" runat="server" width="380" height="25" border="0"
                    cellpadding="0" cellspacing="0">
                    <tr>
                        <td align="center" valign="middle">
                            <table width="460px" border="0" cellspacing="0" cellpadding="0">
                                <tr>                                
                                    <td align="left" >
                                        <asp:Label ID="lblMessage" runat="server"></asp:Label>
                                    </td>
                                </tr>
                            </table>
                        </td>
                    </tr>
                </table>

             
            </td>
        </tr>

        <tr>
            <td align="left" style="padding-left: 100px">
               <asp:Label ID="lblTitle1" runat="server" Text="Import Data"></asp:Label>
            </td>
        </tr>
        <tr>
            <td align="center" style="height: 5px;">
            </td>
        </tr>
        <tr>
            <td align="center" valign="middle">
                <table width="80%" border="0" cellpadding="0" cellspacing="0" >
                    <tr>
                        <td height="8">
                        </td>
                        <td align="center" bgcolor="#f8efeb">
                        </td>
                        <td>
                        </td>
                    </tr>
                    <tr>
                        <td>
                        </td>
                        <td align="center" bgcolor="#f8efeb">
                        </td>
                        <td>
                        </td>
                    </tr>
                    <tr>
                        <td>
                        </td>
                        <td align="center" bgcolor="#f8efeb">
                            <table width="750" border="0" cellpadding="0" cellspacing="0">
                                <tr>
                                    <td>
                                    </td>
                                    <td width="99%" height="10" bgcolor="#f8efeb">
                                    </td>
                                    <td>
                                    </td>
                                </tr>
                                <tr>
                                    <td>
                                    </td>
                                    <td align="center" valign="top" bgcolor="#f8efeb">
                                        <table border="0" cellspacing="0" cellpadding="1">                                                                                                                                  
                                              <tr>
                                                <td align="left" height="25" valign="middle">
                                                    File
                                                </td>
                                                <td align="center" valign="middle">
                                                    :
                                                </td>
                                                <td align="left" valign="middle">
                                                    <asp:FileUpload ID="fleUpload" runat="server" />
                                                </td>
                                            </tr>                                                                                                                                  
                                        </table>
                                    </td>
                                    <td>
                                    </td>
                                </tr>
                                <tr>
                                    <td>
                                    </td>
                                    <td align="center" style="height: 10px" valign="top" bgcolor="#f8efeb">
                                    </td>
                                    <td>
                                    </td>
                                </tr>
                                <tr>
                                    <td>
                                    </td>
                                    <td align="center" valign="top" bgcolor="#f8efeb">
                                        <table border="0" cellspacing="0" cellpadding="0">
                                            <tr>
                                                <td>
                                                    <table border="0" cellspacing="0" cellpadding="1">
                                                        <tr>
                                                            <td>
                                                            </td>
                                                            <td align="left">
      <asp:Button ID="btnSAVE" Width="45px" runat="server" Text="Save" OnClick="btnSAVE_Click" />
                                                            </td>
                                                        </tr>
                                                    </table>
                                                </td>
                                                <td style="width: 10px;">
                                                </td>
                                                <td>
                                                    <table border="0" cellspacing="0" cellpadding="1">
                                                        <tr>
                                                            <td>
                                                            </td>
                                                            <td align="left">
   <asp:Button ID="btnCancel" runat="server" Width="58px" Text="Cancel" OnClick="btnCancel_Click" />
                                                            </td>
                                                        </tr>
                                                    </table>
                                                </td>
                                            </tr>
                                        </table>
                                    </td>
                                    <td>
                                    </td>
                                </tr>
                                <tr>
                                    <td>
                                    </td>
                                    <td align="center" valign="top" bgcolor="#f8efeb">
                                    </td>
                                    <td>
                                    </td>
                                </tr>
                            </table>
                        </td>
                        <td>
                        </td>
                    </tr>
                    <tr>
                        <td>
                        </td>
                        <td align="center" height="10" bgcolor="#f8efeb">
                        </td>
                        <td>
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
        <tr>
            <td align="center" style="height: 8px">
            </td>
        </tr>
    </table>
    </div>
    </form>
</body>
</html>



And The Source Code:

using System;
using System.Web;
using System.Web.UI;
using System.Data.OleDb;
using System.IO;

protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnSAVE_Click(object sender, EventArgs e)
    {
        string strConnection = ConfigurationManager.AppSettings["defaultConnection"];

          #region xlsx
            if (fleUpload.PostedFile.ContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
            {
                try
                {
                    string strDocument = fleUpload.PostedFile.FileName;
                    strDocument = DateTime.Now.Day.ToString() + "_" + DateTime.Now.Month.ToString() + "_" + DateTime.Now.Year.ToString() + "_" + DateTime.Now.Hour.ToString() + "_" + DateTime.Now.Minute.ToString() + "_" + DateTime.Now.Second.ToString() + strDocument.Substring(strDocument.LastIndexOf("\\") + 1);
                    string strAbsolutePathOfFile = Server.MapPath("ExcelSheet/" + strDocument);                  
                    fleUpload.PostedFile.SaveAs(strAbsolutePathOfFile);

                    string ext = Path.GetExtension(strDocument);

                    if (ext == ".xlsx")
                    {
                        string sCSVConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strAbsolutePathOfFile + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES\";";

                        using (OleDbConnection connection = new OleDbConnection(sCSVConnectionString))
                        {
                            connection.ConnectionString = sCSVConnectionString;
                            connection.Open();

                            using (DbCommand command = connection.CreateCommand())
                            {
                                command.CommandText = "SELECT * FROM [Sheet1$]";

                                using (DbDataReader dr = command.ExecuteReader())
                                {
                                    while (dr.Read())
                                    {
                                        SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);
                                        sqlBulk.BulkCopyTimeout = 0;
                                        sqlBulk.BatchSize = 2;

//You Can Use this BatchSize based on Your records You are going to insert

                                        sqlBulk.DestinationTableName = "EXCEL_TABLE";
                                        sqlBulk.ColumnMappings.Add("registrant_name","UNAME");
                                        sqlBulk.WriteToServer(dr);
                                    }

                                    dr.Close();
                                }
                            }
                            tabErrMess.Visible = true;
                            lblMessage.Text = "All Records Inserted Successfully";
                            connection.Close();
                        }
                    }
                }
                catch (Exception ex)
                {
                    ClientScript.RegisterClientScriptBlock(Page.GetType(), "alert", "alert('" + ex.Message + ".');", true);
                    return;
                }
            }
            else
            {
                tabErrMess.Visible = true;
                lblMessage.Text = "Please Upload Xlsx File";              
            }
        #endregion
    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {

    }

In Web.Config:

<appSettings>
<add key="defaultConnection" value="Data Source=.;Initial Catalog='database name';uid=sa;pwd=123;"/>
</appSettings>

The Sample Excel File Which I used , registrant_name is the header of that particular column.


The design Page of Our Example.



After Inserting All Records In the Database the Page Displays Like This


As Our Excel Sheet Contains A Header so the header record is not inserted and the remaining records are inserted into the database successfully.
If we insert more than 50000 records at a time it takes not more than 5 sec to insert into database.



Wednesday, July 10, 2013

How to Count No Of Records In A Excel Sheet Using Asp.Net C#

Here We Will Discuss About How to Count No Of Records In A Excel Sheet Using Asp.Net C#

Design Page:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <table>
           <tr>
                  <td class="c1">
                     </td>
                        <td align="center" valign="top" bgcolor="#f8efeb">
                            <table border="0" cellspacing="0" cellpadding="1">
                                     <tr>
                                    <td align="left" class="s6" height="25" valign="middle">
                                                    File
                                     </td>
                                      <td align="center" class="s6" valign="middle">
                                        :
                                      </td>
                                      <td align="left" valign="middle">
                                        <asp:FileUpload ID="fleUpload" runat="server" />
                                         </td>
                                         </tr>
                                        </table>
                                </td>
                                <td class="c2">
                                 </td>
                                </tr>
                                <tr>
                                 <td class="c1">
                                  </td>
                                  <td align="center" style="height: 10px" valign="top" bgcolor="#f8efeb">
                                  </td>
                                 <td class="c2">
                                  </td>
                                </tr>
                                <tr>
                               <td class="c1">
                                 </td>
                                  <td align="center" valign="top" bgcolor="#f8efeb">
                                   <table border="0" cellspacing="0" cellpadding="0">
                                    <tr>
                                         <td>
                                            <table border="0" cellspacing="0" cellpadding="1">
                                                <tr>
                                                <td class="save">
                                                </td>
                                                 <td align="left">
     <asp:Button ID="btnSAVE" Width="45px" runat="server" Text="Count" OnClick="btnSAVE_Click" />
                                                  </td>
                                                  </tr>
                                                 </table>
                                                </td>
                                                <td style="width: 10px;">
                                                </td>
                                                <td>
                                               <table border="0" cellspacing="0" cellpadding="1">
                                                <tr>
                                                 <td class="cancel">
                                                   </td>
                                                       <td align="left">
   <asp:Button ID="btnCancel" runat="server" Width="48px" Text="Cancel" OnClick="btnCancel_Click" />
                                                     </td>
                                                   </tr>
                                               </table>
                                                </td>
                                         </tr>
                                        </table>
                                        <br />
                                        <asp:Label ID="lblMessage" runat="server" ForeColor="Red"></asp:Label>
                                    </td>
                                    <td>
                                    </td>
                                </tr>
    </table>
    </div>
    </form>
</body>
</html>

Code Page:

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.OleDb;
using System.IO;

public partial class _Default : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void btnSAVE_Click(object sender, EventArgs e)
    {
        #region Upload Excel

                try
                {
                    string strDocument = fleUpload.PostedFile.FileName;
                    strDocument = DateTime.Now.Day.ToString() + "_" + DateTime.Now.Month.ToString() +                    "_" + DateTime.Now.Year.ToString() + "_" + DateTime.Now.Hour.ToString() + "_" +  DateTime.Now.Minute.ToString() + "_" + DateTime.Now.Second.ToString() + strDocument.Substring(strDocument.LastIndexOf("\\") + 1);
               string strAbsolutePathOfFile = Server.MapPath("Excel/" + strDocument);                  
               fleUpload.PostedFile.SaveAs(strAbsolutePathOfFile);

                    string ext = Path.GetExtension(strDocument);

                    if (ext == ".xlsx")
                    {

                        #region Count No Of Records

                        string connectionString;
                        string count = "";

                        connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strAbsolutePathOfFile + ";Mode=ReadWrite;Extended Properties=\"Excel 12.0;HDR=NO\"";

                        string SQL = "SELECT COUNT (*) FROM [Sheet1$]";

                        using (OleDbConnection conn = new OleDbConnection(connectionString))
                        {
                            conn.Open();

                            using (OleDbCommand cmd = new OleDbCommand(SQL, conn))
                            {
                                using (OleDbDataReader reader = cmd.ExecuteReader())
                                {
                                    reader.Read();
                                    count = reader[0].ToString();
                                    lblMessage.Text = " There are " + count + " Records In The Excel Sheet";
                                }
                            }

                            conn.Close();
                        }

                        #endregion

                    }

                    else
                    {
                        lblMessage.Text = "Please Enter Xlsx File Only";
                    }
                }

                catch (Exception ex)
                {
                    ClientScript.RegisterClientScriptBlock(Page.GetType(), "alert", "alert('" + ex.Message + ".');", true);
                    lblMessage.Text = "" + ex.Message + "";
                    return;
                }

        #endregion

    }
 





After Selecting The File Using File Upload Control And After Clicking the Count Button . The Process Would Count No Of Records In The Uploaded Excel File


Wednesday, June 5, 2013

How To Merge Multiple CSV Files Into Single CSV File Using Command Prompt

While Uploading CSV Files To Database You May Find Unformated Data In CSV File While You Copy Manually. So To Avoid Such Condition We Can Merge Multiple CSV Files To Single CSV File Without Any Format Errors.

So We Have Two Csv File To Merge.
Go To Start Menu,Open A Command Prompt.And Next Direct The Command Prompt To file directory where the csv files are contained.So All I need to do is type "CD \MergeCsv".
Next For Merging the Csv Files use the following commands
"Copy *.csv file3.csv"

Finally you can find the merged file in the same folder with file3.csv , 

Thursday, May 23, 2013

Asp.Net How to Convert To Different Time Zones Using C#


Here I will Explain How To Get The Server Times Of Different Countries Using C#

Some Times We Come Across Different Date And Time Zones To Display, So By Using The Following Code You Can Get Different Countries Date And Time.
     
        DateTime now = DateTime.Now;            //Displays Our System Time
        c.Text = "Time is " + now.ToString() + " in your System";      

        string zoneId = "Central European Standard Time";
        TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById(zoneId);
        DateTime result = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, tzi);
        a.Text = "Time is " + result + " in Denmark";

        string zoneId1 = "India Standard Time";
        TimeZoneInfo tzi1 = TimeZoneInfo.FindSystemTimeZoneById(zoneId1);
        DateTime result1 = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, tzi1);
        b.Text = "Time is " + result1 + " in India";

        string zoneId2 = "Central Standard Time";
        TimeZoneInfo tzi2 = TimeZoneInfo.FindSystemTimeZoneById(zoneId2);
        DateTime result2 = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, tzi2);
        c.Text = "Time is " + result2 + " in Chicago";

Output:



Ramayana story narrated by a kid

Hi everyone,
this post is just for fun , i got a mail from my sister and its really funny so thought of sharing with all who visit this blog.


"May be Two years back….one of the proud school in Chennai where all felt admission is impossible. to get UKG admission for my friend’s daughter I too went there.  For that admission my friend had studied a lot than his daughter J
 The child could not understand why they have bought her there.  Principal of the school is like “kadalora kavithai Jenifer” (one of the filmy characters).  When I smiled at her, she turned & that moment my friend realized there is no benefit by my presence L

When we are all standing, the school principal started to converse with the child…yes in English only.  This is one of most memorable interview I have ever witnessed in my life..

“ “What’s your name?”

“Sarithra”

“Good. Tell me something you know”

“I know many things. Tell me what you want”

Alas, there is no better point for not getting the admission. .Sarithra’s mother was trying to make up the situation but Jenifer stopped..

Turning to child…Jenifer said.. “Tell any rhymes or story which you know”

Again…”Which one you want Rhymes or Story?”

Well done, second wicket too gone. Jenifer was little bit angry about the reply

“Ok. .tell me a story”

“You want to hear what I studied or what I wrote”

Taken to surprise, Jenifer asked “Oh you write stories”

“Why should I not write?”

Now even I was taken aback and whispered to my friend “our whole generation is not going to get admission in this school”

But Jenefier was impressed with the answer, she & including us, would have not heard such a story in our life

“Ok, tell me story which you have written”

Sarithra said “ Ravanan kidnapped Sita to Srilanka”

Opening scene failed to fail an impress Jenifer but still she encouraged the child to continue

“Rama asked Hanuman’s help to rescue Sita.  Hanuman too agreed to help Rama”
 “Then”
‘“Now, Hanuman called his friend Spider man”.no one expected this twist in the story
 “Why?”
 “Because there are lot of mountains between India and Srilanka..if we have Spiderman we can go easily with his rope”
 “But Hanuman can fly isn’t it”
 “Yes. But he is having Sanjeevi Mountain on one hand so he cannot fly very fast”
 (I remember Hanuman’s picture in ABT parcel serviceJ)
 Now Jenifer is quiet, after a while Sarithra asked “Should I continue or not”..
 “Ok ok then”
 “Hanuman and Spiderman flew to Srilanka and rescued Sita.  Sita said Thanks to both”
 “Why”
 “When you are helped you should say Thanks”
 “Ok Ok then”
 “Hanuman now called Hulk.”
 All were surprised…she realized our curiosity and said  “ Now Sita is there, so to take her safely back to Rama..he called Hanuman”
 What logic??? But Jenifer asked…
 “Hanuman can carry Sita right?”
 “Yes. But he has Sanjeevi Mountain in one hand and has to hold spider man on the other”
 Jenifier could not control her smile…”So when they all started to India they met my friend Akshay”
 “How come Akshay there now”
 “Because its my story and I can bring any one there”
 Now Jenifer didn’t get angry but waited for the next twist
 “Then all started to India and landed at Chennai Velechery bus stop”
 Now I asked “ Why they have landed In Velechery bus stop?”
 “Because they forgot the way..& Hulk got an idea and called Dora”
 I came to know about Doremon only there…
 “Doremon came and she took Sita to Velechery Venus Colony…that’s all”. Finished the story with a smile
Now Jenifer asked “Why venus Colony?”
 "Because sita there & am Sita”
 Jenifer impressed and embraced the child. She has been admitted in UKG & gifter her with a Doremon doll."
J