Tuesday, January 26, 2010

Gridview Delete confirmation box using javascript in asp.net C#


In .aspx page
In .aspx.cs page
protected void gv_getdata_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int i = Convert.ToInt16(gv_getdata.Rows[e.RowIndex].Cells[1].Text);
string strQuery = “delete from tbl_account where id = @Id”;
SqlCommand cmd = new SqlCommand(strQuery, conn);
cmd.Parameters.Add(“@id”, SqlDbType.VarChar).Value = i;
conn.Close();
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
Response.Redirect(“viewaccount.aspx”);
}
Javascript:
function confirmDelete(evt)
{
return window.confirm(“Are you sure you want to delete this record?”);
}

User Registration in C#, Insert data in Sql Server

web Config For sql server
<add key=”test” value=”data source=servername;uid=”";pwd=”";initial catalog=”"”; Connect Timeout=900;pooling=’true’; Max Pool Size=900;”/>
.aspx.cs page
conn = new SqlConnection(ConfigurationManager.AppSettings["test"]);
conn.Open();
SqlCommand cmd = new SqlCommand(“spregistration”, conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue(“@companyname”, txtcompanyname.Text);
cmd.Parameters.AddWithValue(“@title”, droptitle.Text);
cmd.Parameters.AddWithValue(“@name”, txtname.Text);
cmd.Parameters.AddWithValue(“@designation”, txtdesignation.Text);
cmd.ExecuteNonQuery();
cmd.Connection.Close();
Stored Procedure:
CREATE  PROCEDURE spregistration
@companyname varchar (200),
@title varchar (200),
@name varchar (200),
@designation varchar (50)
AS
INSERT INTO [tbl_registration]
(companyname,title,[name],designation)
VALUES (@companyname,@title,@name,@designation)
RETURN
GO
Click Here!

c# code for user login

web Config For sql server
<add key=”test” value=”data source=servername;uid=””;pwd=””;initial catalog=”””; Connect Timeout=900;pooling=’true’; Max Pool Size=900;”/>
.aspx page
conn = new SqlConnection(ConfigurationManager.AppSettings["test"]);
strQuery = “select * from tbl_admin where username=@userName and password=@password and status=’Active’”;
SqlCommand cmd = new SqlCommand(strQuery, conn);
cmd.Parameters.Add(“@userName”, SqlDbType.VarChar).Value = txtusername.Text;
cmd.Parameters.Add(“@password”, SqlDbType.VarChar).Value = password;
conn.Open();
try
{
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.Read())
{
FormsAuthentication.RedirectFromLoginPage(txtusername.Text, false);
FormsAuthentication.RedirectFromLoginPage(txtpassword.Text, false);
FormsAuthentication.RedirectFromLoginPage(dr["status"].ToString(), false);
Session["userid"] = dr["userid"];
Session["username"] = dr["username"];
if (Session["status"].ToString() == “Active”)
{
Response.Redirect(“cphome.aspx”);
}
else
{
Session.Abandon();
FormsAuthentication.SignOut();
Response.Redirect(“../index.aspx”);
}
}
lblmsg.Visible = true;
lblmsg.Text = “Invalid UserName or Passoword.”;
}
finally
{
conn.Close();
}
Web Config Authotication:
<authentication mode=”Forms”>
<forms name=”ExAuth” path=”/” loginUrl=”admin/login.aspx” protection=”All” timeout=”30″ defaultUrl=”Default.aspx”>
</forms>
</authentication>

Resize the Image using The C# code Without Changing Image Resolution

