Monday, September 22, 2008

form authetication code in c#

form authetication code:::::
---------------------------------------


protected void Login_Authenticate(object sender, AuthenticateEventArgs e)
{
Config objcon = new Config();
DAL.TextEncryption objencryption = new DAL.TextEncryption();
string strUserName, strPassword;
int intUserID;
try
{
Login.Focus();
strUserName = this.Login.UserName;
strPassword = objencryption.Main(Login.Password, 0);
intUserID = objcon.AuthenticateUser(strUserName, strPassword);
Session["UserID"] = intUserID.ToString();
if (intUserID > 0)
{
e.Authenticated = true;
FormsAuthenticationTicket tkt;
string cookiestr;
HttpCookie ck;

tkt = new FormsAuthenticationTicket(1,
this.Login.UserName,
DateTime.Now,
DateTime.Now.AddMinutes(30),
false,//chkPersistCookie.Checked
"Area");

cookiestr = FormsAuthentication.Encrypt(tkt);
ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);
//if (chkPersistCookie.Checked)
// ck.Expires = tkt.Expiration;
ck.Path = FormsAuthentication.FormsCookiePath;
Response.Cookies.Add(ck);

string strRedirect;
strRedirect = Request["ReturnUrl"];
char[] c ={ '/' };
string[] temp;
if (strRedirect == null)
{
strRedirect=Request.CurrentExecutionFilePath.ToString();

// "/area_devlopment/Admin/Login.aspx"
}

try
{
temp = strRedirect.Split(c);
//if (temp.ToString().Contains("localhost"))
//{
// strRedirect = "/" + temp[1].ToString() + "/" + temp[2].ToString() + "/welcome.aspx";

//}
//else
//{
// strRedirect = "/" + temp[1].ToString() + "/welcome.aspx";

//}
try
{
strRedirect = "~/Admin/Welcome.aspx";
}
catch
{
strRedirect = "~/Admin/Welcome.aspx";

}

}
catch { }
if (strRedirect == null)

strRedirect = "~/Admin/Welcome.aspx";
Response.Redirect(strRedirect, true);
// Response.Redirect("Welcome.aspx", false);
}
else
{
e.Authenticated = false;
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}


how to add cookies::
-----------------------------------------
// Code that runs when a new session is started
///Session["ActiveCountry"] = 66;
int cid=DAL.Country.GetUsaCountryId();
HttpContext.Current.Session["ActiveCountry"] = cid;
#region Get Culture Code

DataSet ds = new DataSet();
ds = DAL.Country.GetAllCountryDetailsById(cid);
if (ds.Tables.Count > 0)
{
DataRow drBasicInfo;
drBasicInfo = ds.Tables[0].Rows[0];
if (drBasicInfo != null)
{

HttpCookie cookie = Request.Cookies["Language"];
if (cookie == null)
{
cookie = new HttpCookie("Language");
}
cookie["LanguCode"] = drBasicInfo["Language"].ToString();

cookie.Expires = DateTime.Now.AddYears(1);
Response.Cookies.Add(cookie);

}
}
#endregion

Sunday, September 21, 2008

Form authentication without ticket

What is authentication? "To establish the authenticity of; prove genuine" (The American Heritage® Dictionary of the English Language). ASP.NET has buildt in authentication support for web page development making it really easy for any web developer to add personalized webpages or password-protect areas.

This tutorial is aimed at people who already have a good understanding of ASP.NET. If you want to learn ASP.NET, I have a beginner tutorial here: Guestbook.NET - a beginner tutorial to ASP.NET

There are three types of autentication in ASP.NET: forms authentication, windows authentication, and Passport authentication.

Windows Authentication - This is provided so that web pages can make use of the local Windows User and Groups.

Passport Authentication - This is Microsoft's initiative for a single authentication point. It is used for such things as Hotmail, MSN and Devhood. Find out more at www.passport.com

Forms Authentication - This is a cookie based authentication system where the username and passport is stored in a text file or a database. We will be focusing on this authentication model in this tutorial.

Let's start!

web.config file
The web.config file is an XML based configuration file which exists for every web application. The web.config file typical resides in the application root directory although it is possible to have multiple web.config files. If there is another web.config file placed in a directory below the application root, it will use those setting instead. The web.config file is where you will tell a web application to use either of the three types of autentication types.

Here we show you a basic example of what a web.config file looks like when it has be set to use form authentication. I will go in further detail and explain the tags.











































The first tag in the web.config file is the tag. It is the base tag for the web.config file and will contain all your configuration settings in here. The first tag specifies the settings that will apply to all the file in the same directory and the files below this directory.

tag
Here we come to our first tag for authentication, which is thence called . We see that there is one attribute for this tag and it specifies the type of authentication that will be applied to this site. The choices are Windows|Forms|Passport|None. This tutorial focuses on Forms authentication so that's what we got in there.

tag
Next we move to the tag. This tag is unique to the Forms authentication mode and will specify things such as the loginUrl, the type of protection and the timeout of inactivity.
loginUrl attribute - when a user does not have the correct credentials to view a page, the user will be forwarded to this url.
protection attribute - there are four(4) types of protection modes, All|None|Encryption|Validation. For simplicity sake, we're not going to go into this now, but if you want to know more, consult the MSDN documentation.
timeout attribute - this is an integer value specifying the number of minutes a user's cookie will be valid for. After this period of inactivity, the user will be forced to re-authenticate.

tag
This is an optional section if you want to specify the username/password combinations in here. We will first discuss authentication with passwords in the web.config file and I will later highlight how you can store the usernames and passwords in a database or XML file. The credentials tag also has an attribute called passwordFormat. Your choices for password format are: Clear|SHA1|MD5. We still stick with clear text passwords for now and talk about encrypting the passwords further down.

tag
This is also an optional tag (since it resides in the optional credentials tag). This tag is pretty straight forward, name attribute for the username and password attribute for the password.

tag
Now that we have specified our authentication type and the user accounts, we have to specify how the authentication is to be applied to our website. We used the authorization tag to mark this. The autorization tag is placed between the system.web tags. In the example above, we see that the authorization tag contains the tag. This allow tag will (as you can guess) specify which users have access to the website. And there is also a tag which will specify which users are denied access. The format of the users attributes is pretty simple. It's just a comma-delimited list of user names (i.e. users="jsmith, jdoe, blah"). There are also two special values that can be used in the users attribute. The first one is the * (asterix) character. This is used to denote "all users". So the example above allows access to all users. The second one is the ? (question mark) character. This is used to denote "anonymous" users. You can use this to deny anonymous access which will force users to authenticate before getting into some webpages (see the examples in the locations tags).

tag
Now what happens when we want some parts of the website to be protected and others to not be protected? ASP.NET did think of that and handles that by the tags. The location tag has one attribute, path, which is the path to apply a different set of security rules to. Inside the location tag, we have the system.web tag once again. The authorization tag is placed inside the system.web tag (just like the in first usage of ).

login.aspx file
Now that we have our web application all configured, we tackle the task of getting a user to authenticate themself by sending his/her username and password. In our tag, we specified that the loginUrl attribute is login.aspx and here is an example of a login page:



Login



Login




Username:

Password:









First, let's look at what the user sees. Our simple webpage example has two textboxes and a button. This webpage will be shown to the user anytime a request is made for a page and the user is does not have the proper credentials. This is a simple example, which you'll probably want to modify. Now we look at the code, this is where the authentication is done and the cookies are sent to the browser.

FormsAuthentication.Authenticate
The single login button on the webpage calls the Login_Click method when clicked. In this method, we use the FormsAuthentication.Authenticate(username,password) to get ASP.NET to check the credentials of the user. The parameters for this method is pretty straightforward and it just returns a boolean value.

FormsAuthentication.RedirectFromLoginPage
If the user is providing proper credentials, then we'll use the FormsAuthentication.RedirectFromLoginPage method. The parameters of this method are a username string and a boolean value. The first parameter is a username string and it is a name of the user for cookie authentication purposes. The value you put in there will be the user name that the client is associated with. It does not need to match the username used in the FormsAuthentication.Authenticate method but it is advisable to set the cookie to the username that was used to log in. The second parameter is a boolean value and it specifies whether or not a durable cookie (one that is saved across browser sessions) should be issued.
If you remember, when a user requests a page without proper authentication, they are redirected to the login page. After setting the cookie, the RedirectFromLoginPage will then send the user back to the page they came from.

There you go. You should have everything you need for a basic Forms based authentication system. Give it a try. If you want to extend the usage of authentication more, read on!

Advanced Part
Now we move to the more advanced topics on authenication. First we'll talk about encrypting your passwords then I'll tell you how to store your user accounts outside the web.config file.

Encrypting passwords
If you look at one of my tips, I say "Storing them as cleartext is asking for trouble." Why? Well, if your system gets comprimised, then someone can steal all your passwords. That's trouble. Also, sometimes people tend to use the same password in different sites because they don't want to memorize so many passwords. If you comprimse your password lists, then someone's going to be unhappy. That's trouble.
So how will you encrypt your passwords. ASP.NET has included some hashing functions to encrypt your passwords. What is a hashing function? Well, simply put, it sends your password to a function which spits out your password all garbled. The two hashing functions that SHA1 or MD5. Both hashing functions are suppose to not let malious users take the hashed password and get the original password. So how does this all work in ASP.NET? Passwords in the web.config file are stored as their hashed values. Then when a user tries to login, they will send they're password to the webserver and the webserver will hash the password and compare it to the hased password in the web.config file. If the two hashes match, then the password is correct. To hash a password, you can use the built in method called HashPasswordForStoringInConfigFile. You can call it like this: FormsAuthentication.HashPasswordForStoringInConfigFile("password","md5"). The first parameter is the password to be hashed. The second parameter is either "md5" or "sha1" depending on which hashing function you use. See your MSDN documentation for more detailed instructions. Make sure to update the passwordFormat attribute in the tag.

Users accounts stored elsewhere
Storing user accounts in the web.config file has it's limitations. A lot of larger website will prefer to store the passwords in an SQL database or maybe a seperate XML/text file. So in this case, we won't have those optional and tags. This tutorial does not concentrate on either of those technologies but we will show you an example of user accounts stored in an SQL database (so I'll assume you have some knowledge of reading data from a database.).

First, our example will assume the existence of a tabled called Users with the fields username and password.

Let's go back to the login.aspx page. We'll change the Login_Click method to look like this:


void Login_Click(Object sender, EventArgs e) {
String sHashedPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(password.Text,"MD5");
String sqlStmt = "Select username from Users where username='" + UserName.Text + "' and password='" + sHashedPassword + "'";
SqlConnection sqlConn = new SqlConnection("server=localhost;uid=sa;pwd=password;database=master;");
SqlCommand sqlCmd = new SqlCommand(sqlStmt, sqlConn);
sqlCmd.Connection.Open();
SqlDataReader sqlReader = sqlCmd.ExecuteReader(CommandBehavior.CloseConnection);

if (sqlReader.Read())
FormsAuthentication.RedirectFromLoginPage(username.Text, true);
else
status.InnerHtml += "Invalid Login";
}




In this function, we've replaced the FormsAuthentication.Authenticate function with some SQL code that will query the database for a username/password pair. If such a pair if found, then the credentials are correct and the user can be issued a cookie and redirected back to the webpage. Also, notice in this example, I've used the HashPasswordForStoringInConfigFile method (see the section above for encrypting password). This function is used because the database will have the passwords hashed. The code above could easily be changed to look in an XML file or a text file. Just remember the key methods that you will have to use is "FormsAuthentication.RedirectFromLoginPage".


Tips

web.config file is cAsE-sEnSiTivE. Be careful how you type the tags and attributes.
Since the web.config file is an XML file, all opened tags must have a closing tag. Or a single tag must look like this: (notice the slash near the end).
Encrypt your passwords! Storing them as cleartext is asking for trouble.
Make sure you hash your passwords with the right hash algorithm and that you don't get them mixed up.
loginUrl has to be absolute. not relative
don't forget to make the password box of type password

how to read and add cookies in .net c#

C# And Cookies
--------------
Cookies allow you to store small bits of data on the user's computer. They take up a small amount of space on the user's hard drive and are often useful for storing nonessential information, such as user preferences.


ReadCoookies.aspx: Reading Cookies Written from the WriteCookies Example
1: <%@ language="C#" %>
2:
23:
24:
25: Use the button below to read a cookie

26:

27: Cookie Name
28:
29:
30: Write Cookies
31:
32:



WriteCookies.aspx: Writing Arbitrary Cookies
1: <%@ language="C#" %>
2:
22:
23:
24:

Use the button below to write cookies to your browser


25: The cookies will expire in one minute.
26:

27: Cookie Name

28: Cookie Value

29:

30:
31: Read the cookies
32:
33:




ReadCookies.aspx page reads cookies stored on a user's browser.

To write a cookie, create a new HttpCookie object (Line 6 of Listing 3.2), assign a string to its Value property (Line 9), and then call the Add() method on the Response.Cookies object (Line 17). You can also set the time of expiration for a cookie by setting the Expires property to a DateTime value (Line 14).

ReadCookies.aspx in Listing 3.3 shows that it's equally easy to read cookies back, using the Request.Cookies collection (Line 9), which is indexed by cookie name.

Cookies can store only strings, so if you need to store a more complex data type, it must be converted into a string. One possibility for storing complicated data structures is to write the structure out as an XML string and convert it back when reading the cookie.

You can store multiple strings in a cookie by treating each cookie as a collection object. For example, the following would work fine:

HttpCookie cookie = new HttpCookie("UserFavorites");
cookie["FavoriteColor"] = "blue";
cookie["FavoriteFlavor"] = "chocolate";
cookie["FavoriteDrink"] = "coffee";



Advanced Properties of the HttpCookie Class
Property
Description

Domain
Gets/sets the domain name that this cookie belongs to. If set, it restricts access to this cookie from Web servers in the specified domain, such as mycompany.com.

Path
Gets/sets the path that this cookie belongs to. If set, it restricts access to this cookie from Web pages in the specified path.

Secure
Gets/sets a flag that tells whether the cookie should be transmitted securely to the client browser using the HTTPS protocol. You must have HTTPS set up on your Web server for this option to work.

HasKeys
Tells whether the cookie is made up of a collection of strings.


Event delegation from user control to aspx page in ASP.NET,C#

“What is delegate?” we all have faced this question in one or more interview. and the most common answer is “Function pointer”. Here I am showing a simple example of delegate. I have one user control and one aspx page. The user control contains one button. When user click on this button I will call a method on main page using delegate. Here is my user control,

<%@ Control Language=”C#” AutoEventWireup=”true” CodeFile=”WebUserControl.ascx.cs” Inherits=”Dalegate_WebUserControl” %>



Fig - (1) WebUserControl.ascx

On WebUserControl.ascx.cs I have written simple delegate and event handler as shown below,

public partial class Dalegate_WebUserControl : System.Web.UI.UserControl
{

// Delegate declaration
public delegate void OnButtonClick(string strValue);

// Event declaration
public event OnButtonClick btnHandler;

// Page load
protected void Page_Load(object sender, EventArgs e)
{

}

protected void btnTest_Click(object sender, EventArgs e)
{
// Check if event is null
if (btnHandler != null)
btnHandler(string.Empty);

// Write some text to output
Response.Write(“User Control’s Button Click
”);
}
}

Fig - (2) WebUserControl.ascx.cs

Above code first check whether btnHandler is not null and than raise the event by passing argument. You can pass any number of argument in event. You need to change public delegate void OnButtonClick(string strValue) and btnHandler(string.Empty) lines for changing number of arguments. Now take a look at aspx page,

<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”Dalegate_Default” %>

<%@ Register Src=”WebUserControl.ascx” TagName=”WebUserControl” TagPrefix=”uc1″ %>





Untitled Page




runat=”server”>

Chirag
Dipak
Shailesh












Fig - (3) Default.aspx

Default.aspx has one drop down list and a user control as shown in above code. Lets look at cs file,

public partial class Dalegate_Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Declare and Define Event of User Control. When User Clicks on button
(which is inside UserControl)
// below event is raised as I have called raised that event on Button Click
WebUserControl1.btnHandler += new
Dalegate_WebUserControl.OnButtonClick(WebUserControl1_btnHandler);

}

void WebUserControl1_btnHandler(string strValue)
{
Response.Write(“Main Page Event
Selected Value: “ +
ddlTemp.SelectedItem.Text + “
”);
}
}

Fig - (4) Default.aspx.cs

Now when you run the application and clicks on button you can see that when user click on button the user control raise the click event and calls the WebUserControl1_btnHandler(string strValue) method on main page.

From Custom Authentication to ASP.NET Forms Authentication

Introduction
One of the first projects I tackled with .NET, after doing the customary "Hello World" example, was converting a commercial ASP application into ASP.NET.

The application tasks were to process, store and acknowledge (via email) customers' answers to a competition question and to provide a secure area for company officials to view customer entries and send out bulk mail.

Apart from learning how to implement each step in ASP.NET, I also restructured the application to make it more object-oriented. For the secure area of the site I initially more-or-less faithfully reproduced the original functionality. Then I discovered and investigated ASP.NET's built-in Forms Authentication.

What is authentication?
Authentication is the process of obtaining identification credentials, such as name and password, from a user and validating those credentials against some authority. If the credentials are valid, the entity that submitted the credentials is considered an authenticated identity. Once an identity has been authenticated, the authorization process determines whether that identity has access to a given resource.

ASP.NET provides two other methods of authentication that are platform-specific with respect to the client, whereas Forms Authentication isn't. A couple of other articles on this site provide more in-depth insight into Forms Authentication. Here, I just provide the basics and discuss the issues I needed to address in my authentication process.

The Problem
A company official (also referred to as an administrator) wants to view the list of names and email addresses of the people who have entered the competition and the answers they've provided. The official may then perform other tasks, such as running queries or sending bulk mail.

The security requirements are:

Access to the pages in the secure area requires the official to log in with a valid user name and password.
Any attempt to navigate to a page in the secure area should redirect a user to the Login page.
It should not be possible to view any page when the browser is in offline mode, thereby bypassing security.
There should be a limit on the number of login attempts within any browser session.
Now, this isn't an e-commerce application. No credit card details are being processed. It's not necessary to have rock-solid security. Nevertheless it's worth exploring how security can be breached.

There is no direct navigation from the customer pages to the secure area but suppose somehow a customer or other user discovers the URL to one of the pages in the secure area. Then our security mechanism will force them to login. It will throw them out after a specified number of invalid attempts (say 3). Though they can shut down the browser and try again, but they don't know that. Hopefully they'll be discouraged. But if not, they'll still have a hard time discovering the correct user name and password. An administrator will be aware that they can restart the browser though. So if they forget their login details they can try again to their heart's content.

A more serious breach would be a malicious user's hacking the web site, downloading the database and extracting the login details. For this application we are just using a simple Microsoft Access database. The database is password-protected so it can't be opened in Access. But you can open the database in a text editor and perhaps have a poke around (it's mostly gibberish but it does contain the odd English word fragment). We could encrypt the database but we haven't.

The last possibility (I think) is a network sniffer's intercepting and extracting the user name and password as they are transported across the network. I have not catered for this. But it can be addressed by using Secure Sockets Layer (SSL) to encrypt the user name and password as they are passed over the network. If there is a security breach then a hacker would have access to the names and email addresses of our customers and could send them junk mail. That's it. In the initial design, at least, company officials cannot directly update the database via the web. All operations are read-only. So these restrictions would apply to a hacker too.

Initial Solution
We roll our own authentication functionality. First, define some Session objects in Global.asax.

protected void Session_Start(Object sender, EventArgs e)
{
// Administrator will only be allowed a certain number of login attempts
Session["MaxLoginAttempts"] = 3;
Session["LoginCount"] = 0;

// Track whether they're logged in or not
Session["LoggedIn"] = "No";
}

The login code looks like this.

Collapse
// Note: here we are just faithfully reproducing the original ASP behaviour.
// Otherwise we would use ASP.NET authentication.

// Check number of login attempts not exceeded. If it is redirect to failed
// login page.
int maxLoginAttempts = (int)Session["MaxLoginAttempts"];

if (Session["LoginCount"].Equals(maxLoginAttempts))
{
Response.Redirect("LoginFail.aspx?reason=maxloginattempts");
}

// Attempt login
if (Request.Form["txtUserName"].Trim() == AdministratorLogin.UserName &&
Request.Form["txtPassword"].Trim() == AdministratorLogin.Password)
{
// Success, so we can access customer details.
Session["LoggedIn"] = "Yes";
Response.Redirect("CustomerDetails.aspx");
}
else // Fail to login
{
// Report failure
string invalidLogin = "Invalid Login.";
lblMessage.Text = invalidLogin;

// Track the number of login attempts
int loginCount = (int)Session["LoginCount"];
loginCount += 1;
Session["LoginCount"] = loginCount;
}

When the login page is loaded it first checks to see whether the maximum number of login attempts has been exceeded. If it has the user is redirected to the "failed login" page.

If the user has not exceeded the maximum number of login attempts the user name and password are validated against those returned by the AdministratorLogin object. Here I have just provided a couple of read-only properties which retrieve the user name and password from a persistent store (in this case, a database). If all is OK the user can access the customer details page. If not, an invalid login message is displayed to the user and they can try again up until the allowable number of attempts.

Once the allowable number of login attempts has been exceeded the user will be unable to attempt a login again without being redirected to the "failed login" page.

If the user tries to access any other page in the secure area they are automatically directed to the login page. This is because the Page_Load event of each page calls a custom authentication function that looks like this.

///
/// Authenticates user for access to administration pages.
/// Ensures that page can't be navigated to
/// without user's being online and logged in.
///

protected void AuthenticateUser()
{
// Prevent caching, so can't be viewed offline
Response.Cache.SetCacheability(HttpCacheability.NoCache);

// Can't navigate to the page unless already logged in.
// If not already logged in go to login page.
if (Session["LoggedIn"].Equals("No"))
{
Response.Redirect("Login.aspx");
}
}

Without the first line users can navigate to a secure page when the browser is offline, if the page is in the history list, which is not what we want!

Forms Authentication Solution
The principal effect of using ASP.NET's Forms Authentication mechanism is that we no longer need to track the login state. The AuthenticateUser function above disappears. Nor do we have to write our own code to retrieve the user name and password from the database. But in order to use the mechanism we must add some sections to the web.config file in the application root directory. In the authentication section we replace the default settings with the following:
















Then, after the closing system.web tag:










The effect of these settings is that all pages in the directory are protected from access except through the login mechanism. Any files in sub-directories are also protected unless they contain their own web.config files with different settings.

In the authentication section, "FwLoginCookie" is the name of the cookie created by the authentication mechanism. Sometimes we may not want to use cookies. But for the present purposes these pages are for access only by company officials. They won't mind having cookies from themselves so to speak!

"Login.aspx" is the page to be redirected to if a user accesses any other page in the directory. The credentials section contains a list of valid user names and passwords in clear format. An alternative is to encrypt them. (There is a framework function that can do this.) Instead of putting the user name and password in the web.config file they could be placed in an external XML Users file (or a database). This is the solution we would go for if we wanted to add new users to the system.

The authorization section's settings deny anonymous (i.e., unauthenticated) users access to our pages.

The location section allows us to override the authentication and authorization checks for the LoginFail.aspx page. We need to do this so that an unauthenticated user can be redirected here when their login fails (i.e., after exceeding the allowable number of login attempts). An alternative is to put the LoginFail.aspx page in another directory or in a sub-directory with its own web.config file.

The revised code looks like this. The Session["LoggedIn"] object is no longer required:

protected void Session_Start(Object sender, EventArgs e)
{
// Administrator will only be allowed a certain number of login attempts
Session["MaxLoginAttempts"] = 3;
Session["LoginCount"] = 0;
}

The Login code now just uses ASP.NET's Forms Authentication methods instead of the custom user name and password checking functionality implemented in the initial solution:

Collapse
// Check number of login attempts not exceeded. If it is redirect to
// failed login page.
int maxLoginAttempts = (int)Session["MaxLoginAttempts"];

if (Session["LoginCount"].Equals(maxLoginAttempts))
{
Response.Redirect("LoginFail.aspx?reason=maxloginattempts");
}

// Attempt login
if (FormsAuthentication.Authenticate(txtUserName.Text.Trim(),
txtPassword.Text.Trim()))
{
// Success, create non-persistent authentication cookie.
FormsAuthentication.SetAuthCookie(txtUserName.Text, false);

// Navigate to Customer Details
Response.Redirect("CustomerDetails.aspx");
}
else // Fail to login
{
// Report failure
string invalidLogin = "Invalid Login.";
lblMessage.Text = invalidLogin;

// Track the number of login attempts
int loginCount = (int)Session["LoginCount"];
loginCount += 1;
Session["LoginCount"] = loginCount;
}

In the Page_Load event in each protected page we still need to prevent offline viewing.

// Prevent caching, so can't be viewed offline
Response.Cache.SetCacheability(HttpCacheability.NoCache);

That's it. Again, to make it solid, we should also apply SSL to prevent user name and password interception.

Insert,Update and Delete in XML file with xmldoc nad xmlelement

How to Read XML and insert a node in xml file
--------------------------------------------

'Insert in xml if not available.....
Dim strXmlPath As String = Server.MapPath("~/App_Data/reminder.xml")
Dim xmlDoc As New XmlDocument()
xmlDoc.Load(strXmlPath)
Dim nodeList As XmlNodeList = xmlDoc.SelectNodes("/reminder_list/reminder[@ID='" & Session("UserName").ToString().ToLower() & "']")

Dim xmlNamespace As String = [String].Empty
Dim parentNode As XmlElement = xmlDoc.CreateElement("reminder", xmlNamespace)
xmlDoc.DocumentElement.AppendChild(parentNode)
Dim t As XmlNode = xmlDoc.SelectSingleNode("/reminder_list/reminder[@rem_id='" & objReminder.ReminderId & "' and @ID='" & Session("UserName").ToString().ToLower() & "' and @subject='" & txtSuject.Text.Trim & "']")
If Convert.ToString(t) <> "" Then
t.ParentNode.RemoveChild(t)
parentNode.SetAttribute("end_date", strRemDateTime)
parentNode.SetAttribute("ID", Session("UserName").ToString().ToLower())
parentNode.SetAttribute("rem_id", hidremid.Value)
parentNode.SetAttribute("subject", txtSuject.Text.Trim)
parentNode.SetAttribute("start_date", Date.Now)
parentNode.SetAttribute("reminder", txtmsg.Text)
parentNode.SetAttribute("flag", 1)
xmlDoc.Save(strXmlPath)
Else
parentNode.SetAttribute("end_date", strRemDateTime)
parentNode.SetAttribute("ID", Session("UserName").ToString().ToLower())
parentNode.SetAttribute("rem_id", hidremid.Value)
parentNode.SetAttribute("subject", txtSuject.Text.Trim)
parentNode.SetAttribute("start_date", Date.Now)
parentNode.SetAttribute("reminder", txtmsg.Text)
parentNode.SetAttribute("flag", 1)
xmlDoc.Save(strXmlPath)
End If

Custom Paging in ASP.NET with C# and SQL SERVER Stored Procedures

how to do custom paging::
------------------------------------

stored procedure::

ALTER PROCEDURE [dbo].[GetProductListBySearch1]
(
@currentpage varchar(100) = null,
@pagesize int
)

AS
SET NOCOUNT ON
declare @query varchar(4000)
declare @querycnt varchar(4000)

declare @skiprecords int
set @skiprecords=(@currentpage -1) * @pagesize

if(@skiprecords <0)
set @skiprecords=0

SELECT ROW_NUMBER() OVER (ORDER BY id desc) as id,title
FROM article

declare @totalrecords int
declare @no int
declare @pageno int

set @totalrecords= (select count(*) from article)
set @pageno=(@totalrecords / convert(varchar,@pagesize))

if((@totalrecords / convert(varchar,@pagesize))>0)
begin
set @pageno=@pageno+1
end

select @pageno as total_pages, @totalrecords
return



aspx.cs page:::
---------------------------

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 DLL;
using System.IO;
public partial class Default2 : System.Web.UI.Page
{
PagedDataSource page = new PagedDataSource();
DataTable dt=new DataTable();
int index = 0;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
getdata();
}
}

public void getdata()
{
dt = Class1.getdata();
if (dt.Rows.Count > 0)
{
page.DataSource = dt.DefaultView;
page.AllowPaging = true;
page.PageSize = 2;
page.CurrentPageIndex = index;


ArrayList array = new ArrayList();
for (int i = 0; i < page.Count; i++)
{
array.Add((i + 1).ToString());
}

rpt.DataSource = array;
rpt.DataBind();
// changecolor();
GridView1.DataSource = page;
GridView1.DataBind();
}
}


protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = GridView1.Rows[e.RowIndex];

}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
}
protected void rpt_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "change")
{
index = Convert.ToInt32(e.CommandArgument.ToString()) - 1;
getdata();
}
}
protected void rpt_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (rpt.Items.Count >= 0)
{
LinkButton lnk = (LinkButton)e.Item.FindControl("lnk");

lnk.ForeColor = System.Drawing.Color.Red;
changecolor();
}
}
}
--------------------------

aspx page:::::::
------------------------------------

































<%#Container.DataItem %>