Thursday, November 22, 2012

Remove Duplicate Rows from DataBase in Sql Server

SELECT * FROM Tab_Test WHERE serial_num NOT IN (SELECT MIN(serial_num) FROM dbo.Tab_Test GROUP BY col1,col2)

serial_num is an auto indentity column

DELETE FROM Tab_Test WHERE serial_num NOT IN (SELECT MIN(serial_num) FROM dbo.Tab_Test GROUP BY col1,col2)

Tuesday, November 6, 2012

Upload Data from CSV file to Sql Server

1.FileUploader1 is a fileUploadControl
2.name,fathername,address are the columns which same as csv file name and sql server database 
3.G:\\FileName is your local computer path where CSV file save.
           

FileUploader1.SaveAs("G:\\FileName\\" + FileUploader1.FileName);

                // You can get connected to driver either by using DSN or connection string

                // Create a connection string as below, if you want to use DSN less connection.
The DBQ attribute sets the path of directory which contains CSV files

                string strConnString = "Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=" + "G:\\FileName\\" + ";Extensions=asc,csv,tab,txt;Persist Security Info=False";


                string Query;

                DataSet ds = new DataSet();
                System.Data.Odbc.OdbcConnection conn;

                //Create connection to CSV file


                conn = new System.Data.Odbc.OdbcConnection(strConnString.Trim());

                // For creating a connection using DSN, use following line

                //Open the connection
                conn.Open();


                //Fetch records from CSV
                Query = "select * from [" + FileUploader1.FileName.ToString() + "]";

                System.Data.Odbc.OdbcDataAdapter oledaObj = new System.Data.Odbc.OdbcDataAdapter(Query, conn);

                //Fill dataset with the records from CSV file
                oledaObj.Fill(ds);


                int j = 0;
                if (ds.Tables[0].Rows.Count > 0)
                {

                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        try
                        {

                            DataSet ds2 = new DataSet();
                            SqlDataAdapter adap = new SqlDataAdapter("INSERT INTO TableDetails (name,fathername,address)  VALUES('" + ds.Tables[0].Rows[i]["name"].ToString() + "','" + ds.Tables[0].Rows[i]["fathername"].ToString() + "','" + ds.Tables[0].Rows[i]["address"].ToString() + "')", ConfigurationManager.ConnectionStrings["Conn"].ConnectionString.ToString());
                            adap.Fill(ds);
                            j++;
                        }
                        catch (Exception ex)
                        {

                        }
                    }


                    LblMsg.Text = "File Uploaded Successfully, No. of record save - " + System.Convert.ToString(j);
                    LblMsg.Visible = true;


                }
                conn.Close();

Thursday, October 18, 2012

Finding duplicate Row in sql Server

Select name from Table_Personal group by name having (count(*) >1)

Update Top 1 row in Sql Server

Update Top (1) Tab_Test set name='' where serialNum=1

Sunday, October 14, 2012

Set Sql Server Time Out in ASP.Net

How to Solve timeout expired problem:

simply Add in your web.config file inside ConnectionString;
<connectionStrings>
<add name="connect" connectionString="DataSource=MYPC;Initial Catalog=North;TimeOut=120"/>
</connectionStrings>
If u use a SqlCommand object in your code:
Then use

SqlCommand cmd=new SqlCommand();
cmd.TimeOut="180";

Sunday, September 16, 2012

Automatically Refresh Page in ASP.NET

Simply Add a meta tag in design code inside header tag

<meta http-equiv="refresh" content="15" /> 

Monday, August 27, 2012

READ AND WRITE COOKIES IN ASP.NET

 At Page load event


//////Read Cookie
 if(Request.Cookies["Cookiename"]!=null)
{
HttpCookie cok=new HttpCookie("Cookiename");
LblCookie.Text=cok.Value ;
}
//////



/////write cookie

HttpCookie cok=new HttpCookie("Cookiename");
cok.Value=txtUsername.Text;
Response.Cookies.Add(cok);



//////

Sunday, August 12, 2012

Character Count in asp.net


Define Script in design side

 <script type="text/javascript">
 
        function textCounter(field, countfield, maxlimit,msg,word)
        {
           if (field.value.length > maxlimit)
               field.value = field.value.substring(0, maxlimit);
           else
           {
               countfield.value =maxlimit - field.value.length;
               word.value=field.value.length;
               if(word.value > 160  && word.value <= 321)
                msg.value="2";
                else if(word.value > 321 && word.value <= 482)
                   msg.value="3";
                 
                    else if(word.value > 482 && word.value <= 643)
                   msg.value="4";
                 
                    else if(word.value > 643 && word.value <= 800)
                   msg.value="5";
                 
                   else
                         msg.value="1";
               
           }
        }
 
  </script>




