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

No comments: