27 February 2014

How To Create And Read Cookies In Asp.Net And C#.Net

Cookies store user information in a text file and stored on user hard drive.here are some exmaples of how we can create cookies and read from them.

Creating Induvisual cookies

Indivisulal cookies are cookies which can store only single value

First way to create cookie Indivisulal (using Response object)

Response.Cookies["un"].Value = TextBox1.Text;
Response.Cookies["un"].Expires = DateTime.Now.AddMinutes(10);

Second way to create cookie Indivisulal (using HttpCookie Class)

HttpCookie ck = new HttpCookie("un1", TextBox1.Text);
ck.Expires = DateTime.Now.AddMinutes(10);Response.Cookies.Add(ck);

Reading from indivisual cookies

Response.Write(Request.Cookies["un"].Value);
//or
HttpCookie d = Request.Cookies["un1"].Value;Response.Write(d.Value);

Creating Sub-Key cookies
//First Method
Response.Cookies["myckk"]["un"] = TextBox1.Text;
Response.Cookies["myckk"]["up"] = TextBox2.Text;
Response.Cookies["myckk'"].Expires = DateTime.Now.AddMinutes(10);

//Second method 
HttpCookie ck = new HttpCookie("myckk");
ck.Values.Add("un", TextBox1.Text);
ck.Values.Add("up", TextBox2.Text);
ck.Expires = DateTime.Now.AddMinutes(10);
Response.Cookies.Add(ck);
Response.Redirect("Default2.aspx");

Reading Sub-Key cookies

//First Mehtod ( with Request object)
Response.Write(Request.Cookies["myckk"]["un"].ToString());
Response.Write(Request.Cookies["myckk"]["up"].ToString());
Response.Redirect("Default2.aspx");

//Second Method
HttpCookie ck = Request.Cookies["myckk"];
Response.Write(ck.Values["un"].ToString());
Response.Write(ck.Values["un"].ToString());
Try it

Authentication Using XML

How to make users in XML File and authenticate them..
Solution:
create a xml file as

<mydata>
<tb>
<user>admin</user>
<pass>admin</pass>
</tb>
<tb>
<user>admin1</user>
<pass>admin1</pass>
<tb>
<tb>
<user>admin2</user>
<pass>admin2</pass>
<tb>
</mydata>


Add two Text Boxes on Design page with ids TextBox1 and TextBox2 
Add a label with id Label1
Add a button
double click on button
and write following code in button click event

//code to authenticate user
String pt = Server.MapPath("XMLFile.xml");//
DataSet ds = new DataSet();
ds.ReadXml(pt);
DataView dv = ds.Tables[0].DefaultView;
dv.RowFilter = "user='" + TextBox1.Text+"'";
if (dv.Count == 0)
Label1.Text = "Wrong User";
else
{
if (dv[0][1].ToString() == TextBox2.Text)
FormsAuthentication.RedirectFromLoginPage(TextBox1.Text, false);
else
Label1.Text = "Wrong Password";
}

Store Username And Password In Web.Config File

How to create user in web.config file and authenticate and authorise them


Web.config file,is a configuration file used in Asp .net web application. An Asp .net application has at least one web.config file which keeps the configurations required for the application. Web.config file is a XML file with specific tags having specific meanings.

What is stored in Web.config file

There are number of settings that can be stored in the Web.config file. Following are the most used configurations, stored in Web.config file..
1.Database connections
2.Security 
3.Session States 
4.Error Handling 

The most important thing of any application is the security.In this post I will tell about how we can use web.config for security in asp.net application

I am showing a simple application of how to create user/ Store username and password in web.config file and authenticate and authorise them.

How to Create user in web.config file

Find the following line in your web.config file

<authentication mode="Windows" />

Modify it as below

<authentication mode="Forms">
<forms>
<credentials passwordFormat="Clear">
<user name="admin" password="admin"/>
<user name="admin1" password="admin1"/>
<user name="admin2" password="admin2"/>
</credentials>
</forms> 
</authentication>

Now drag and drop two TextBox and a Button control in your desing page (login.aspx)
Or
Copy paste following code in your .aspx page

UserName<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
Password<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox><br />
<br />
              
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Login" />

Now double click on your button and write following code in it’s button click event

if(FormsAuthentication.Authenticate(TextBox1.Text,TextBox2.Text))
FormsAuthentication.RedirectFromLoginPage(TextBox1.Text,false);
else
Response.Write("Wrong user");
That’s it with creating and authenticating user in Web.config file

Now I am showing how to authorize user using web.config file

First add four web pages in your application named default.aspx, default2.aspx, default3.aspx and default4.aspx

On default2.aspx write a message for user admin (welcome admin)
On default3.aspx write a message for user admin1 (welcome admin1)
On default4.aspx write a message for user admin2 (welcome admin2)


Find the following tag (closing of system.web tag)in your web.config file

</system.web> 

