Sunday, 2 November 2014

Asp.net insert, Edit, update, delete data in gridview

How to insert, edit, update and delete data in gridview using asp.net:
I have one gridview I need to write code to insert data into gridview after that I need to edit that gridview data and update it and if I want to delete the record in grdview we need to delete record simply by click on delete button of particular row to achieve these functionalities I have used some of gridview events those are
1        1) Onrowcancelingedit
2        2) Onrowediting
3        3) Onrowupdating
4        4) Onrowcancelingedit
5        5) Onrowdeleting
By Using above griview events we can insert, edit, update and delete the data in gridview. My Question is how we can use these events in our coding before to see those details first design  table in database and give name Employee_Details
ColumnNameDataType
UserIdInt(set identity property=true)
UserNamevarchar(50)
Cityvarchar(50)
Designationvarchar(50)
After completion table creation design aspx page like this
<html xmlns=”http://www.w3.org/1999/xhtml” ><head runat=”server”>
<title>Untitled Page</title>
<style type=”text/css”>
.Gridview
{
font-family:Verdana;
font-size:10pt;
font-weight:normal;
color:black;
}
</style>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<asp:GridView ID=”gvDetails” DataKeyNames=”UserId,UserName” runat=”server”
AutoGenerateColumns=”false” CssClass=”Gridview” HeaderStyle-BackColor=”#61A6F8″
ShowFooter=”true” HeaderStyle-Font-Bold=”true” HeaderStyle-ForeColor=”White”
onrowcancelingedit=”gvDetails_RowCancelingEdit”
onrowdeleting=”gvDetails_RowDeleting” onrowediting=”gvDetails_RowEditing”
onrowupdating=”gvDetails_RowUpdating”
onrowcommand=”gvDetails_RowCommand”>
<Columns>
<asp:TemplateField>
<EditItemTemplate>
<asp:ImageButton ID=”imgbtnUpdate” CommandName=”Update” runat=”server” ImageUrl=”~/Images/update.jpg” ToolTip=”Update” Height=”20px” Width=”20px” />
<asp:ImageButton ID=”imgbtnCancel” runat=”server” CommandName=”Cancel” ImageUrl=”~/Images/Cancel.jpg” ToolTip=”Cancel” Height=”20px” Width=”20px” />
</EditItemTemplate>
<ItemTemplate>
<asp:ImageButton ID=”imgbtnEdit” CommandName=”Edit” runat=”server” ImageUrl=”~/Images/Edit.jpg” ToolTip=”Edit” Height=”20px” Width=”20px” />
<asp:ImageButton ID=”imgbtnDelete” CommandName=”Delete” Text=”Edit” runat=”server” ImageUrl=”~/Images/delete.jpg” ToolTip=”Delete” Height=”20px” Width=”20px” />
</ItemTemplate>
<FooterTemplate>
<asp:ImageButton ID=”imgbtnAdd” runat=”server” ImageUrl=”~/Images/AddNewitem.jpg” CommandName=”AddNew” Width=”30px” Height=”30px” ToolTip=”Add new User” ValidationGroup=”validaiton” />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”UserName”>
<EditItemTemplate>
<asp:Label ID=”lbleditusr” runat=”server” Text='<%#Eval(“Username”) %>’/>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID=”lblitemUsr” runat=”server” Text='<%#Eval(“UserName”) %>’/>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID=”txtftrusrname” runat=”server”/>
<asp:RequiredFieldValidator ID=”rfvusername” runat=”server” ControlToValidate=”txtftrusrname” Text=”*” ValidationGroup=”validaiton”/>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”City”>
<EditItemTemplate>
<asp:TextBox ID=”txtcity” runat=”server” Text='<%#Eval(“City”) %>’/>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID=”lblcity” runat=”server” Text='<%#Eval(“City”) %>’/>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID=”txtftrcity” runat=”server”/>
<asp:RequiredFieldValidator ID=”rfvcity” runat=”server” ControlToValidate=”txtftrcity” Text=”*” ValidationGroup=”validaiton”/>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText=”Designation”>
<EditItemTemplate>
<asp:TextBox ID=”txtDesg” runat=”server” Text='<%#Eval(“Designation”) %>’/>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID=”lblDesg” runat=”server” Text='<%#Eval(“Designation”) %>’/>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID=”txtftrDesignation” runat=”server”/>
<asp:RequiredFieldValidator ID=”rfvdesignation” runat=”server” ControlToValidate=”txtftrDesignation” Text=”*” ValidationGroup=”validaiton”/>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<div>
<asp:Label ID=”lblresult” runat=”server”></asp:Label>
</div>
</form>
</body>
</html>

Now add the following namespaces in codebehind
using System;using System.Data;using System.Data.SqlClient;
using System.Drawing

After that write the following code

SqlConnection con = new SqlConnection(“Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB”);protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindEmployeeDetails();
}
}
protected void BindEmployeeDetails()
{
con.Open();
SqlCommand cmd = new SqlCommand(“Select * from Employee_Details”, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
if (ds.Tables[0].Rows.Count > 0)
{
gvDetails.DataSource = ds;
gvDetails.DataBind();
}
else
{
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
gvDetails.DataSource = ds;
gvDetails.DataBind();
int columncount = gvDetails.Rows[0].Cells.Count;
gvDetails.Rows[0].Cells.Clear();
gvDetails.Rows[0].Cells.Add(new TableCell());
gvDetails.Rows[0].Cells[0].ColumnSpan = columncount;
gvDetails.Rows[0].Cells[0].Text = “No Records Found”;
}
}
protected void gvDetails_RowEditing(object sender, GridViewEditEventArgs e)
{
gvDetails.EditIndex = e.NewEditIndex;
BindEmployeeDetails();
}
protected void gvDetails_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int userid = Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Value.ToString());
string username = gvDetails.DataKeys[e.RowIndex].Values[“UserName”].ToString();
TextBox txtcity = (TextBox)gvDetails.Rows[e.RowIndex].FindControl(“txtcity”);
TextBox txtDesignation = (TextBox)gvDetails.Rows[e.RowIndex].FindControl(“txtDesg”);
con.Open();
SqlCommand cmd = new SqlCommand(“update Employee_Details set City='” + txtcity.Text + “‘,Designation='” + txtDesignation.Text + “‘ where UserId=” + userid, con);
cmd.ExecuteNonQuery();
con.Close();
lblresult.ForeColor = Color.Green;
lblresult.Text = username + ” Details Updated successfully”;
gvDetails.EditIndex = -1;
BindEmployeeDetails();
}
protected void gvDetails_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gvDetails.EditIndex = -1;
BindEmployeeDetails();
}
protected void gvDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int userid = Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Values[“UserId”].ToString());
string username = gvDetails.DataKeys[e.RowIndex].Values[“UserName”].ToString();
con.Open();
SqlCommand cmd = new SqlCommand(“delete from Employee_Details where UserId=” + userid, con);
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
BindEmployeeDetails();
lblresult.ForeColor = Color.Red;
lblresult.Text = username + ” details deleted successfully”;
}
}
protected void gvDetails_RowCommand(object sender, GridViewCommandEventArgs e)
{
if(e.CommandName.Equals(“AddNew”))
{
TextBox txtUsrname = (TextBox)gvDetails.FooterRow.FindControl(“txtftrusrname”);
TextBox txtCity = (TextBox)gvDetails.FooterRow.FindControl(“txtftrcity”);
TextBox txtDesgnation = (TextBox) gvDetails.FooterRow.FindControl(“txtftrDesignation”);
con.Open();
SqlCommand cmd =
new SqlCommand(
“insert into Employee_Details(UserName,City,Designation) values(‘” + txtUsrname.Text + “‘,'” +
txtCity.Text + “‘,'” + txtDesgnation.Text + “‘)”, con);
int result= cmd.ExecuteNonQuery();
con.Close();
if(result==1)
{
BindEmployeeDetails();
lblresult.ForeColor = Color.Green;
lblresult.Text = txtUsrname.Text + ” Details inserted successfully”;
}
else
{
lblresult.ForeColor = Color.Red;
lblresult.Text = txtUsrname.Text + ” Details not inserted”;
}
}
}

Saturday, 1 November 2014

3 tier architecture Example in ASP.NET with C#

  1. What is the use of 3-tier architecture and why we go for that architecture? 
  2. First we need to know what 3-Tier architecture is. 
  3. How to create 3-Tier architecture for our project?
To make application more understandable.
Easy to maintain, easy to modify application and we can maintain good look of architecture.
If we use this 3-Tier application we can maintain our application in consistency manner.
Basically 3-Tier architecture contains 3 layers
Application Layer or Presentation Layer
Business Access Layer(BALor Business Logic Layer(BLL)
Data Access Layer(DAL)
Here I will explain each layer with simple example that is User Registration
Application Layeror Presentation Layer
Presentation layer contains UI part of our application i.e., our aspx pages or input is taken from the user. This layer mainly used for design purpose and get or set the data back and forth. Here I have designed my registration aspx page like this
This is Presentation Layer for our project Design your page like this and double click on button save now in code behind we need to write statements to insert data into database this entire process related to Business Logic Layer and Data Access Layer.
Now we will discuss about Business Access Layer or Business Logic Layer
Business Access Layer(BAL)or Business Logic Layer (BLL)
This layer contains our business logic, calculations related with the data like insert data, retrieve data and validating the data. This acts as a interface between Application layer and Data Access Layer
Now I will explain this business logic layer with my sample
I have already finished form design (Application Layer) now I need to insert user details into database if user click on button save. Here user entering details regarding Username, password, Firstname, Lastname, Email, phone no, Location. I need to insert all these 7 parameters to database. Here we are placing all of our database actions into data access layer (DAL) in this case we need to pass all these 7 parameters to data access layers.
In this situation we will write one function and we will pass these 7 parameters to function like this
String Username= InserDetails (string Username, string Password, string Email, string Firstname, string Lastname, string phnno, string Location)
If we need this functionality in another button click there also we need to declare the parameters like string Username, string Password like this rite. If we place all these parameters into one place and use these parameters to pass values from application layer to data access layer by using single object to whenever we require how much coding will reduce think about it for this reason we will create entity layer or property layer this layer comes under sub of group of our Business Logic layer
Don’t get confuse just follow my instructions enough
How we have to create entity layer it is very simple
Right click on your project web application—> select add new item —-> select class file in wizard —> give name as BEL.CS because here I am using this name click ok
Open the BEL.CS class file declare the parameters like this in entity layer
Don’t worry about code it’s very simple for looking it’s very big nothing is there just parameters declaration that’s all check I have declared whatever the parameters I need to pass to data access layer I have declared those parameters only
BEL.CS
#region Variables///<summary>
/// User Registration Variables
///</summary>
private string _UserName;
private string _Password;
private string _FirstName;
private string _LastName;
private string _Email;
private string _Phoneno;
private string _Location;
private string _Created_By;
#endregion

///<summary>
/// Gets or sets the <b>_UserName</b> attribute value.
///</summary>
///<value>The <b>_UserName</b> attribute value.</value>
public string UserName
{
get
{
return _UserName;
}
set
{
_UserName = value;
}
}

///<summary>
/// Gets or sets the <b>_Password</b> attribute value.
///</summary>
///<value>The <b>_Password</b> attribute value.</value>
public string Password
{
get
{
return _Password;
}
set
{
_Password = value;
}
}

///<summary>
/// Gets or sets the <b>_FirstName</b> attribute value.
///</summary>
///<value>The <b>_FirstName</b> attribute value.</value>
public string FirstName
{
get
{
return _FirstName;
}
set
{
_FirstName = value;
}
}
///<summary>
/// Gets or sets the <b>_LastName</b> attribute value.
///</summary>
///<value>The <b>_LastName</b> attribute value.</value>
public string LastName
{
get
{
return _LastName;
}
set
{
_LastName = value;
}
}

///<summary>
/// Gets or sets the <b>_Email</b> attribute value.
///</summary>
///<value>The <b>_Email</b> attribute value.</value>
public string Email
{
get
{
return _Email;
}
set
{
_Email = value;
}
}

///<summary>
/// Gets or sets the <b>_Phoneno</b> attribute value.
///</summary>
///<value>The <b>_Phoneno</b> attribute value.</value>
public string Phoneno
{
get
{
return _Phoneno;
}
set
{
_Phoneno = value;
}
}

///<summary>
/// Gets or sets the <b>_Location</b> attribute value.
///</summary>
///<value>The <b>_Location</b> attribute value.</value>
public string Location
{
get
{
return _Location;
}
set
{
_Location = value;
}
}

///<summary>
/// Gets or sets the <b>_Created_By</b> attribute value.
///</summary>
///<value>The <b>_Created_By</b> attribute value.</value>
public string Created_By
{
get
{
return _Created_By;
}
set
{
_Created_By = value;
}
Our parameters declaration is finished now I need to create Business logic layer how I have create it follow same process for add one class file now give name called BLL.CS. Here one point don’t forget this layer will act as only mediator between application layer and data access layer based on this assume what this layer contains. Now I am writing the following BLL.CS(Business Logic layer)
#region Insert UserInformationDetails///<summary>
/// Insert UserDetails
///</summary>
///<param name=”objUserBEL”></param>
///<returns></returns>
public string InsertUserDetails(BEL objUserDetails)
{
DAL objUserDAL = new DAL();
try
{
return objUserDAL.InsertUserInformation(objUserDetails);
}
catch (Exception ex)
{
throw ex;
}
finally
{
objUserDAL = null;
}
}
#endregion
Here if you observe above code you will get doubt regarding these
what is
BEL objUserDetails
DAL objUserDAL = new DAL();
and how this method comes
return objUserDAL.InsertUserInformation(objUserDetails);
Here BEL objUserDetails means we already created one class file called BEL.CS with some parameters have you got it now I am passing all these parameters to Data access Layer by simply create one object for our BEL class file
What is about these statements I will explain about it in data access layer
DAL objUserDAL = new DAL();
return objUserDAL.InsertUserInformation(objUserDetails);
this DAL related our Data access layer. Check below information to know about that function and Data access layer
Data Access Layer(DAL)
Data Access Layer contains methods to connect with database and to perform insert,update,delete,get data from database based on our input data
I think it’s to much data now directly I will enter into DAL
Create one more class file like same as above process and give name as DAL.CS
Write the following code in DAL class file
//SQL Connection stringstring ConnectionString = ConfigurationManager.AppSettings[“LocalConnection”].ToString();

#region Insert User Details
///<summary>
/// Insert Job Details
///</summary>
///<param name=”objBELJobs”></param>
///<returns></returns>
public string InsertUserInformation(BEL objBELUserDetails)
{
SqlConnection con = new SqlConnection(ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand(“sp_userinformation”, con);
cmd.CommandType = CommandType.StoredProcedure;
try
{
cmd.Parameters.AddWithValue(“@UserName”,objBELUserDetails.UserName);
cmd.Parameters.AddWithValue(“@Password”, objBELUserDetails.Password);
cmd.Parameters.AddWithValue(“@FirstName”, objBELUserDetails.FirstName);
cmd.Parameters.AddWithValue(“@LastName”, objBELUserDetails.LastName);
cmd.Parameters.AddWithValue(“@Email”, objBELUserDetails.Email);
cmd.Parameters.AddWithValue(“@PhoneNo”, objBELUserDetails.Phoneno);
cmd.Parameters.AddWithValue(“@Location”, objBELUserDetails.Location);
cmd.Parameters.AddWithValue(“@Created_By”, objBELUserDetails.Created_By);
cmd.Parameters.Add(“@ERROR”, SqlDbType.Char, 500);
cmd.Parameters[“@ERROR”].Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
string strMessage = (string) cmd.Parameters[“@ERROR”].Value;
con.Close();
return strMessage;
}
catch (Exception ex)
{
throw ex;
}
finally
{
cmd.Dispose();
con.Close();
con.Dispose();
}
}
#endregion
Here if you observe above functionality I am getting all the parameters by simply creating BEL objBELUserDetails. If we create one entity file we can access all parameters through out our project by simply creation of one object for that entity class based on this we can reduce redundancy of code and increase re usability
Observe above code have u seen this function before? in BLL.CS i said i will explain it later got it in DAL.CS I have created one function InsertUserInformation and using this one in BLL.CS by simply creating one object of DAL in BLL.CS.
Here you will get one doubt that is why BLL.CS we can use this DAL.CS directly into our code behind  we already discuss Business logic layer provide interface between DAL and Application layer by using this we can maintain consistency to our application.
Now our Business Logic Layer is ready and our Data access layer is ready now how we can use this in our application layer write following code in your save button click like this
protected void btnsubmit_Click(object sender, EventArgs e){
string Output = string.Empty;
if (txtpwd.Text == txtcnmpwd.Text)
{
BEL objUserBEL = new BEL();

objUserBEL.UserName = txtuser.Text;
objUserBEL.Password = txtpwd.Text;
objUserBEL.FirstName = txtfname.Text;
objUserBEL.LastName = txtlname.Text;
objUserBEL.Email = txtEmail.Text;
objUserBEL.Phoneno = txtphone.Text;
objUserBEL.Location = txtlocation.Text;
objUserBEL.Created_By = txtuser.Text;
BLL objUserBLL = new BLL();
Output = objUserBLL.InsertUserDetails(objUserBEL);

}
else
{
Page.RegisterStartupScript(“UserMsg”, “<Script language=’javascript’>alert(‘” + “Password mismatch” + “‘);</script>”);
}
lblErrorMsg.Text = Output;
}
Here if you observe I am passing all parameters using this BEL(Entity Layer) and we are calling the method InsertUserDetails by using this BLL(Business Logic Layer)
Now run your applciation test with debugger you can get idea clearly.

Friday, 1 August 2014

Writing Efficient String Functions in C#

Writing Efficient String Functions in C#
The .NET Framework provides a set of powerful string functions. These building blocks can be used to write more complex algorithms for handling string data. However developers aiming to write fast and efficient string functions must be careful of how they use those building blocks.
To write efficient string handling functions, it is important to understand the characteristics of string objects in C#
String Characteristics
First and foremost it is important to know that strings in .NET  class objects. There is no difference between the types System.String and string, they are both class objects. Unlike value types, class objects are stored in the heap (instead of the stack). This is an important fact because it means that creating a string object can trigger garbage collection, which is costly in terms of performance.
In terms of string functions, this means we want to avoid creating new strings as much as possible.
However that is easier said than done. Another important thing about strings in .NET is that they are immutable. This means string objects cannot be modified. To edit a string object, you have to instead create a new string that will have the modification.
Working with Characters
The solution is to work with characters instead of strings as much as possible. The char object in C# is a value type, which means all char variables are stored in the stack. Furthermore, since a string is a collection of characters, converting between chars and strings is very simple.
To convert a string to a char array, use the ToCharArray() .NET function:
string myStr = “hello world”;
char[] myStrChars = myStr.ToCharArray();
To convert a char array back to a string, simply create a new instance of a string:
char[] myChars = { ‘h’, ‘e’, ‘l’, ‘l’, ‘o’, ‘ ‘, ‘w’, ‘o’, ‘r’, ‘l’, ‘d’ };
string myStr = new string(myChars);
Writing efficient string functions thus boils down to working with char arrays. However you might remember that arrays are stored in the heap. Thus there isn’t much difference between working with a string and a character array in terms of performance if we end up handling arrays in the same way as strings.
Yet this does not mean working with array is not faster. For one thing, we can make use of dynamic arrays such as List (or ArrayList in .NET Framework 1.1) to make our array management as efficient as possible.
Example Function
Let’s write a very simple string function and compare the difference between using strings and char arrays. The function will capitalize all the vowels in a string (working with the English alphabet), and make all other characters lowercase.
Using just strings:
public string CapitalizeVowels(string input)
{
if (string.IsNullOrEmpty(input)) //since a string is a class object, it could be null
return string.Empty;
else
{
string output = string.Empty;
for (int i = 0; i < input.Length; i++)
{
if (input[i] == ‘a’ || input[i] == ‘e’ ||
input[i] == ‘i’ || input[i] == ‘o’ ||
input[i] == ‘u’)
output += input[i].ToString().ToUpper(); //Vowel
else
output += input[i].ToString().ToLower(); //Not vowel
}
return output;
}
}
Using character arrays:
public string CapitalizeVowels(string input)
{
if (string.IsNullOrEmpty(input)) //since a string is a class object, it could be null
return string.Empty;
else
{
char[] charArray = input.ToCharArray();
for (int i = 0; i < charArray.Length; i++)
{
if (charArray[i] == ‘a’ || charArray[i] == ‘e’ ||
charArray[i] == ‘i’ || charArray[i] == ‘o’ ||
charArray[i] == ‘u’)
charArray[i] = char.ToUpper(charArray[i]); //Vowel
else
charArray[i] = char.ToLower(charArray[i]); //Not vowel
}
return new string(charArray);
}
}
Both functions will produce the exact same results given the same input data. We can perform some basic benchmarks to compare the performance of each function. For example, the string-based function took an average of 2181ms to process the string “hello world” 1,000,000 times while the array-based function only took 448ms (measured on my computer).