string sSavePath;
string sThumbExtension;
int intThumbWidth;
int intThumbHeight;
sSavePath = “../upload/category/”;
sThumbExtension = “_thumb”;
intThumbWidth = 65;
intThumbHeight = 57;
HttpPostedFile myFile = (HttpPostedFile)(fileupload.PostedFile);
int nFileLen = myFile.ContentLength;
if (nFileLen == 0)
{
errormsg.Visible = true;
errormsg.Text = “There wasn’t any file uploaded.”;
return;
}
byte[] myData = new Byte[nFileLen];
myFile.InputStream.Read(myData, 0, nFileLen);
// Make sure a duplicate file doesn’t exist.  If it does, keep on appending an incremental numeric until it is unique
string sFilename = System.IO.Path.GetFileName(myFile.FileName);
int file_append = 0;
while (System.IO.File.Exists(Server.MapPath(sSavePath + sFilename)))
{
file_append++;
sFilename = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName) + file_append.ToString() + “”;
}
// Save the stream to disk
System.IO.FileStream newFile = new System.IO.FileStream(Server.MapPath(sSavePath + sFilename), System.IO.FileMode.Create);
newFile.Write(myData, 0, myData.Length);
newFile.Close();
System.Drawing.Image.GetThumbnailImageAbort myCallBack = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
Bitmap myBitmap;
try
{
myBitmap = new Bitmap(Server.MapPath(sSavePath + sFilename));
// If jpg file is a jpeg, create a thumbnail filename that is unique.
file_append = 0;
string sThumbFile = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName) + sThumbExtension + “.gif”;
while (System.IO.File.Exists(Server.MapPath(sSavePath + sThumbFile)))
{
file_append++;
sThumbFile = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName) + file_append.ToString() + sThumbExtension + “.gif”;
}
// Save thumbnail and output it onto the webpage
System.Drawing.Image myThumbnail = myBitmap.GetThumbnailImage(intThumbWidth, intThumbHeight, myCallBack, IntPtr.Zero);
myThumbnail.Save(Server.MapPath(sSavePath + sThumbFile));
//imgPicture.ImageUrl = sSavePath + sThumbFile;
filesave = sThumbFile;
// Displaying success information
errormsg.Text = “File uploaded successfully!”;
// Destroy objects
myThumbnail.Dispose();
myBitmap.Dispose();
}
catch (ArgumentException errArgument)
{
// The file wasn’t a valid jpg file
errormsg.Text = “The file wasn’t a valid jpg file.”;
System.IO.File.Delete(Server.MapPath(sSavePath + sFilename));
}
Used Namespace:
using System.IO;

Delete The Iamge From Server / Save the Serve Space

Delete The Iamge From Server
private void DeleteFile(string strFileName1)
{
strFileName1 = filename1;
string str1 = Server.MapPath(“../upload/category/”) + strFileName1;
if (str1.Trim().Length > 0)
{
FileInfo fi1 = new FileInfo(str1);
if (fi1.Exists)
{
fi1.Delete();
}
}
}

Use Of Data Reader / Get data from the Table using data Reader

SqlDataReader dr1;
conn.Open();
string strquery1 = “select * from tbl_test where id= ‘” + Request.Params.Get(“id”) + “‘”;
SqlCommand cmd2 = new SqlCommand(strquery1, conn);
dr1 = cmd2.ExecuteReader();
if (dr1.Read())
{
filename1 = dr1["categoryphoto"].ToString();
//filename2 = dr1["photopathbig"].ToString();
}
dr1.Close();

Bind the data with Gridview, Datalist and Repeater

public void BindData()
{
conn.Close();
cmd = new SqlCommand(“select * from tbl_test”, conn);
cmd.CommandType = CommandType.Text;
da = new SqlDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds, “tbl_test”);
conn.Open();
cmd.ExecuteReader();
dgcategory.DataSource = ds;
conn.Close();
try
{
dgcategory.DataBind();
}
catch
{
dgcategory.CurrentPageIndex = 0;
}
}

Display Page Detail in Label

void displaypagedetail()
{
conn.Open();
hprHome.Visible = true;
if (Request.Params.Get(“state”) == “detail”)
{
Btn_save.Visible = false;
Btn_cancel.Visible = false;
hprHome.Visible = true;
}
string ID = Request.Params.Get(“id”).ToString();
string strQuery = “Select * from tbl_test where id= ‘” + Request.Params.Get(“id”) + “‘”;
cmd1 = new SqlCommand(strQuery, conn);
dr1 = cmd1.ExecuteReader();
try
{
if (dr1.Read())
{
txtText.Text = dr1["name"].ToString();
if (imgurl1 == “”)
{
fileupload.Enabled = true;
}
else
{
fileupload.Enabled = false;
}
}
}
finally
{
conn.Close();
}
}

Delete File From The Server

dr1.Close();
String strQuery = “delete from tbl_test where id=’” + Request.Params.Get(“id”) + “‘”;
cmd1 = new SqlCommand(strQuery, conn);
cmd1.CommandType = CommandType.Text;
cmd1.Connection = conn;
cmd1.Parameters.AddWithValue(“state”, Request.Params.Get(“state”));
try
{
cmd1.ExecuteNonQuery();
cmd1.ExecuteReader();
DeleteFile(“File”);
}
finally
{
conn.Close();
lblmsg.Visible = true;
lblmsg.Text = “Selected Data is successfully deleted.”;
BindData();
}
private void DeleteFile(string strFileName1)
{//Delete file from the server
strFileName1 = filename1;
string strFileName2 = filename2;
string str1 = Server.MapPath(“../upload/image/”) + strFileName1;
string str2 = Server.MapPath(“../upload/image1/”) + strFileName2;
if (str1.Trim().Length > 0 && str2.Trim().Length > 0)
{
FileInfo fi1 = new FileInfo(str1);
FileInfo fi2 = new FileInfo(str2);
if (fi1.Exists && fi2.Exists)//if file exists delete it
{
fi1.Delete();
fi2.Delete();
}
}
}

Bind the table with dropdown

tring strCategory1 = “select * from tbl_test where status=’Active’ and id=’” + drpmaincategory.SelectedValue.ToString() + “‘”;
SqlCommand cmdCategory1 = new SqlCommand(strCategory1, conn);
cmdCategory1.CommandType = CommandType.Text;
SqlDataAdapter daCategory1 = new SqlDataAdapter(cmdCategory1);
DataSet dsCategory1 = new DataSet();
daCategory1.Fill(dsCategory1, “tbl_test”);
drpsubcategory.DataSource = dsCategory1.Tables["tbl_test"];
drpsubcategory.DataTextField = “name”;
drpsubcategory.DataValueField = “id”;
drpsubcategory.DataBind();
drpsubcategory.Items.Insert(0, new ListItem(“Select SubCategory”, “”));

Use Of Data table and Dataset

SqlCommand mySqlSelect = new SqlCommand(“select * from tbl_test where nid=’” + Session["nid"].ToString() + “‘ and sessionid=’” + Session["sid"].ToString() + “‘”, conn);
mySqlSelect.CommandType = CommandType.Text;
SqlDataAdapter mySqlAdapter = new SqlDataAdapter(mySqlSelect);
DataSet myDataSet = new DataSet();
mySqlAdapter.Fill(myDataSet);
// Convert DataSet to DataTable by getting DataTable at first zero-based index of DataTableCollection
DataTable dtr1 = myDataSet.Tables[0];

Get the value from tabel in three drop down on select index change Event

string strCategory1 = “select categoryname,categoryid from tbl_test where status=’Active’”;
SqlCommand cmdCategory1 = new SqlCommand(strCategory1, conn);
cmdCategory1.CommandType = CommandType.Text;
SqlDataAdapter daCategory1 = new SqlDataAdapter(cmdCategory1);
DataSet dsCategory1 = new DataSet();
daCategory1.Fill(dsCategory1, “tbl_maincategory”);
drpmaincategory.DataSource = dsCategory1.Tables["tbl_test"];
drpmaincategory.DataTextField = “categoryname”;
drpmaincategory.DataValueField = “categoryid”;
drpmaincategory.DataBind();
SqlCommand mySqlSelect = new SqlCommand(“Select * from tbl_list where id= ‘” + Request.Params.Get(“id”) + “‘”, conn);
mySqlSelect.CommandType = CommandType.Text;
SqlDataAdapter mySqlAdapter = new SqlDataAdapter(mySqlSelect);
DataSet dt1 = new DataSet();
mySqlAdapter.Fill(dt1);
DataTable dtr1 = dt1.Tables[0];
string m = dt1.Tables[0].Rows[0]["categoryid"].ToString();
drpmaincategory.SelectedValue = m;
drpmaincategory_SelectedIndexChanged(sender, e);
drpsubcategory.SelectedValue = dt1.Tables[0].Rows[0]["subcategoryid"].ToString();
string strCategory3 = “select * from tbl_category where status=’Active’ and id=’” + drpmaincategory.SelectedValue.ToString() + “‘”;
SqlCommand cmdCategory3 = new SqlCommand(strCategory3, conn);
cmdCategory3.CommandType = CommandType.Text;
SqlDataAdapter daCategory3 = new SqlDataAdapter(cmdCategory3);
DataSet dsCategory3 = new DataSet();
daCategory3.Fill(dsCategory3, “tbl_subcategory”);
drpsubcategory.DataSource = dsCategory1.Tables["tbl_category"];
drpsubcategory.DataTextField = “subcategoryname”;
drpsubcategory.DataValueField = “subcategoryid”;

how to create thumbnail image

 Create thumbnail.aspx Page


<%@ Import Namespace=System.Drawing %>
<%@ Import Namespace=System %>
<%@ Import Namespace=System.Web %>
<html>
<script language="VB" runat="server">
Sub Page_Load(Sender As Object, E As EventArgs)
' Initialize objects
Dim objImage, objThumbnail As System.Drawing.Image
Dim strServerPath, strFilename As String
Dim shtWidth, shtHeight As Short    
Dim PRTarget, PROriginal As Short
' Get image folder path on server - use "\" string if root
' strServerPath = Server.MapPath("images\")
' Retrieve name of file to resize from query string
' strFilename = strServerPath & Request.QueryString("filename")
strFilename = Request.QueryString("FileName")
' Retrieve file, or error.gif if not available
Try
    objImage = objImage.FromFile(Server.MapPath(strFilename))
Catch
    objImage = objImage.FromFile(Server.MapPath("images/default.gif"))
End Try
' Retrieve width from query string
If Request.QueryString("width") = Nothing Then
    shtWidth = objImage.Width
ElseIf Request.QueryString("width") < 1 Then
    shtWidth = 100
Else
    shtWidth = Request.QueryString("width")
End If
If Request.QueryString("height") = Nothing Then
    shtHeight = objImage.Height
ElseIf Request.QueryString("height") < 1 Then
    shtHeight = 100
Else
    shtHeight = Request.QueryString("height")
End If
PROriginal = objImage.Width / objImage.Height
PRTarget = shtWidth / shtHeight
if objImage.Width > objImage.Height Then
    ' Work out a proportionate height from width
    shtHeight = objImage.Height / (objImage.Width / shtWidth)
Else
    ' Work out a proportionate width from height
    shtWidth = objImage.Width / (objImage.Height / shtHeight)
End If
' Create thumbnail
If objImage.Width<=shtWidth And objImage.Height<=shtHeight Then
    objThumbnail = objImage
Else
            objThumbnail = objImage.GetThumbnailImage(shtWidth, _
            shtHeight, Nothing, System.IntPtr.Zero)
End If
' Send down to client
Response.ContentType = "image/jpeg"
objThumbnail.Save(Response.OutputStream, Imaging.ImageFormat.Jpeg)
' Tidy up
objImage.Dispose()
objThumbnail.Dispose()
End Sub
</script>
</html>

How to expire the sesssion

 Session.Abandon();
            FormsAuthentication.SignOut();

Capta code generator

 In .aspx page

<tr>
 <td align="left" class="normaltext" height="25" style="width: 202px" valign="middle">
  <strong>Enter Security Code</strong></td>
                                      <td align="left" class="normaltext" height="25" valign="middle">
                                         <strong>:</strong>                                      </td>
                                      <td align="left" class="normaltext" colspan="2" height="25" valign="middle">
                                      <img src="JpegImage.aspx"><br>
      <p>
        <strong>Enter the code shown above:</strong><br>
        <asp:TextBox CssClass="button_form" id="CodeNumberTextBox" runat="server"></asp:TextBox><asp:RequiredFieldValidator ID="RequiredFieldValidator17"
                                                                                                                                        runat="server" ErrorMessage="Enter Confirmation Code" ControlToValidate="CodeNumberTextBox"
                                                                                                                                        ForeColor="" CssClass="blue_content" ValidationGroup="signupvalid" Display="none"
                                                                                                                                        SetFocusOnError="true">*</asp:RequiredFieldValidator>
        <br>
      </p>
      <p>
        <em class="notice">
          (Note: If you cannot read the numbers in the above<br>
          image, reload the page to generate a new one.)</em>
      </p>
      <p><asp:Label id="MessageLabel" runat="server"></asp:Label></p>
                                      </td>
                                  </tr>

In .aspx.cs page


  if (!this.IsPostBack)

            // Create a random code and store it in the Session object.
            this.Session["CaptchaImageText"] = GenerateRandomCode();

        else
        {
            // On a postback, check the user input.
            if (this.CodeNumberTextBox.Text == this.Session["CaptchaImageText"].ToString())
            {
                // Display an informational message.
                this.MessageLabel.CssClass = "info";
                this.MessageLabel.Text = "Correct!";
            }
            else
            {
                // Display an error message.
                this.MessageLabel.CssClass = "error";
                this.MessageLabel.Text = "ERROR: Incorrect, try again.";

                // Clear the input and create a new random code.
                this.CodeNumberTextBox.Text = "";
                this.Session["CaptchaImageText"] = GenerateRandomCode();
            }
        }

.jpegImage.aspx

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Text;