Now write the following code in below </system.web> tag


<location path ="default2.aspx">
<system.web>
<authorization>
<allow users="admin"/>
<deny users="*"/>
</authorization>
</system.web>
</location>
<location path ="default3.aspx">
<system.web>
<authorization>
<allow users="admin1"/>
<deny users="*"/>
</authorization>
</system.web>
</location>
<location path="default4.aspx">
<system.web>
<authorization>
<allow users="admin2"/>
<deny users ="*"/>
</authorization>
</system.web>
</location>

Now come to your page named default.aspx

Write the followin code in .aspx page 

<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label><br />
<br />

<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="~/Default2.aspx">Default2</asp:HyperLink>
<asp:HyperLink ID="HyperLink2" runat="server" NavigateUrl="~/Default3.aspx">Default3</asp:HyperLink>
<asp:HyperLink ID="HyperLink3" runat="server" NavigateUrl="~/Default4.aspx">Default4</asp:HyperLink>
Write following code in page_load event of default.aspx page

if (User.Identity.IsAuthenticated)
Label1.Text = "Welcome:" + User.Identity.Name;
else
FormsAuthentication.RedirectToLoginPage();
Set the login.aspx page to start page and run the application

(open solution explorer,right click on login.aspx page and click option set as start page)
Now run the application

Login with username admin and password admin
You will be redirected to default.aspx page
Click on link default2. you will be redirected and will see a message
Now go back to default.aspx page by clicking back button on your browser
Now click on default3 link. You will be redirected to login page mean you don not have permission to go on defult3.aspx page.

Read,Write And Update Data In Excel Sheet Using Asp.Net And C#

Sometime we require to read an Excel file and Modify the data and also save the modified record in the same file.  (Code Link is given Below)
Here i am giving an example to How to Read,Write and Update Data in Excel Sheet.

I am using a Excel file which has 4 columns:
EmpNo
EmpName
EmpAddress
EmpSalary

and to show this data i am using Repeater Control of Asp.Net 

The code of .cs file is given below 

i am using OLEDB provider for these operations.

 Method that will return DataTable to bind Repeater Control

private DataTable ReadExcelData(Int32 EmpID)
{
string file = Server.MapPath("employees.xls");
string constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + file + ";Extended Properties=Excel 8.0;";

string query = "Select EmpNo,EmpName,EmpAddress,EmpSalary from [Sheet1$]";
if (EmpID > 0)
query = query + " WHERE EmpNo=" + EmpID.ToString();
DataSet dsUserData = new DataSet();
using (OleDbConnection Connection = new OleDbConnection(constr))
{
using (OleDbDataAdapter DataAdapter = new OleDbDataAdapter(query, Connection))
{
DataAdapter.Fill(dsUserData, "UserData");
DataAdapter.AcceptChangesDuringFill = false;
DataAdapter.Dispose();
Connection.Close();
}
}
return dsUserData.Tables[0];
}
 
 

 Method that will call above method and bind Repeater

private void BindRepeater()
{
rptUserData.DataSource = ReadExcelData(-1);
rptUserData.DataBind();
}

 

Update Method which will be called to update record

private void UpdateRecord()
{
string file = Server.MapPath("employees.xls");
string constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + file + ";Extended Properties=Excel 8.0;";
using (OleDbConnection Connection = new OleDbConnection(constr))
{
Connection.Open();
string query = "UPDATE [Sheet1$] SET EmpName=\"" + ename.Text.Trim() + "\",EmpAddress=\"" + add.Text.Trim() + "\",EmpSalary=\"" + esal.Text.Trim() + "\" WHERE EmpNo=" + btnUpdate.CommandArgument.ToString();
using (OleDbCommand objCmd = new OleDbCommand(query, Connection))
{
objCmd.ExecuteNonQuery();
objCmd.Dispose();
Connection.Close();
}
}

 

Insert Method that will be called to Insert a Record in Excel File
protected void btnInsert_Click(object sender, EventArgs e)
{

Int32 LastEmpNO = Convert.ToInt32(((Label)rptUserData.Items[rptUserData.Items.Count - 1].FindControl("lblID")).Text);
LastEmpNO += 1;
string file = Server.MapPath("employees.xls");
string constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + file + ";Extended Properties=Excel 8.0;";
using (OleDbConnection Connection = new OleDbConnection(constr))
{
Connection.Open();
string query = "INSERT INTO [Sheet1$](EmpNo,EmpName,EmpAddress,EmpSalary) VALUES(" + LastEmpNO + ",\"" + ename.Text.Trim() + "\",\"" + add.Text.Trim() + "\",\"" + esal.Text.Trim() + "\")";
using (OleDbCommand objCmd = new OleDbCommand(query, Connection))
{
objCmd.ExecuteNonQuery();
objCmd.Dispose();
Connection.Close();
}
}
BindRepeater();
divInsertUpdate.Visible = false;
}