<asp:TextBox ID="TxtMessage" runat="server" Height="92px"
            onkeydown="textCounter(this, this.form.countLen, 800,this.form.msgcount,this.form.wcount);"
            onkeyup="textCounter(this, this.form.countLen, 800,this.form.msgcount,this.form.wcount);" TextMode="MultiLine"></asp:TextBox>


<input maxlength="3" name="countLen" readonly="readonly" size="3"
            style="width: 26px; height: 16px;" type="text" value="800"
            style="border:none; border-color:White; background-color:White;" />Characters Left<br />
        <font color="red">
        Total
           
      <input name="wcount" value="0" type="text" readonly="readonly"
           
           
            style="border:medium none White; background-color:White; width: 24px; height: 15px; color:Red;" />Word(s)
        and&nbsp;<input name="msgcount" value="0" type="text" readonly="readonly"
            style="border:medium none White; background-color:White; width: 14px; height: 15px; color:Red;" />Message(s)

Saturday, June 16, 2012

How To Set Default focus and default button click

 <form id="form1" runat="server" defaultbutton="Btn_Log" defaultfocus="txtUname">

</form>

Monday, May 7, 2012

Create Table from another Table in SQL SERVER

select * into Newtable from oldtable where name like 'a%'

 Above query create table with name Newtable and copy all data from oldtable,


I f u want to create only structure as same as old table then you
can use :

WHERE 1=2

select * into   Newtable from oldtable where 1=2




Saturday, April 28, 2012

How to add days in Date in ASP.NET

DateTime dt=new DateTime();
dt=System.DateTime.Now.Date;
dt.AddDays(2);

How To Resize image in asp.net at upload

 System.Drawing.Image imageToBeResized = System.Drawing.Image.FromStream(FleUpPhoto.PostedFile.InputStream);
                    int imageHeight = imageToBeResized.Height;
                    int imageWidth = imageToBeResized.Width;
                    int maxHeight = 240;
                    int maxWidth = 320;
                    imageHeight = (imageHeight * maxWidth) / imageWidth;
                    imageWidth = maxWidth;

                    if (imageHeight > maxHeight)
                    {
                        imageWidth = (imageWidth * maxHeight) / imageHeight;
                        imageHeight = maxHeight;
                    }

                    Bitmap bitmap = new Bitmap(imageToBeResized, imageWidth, imageHeight);
                    System.IO.MemoryStream stream = new MemoryStream();
                    bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
                    stream.Position = 0;
                    byte[] image = new byte[stream.Length + 1];
                    stream.Read(image, 0, image.Length);

 SqlConnection myConnection = new SqlConnection(ConfigurationSettings.AppSettings["Connect"]);

 SqlCommand storeimage = new SqlCommand("INSERT INTO TablePic" + "(Content, ImgType, Size,imageSeen) " + " values (@image, @imagetype, @imagesize,@imgSeen)", myConnection);
                   
                    storeimage.Parameters.Add("@image", SqlDbType.Binary, image.Length).Value = image;
                    storeimage.Parameters.Add("@imagetype", SqlDbType.VarChar, 100).Value = FleUpPhoto.PostedFile.ContentType;
                    storeimage.Parameters.Add("@imagesize", SqlDbType.BigInt, 99999).Value = FleUpPhoto.PostedFile.ContentLength;
                    storeimage.Parameters.Add("@imgSeen", SqlDbType.VarChar, 100).Value = "Off";
                       myConnection.Open();
                    storeimage.ExecuteNonQuery();
                    myConnection.Close();

Thursday, April 26, 2012

Open new page as a popup window in asp.net



<script type="text/javascript" language="javascript">
        function changeScreenSize(w, h) {
            window.resizeTo(w, h)
        }
</script>

call this script at body onload
<body onload="changeScreenSize(500,300)" >

</body>

Tuesday, April 24, 2012

How to check nullify in SQL SERVER

Select * from TblEmp where address IS NULL


Select * from TblEmp where address IS NOT NULL

Update TblEmp set empcode='E021' where address IS NOT NULL 

How To Disabled right click,copy and paste in asp.net

Define in body tag at design side in asp.net

<body oncontextmenu="return false;" onload="start()" onselectstart="return false;" oncopy="return false;" onpaste="return false;">

Sunday, March 11, 2012

How to show message box with update panel in asp.net


 ScriptManager.RegisterStartupScript(TxtMobileNumber,typeof(Page), "Open Window", "alert('Mobile Number Already Exists')", true);

Saturday, March 10, 2012

GET LATEST INDEX OF CHECKBOX LIST


  string lastValue = string.Empty;
    int lastIndex=0;

        foreach (ListItem listitem in chkSec.Items)
        {
            if (listitem.Selected)
            {
                int thisIndex = chkSec.Items.IndexOf(listitem);

                if (lastIndex < thisIndex)
                {
                    lastIndex = thisIndex;
                    lastValue = listitem.Value;
                }
            }
        }