public partial class JpegImage : System.Web.UI.Page
{
    private void Page_Load(object sender, System.EventArgs e)
    {
        // Create a CAPTCHA image using the text stored in the Session object.
        CaptchaImage ci = new CaptchaImage(
          this.Session["CaptchaImageText"].ToString(),
          200, 50, "Century Schoolbook");

        // Change the response headers to output a JPEG image.
        this.Response.Clear();
        this.Response.ContentType = "image/jpeg";

        // Write the image to the response stream in JPEG format.
        ci.Image.Save(this.Response.OutputStream, ImageFormat.Jpeg);

        // Dispose of the CAPTCHA image object.
        ci.Dispose();
    }

}
                               

Monday, January 25, 2010

Use of three dropdown in Ajax

<asp:UpdatePanel id=”UpdatePanel1″ runat=”server” UpdateMode=”Conditional”>
<contenttemplate>
<asp:DropDownList width=”250px”  id=”drpmaincategory” runat=”server” OnSelectedIndexChanged=”drpmaincategory_SelectedIndexChanged” AutoPostBack=”true” >
</asp:DropDownList>  <asp:RequiredFieldValidator ID=”RequiredFieldValidator3″ runat=”server”
ControlToValidate=”drpmaincategory” ErrorMessage=”Please Select Category” Display=”Dynamic”>*</asp:RequiredFieldValidator>
<asp:Label ID=”lblmaincategory” runat=”server” Text=”"></asp:Label></TD>
<asp:DropDownList id=”drpsubcategory” width=”250px” runat=”server” OnSelectedIndexChanged=”drpsubcategory_SelectedIndexChanged1″ AutoPostBack=”true” CssClass=”textfield”>
</asp:DropDownList> <asp:RequiredFieldValidator ID=”RequiredFieldValidator2″ runat=”server”
ControlToValidate=”drpsubcategory” ErrorMessage=”Please Select Subcategory”
Display=”Dynamic”>*</asp:RequiredFieldValidator>
<asp:Label ID=”lblsubcategory” runat=”server” Text=”"></asp:Label></TD>
<asp:DropDownList id=”drpproductname” width=”250px” runat=”server”>
</asp:DropDownList><asp:RequiredFieldValidator ID=”RequiredFieldValidator1″ runat=”server”
ControlToValidate=”drpproductname” ErrorMessage=”Please Select Product”
Display=”Dynamic”>*</asp:RequiredFieldValidator>
<asp:Label ID=”lblproduct” runat=”server” Text=”"></asp:Label></TD>
</contenttemplate>
<triggers>
<asp:AsyncPostBackTrigger ControlID=”drpmaincategory” EventName=”SelectedIndexChanged” />
<asp:AsyncPostBackTrigger ControlID=”drpsubcategory” EventName=”SelectedIndexChanged” />
</triggers>
</asp:UpdatePanel>




Code Behind the Ajax Control

f (! IsPostBack)
{
hid_Ticker.Value = new TimeSpan(0, 0, 0).ToString();
}
Next, we create the Tick handler, which will retrieve the current time from the HiddenField, add one second to it, and display it in the Literal field, then it will save the new value to the HiddenField to be used again in a second:
protected void Timer1_Tick(object sender, EventArgs e)
{
hid_Ticker.Value = TimeSpan.Parse(hid_Ticker.Value).Add(new TimeSpan(0, 0, 1)).ToString();
lit_Timer.Text = “Time spent on this page: ” + hid_Ticker.Value.ToString();
}
Because AJAX is native to ASP.NET 3.5, we do not need to add anything extra or reference any other namespaces. All we simply need to do is include the ScriptManager and UpdatePanel controls, ASP.NET takes care of everything else for you behind the scenes.
If we run this now the timer will begin counting up as soon as the page is loaded. It is already fully-functional. But to test it, let’s add a textbox and a button so that we can postback the page and demonstrate how to keep the timer counting up regardless.

Finally, we add the logic to the code-behind that will handle the button click event:
protected void btn_Submit_Click(object sender, EventArgs e)
{
lit_Name.Text = “Thanks. Your name is: ” + fld_Name.Text;
}
Now when we run this, you will see that we’re able to submit our name without the timer stopping or pausing or restarting.
Our ASPX page looks like this:

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls; public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (! IsPostBack)
{
hid_Ticker.Value = new TimeSpan(0, 0, 0).ToString();
}
}
protected void Timer1_Tick(object sender, EventArgs e)
{
hid_Ticker.Value = TimeSpan.Parse(hid_Ticker.Value).Add(new TimeSpan(0, 0, 1)).ToString();
lit_Timer.Text = “Time spent on this page: ” + hid_Ticker.Value.ToString();
}
protected void btn_Submit_Click(object sender, EventArgs e)
{
lit_Name.Text = “Thanks. Your name is: ” + fld_Name.Text;
}
}