Session is not being created...why? - asp.net

On login page i have created the session like this.
protected void Page_Load(object sender, EventArgs e)
{
Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();
if (Session["UserId"] != null)
{
Response.Redirect("~/client/ClientHome.aspx");
}
if (Request.QueryString["error"] != null)
{
loginuser.FailureText= "Please Login to visit the Page";
}
}
protected void loginuser_LoggedIn(object sender, EventArgs e)
{
if (Roles.IsUserInRole(loginuser.UserName, "admin"))
{
string username = loginuser.UserName;
DataSet ds = new DBUsers().GetUserId(username);
Guid userid = Guid.Parse(ds.Tables[0].Rows[0][0].ToString());
Session["UserId"] = userid;
Response.Redirect("Admin/Home.aspx");
}
else if (Roles.IsUserInRole(loginuser.UserName, "client"))
{
bool isPersistent = false;
string username = loginuser.UserName;
DataSet ds = new DBUsers().GetUserId(username);
Guid userid = Guid.Parse(ds.Tables[0].Rows[0][0].ToString());
Session["UserId"] = userid;
string userData = "ApplicationSpecific data for this user.";
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
username,
DateTime.Now,
DateTime.Now.AddMinutes(30),
isPersistent,
userData,
FormsAuthentication.FormsCookiePath);
// Encrypt the ticket.
string encTicket = FormsAuthentication.Encrypt(ticket);
// Create the cookie.
Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));
// Redirect back to original URL.
Response.Redirect(FormsAuthentication.GetRedirectUrl(username, isPersistent));
}
}
here value of session is not null , it contains userid
but when the home page loads it says that the value of session is null
protected void Page_Load(object sender, EventArgs e)
{
Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();
if (Session["UserId"] == null)
{
Response.Redirect("../Login.aspx?error=1");
}
}
why it enters inside if statement, why sesion value is null.

Related

Cookie always return null in asp.net

net web pages,in the first one, I wrote like below:
protected void lbXML_Click(object sender, EventArgs e)
{
HttpCookie cookie = new HttpCookie("RequestedXML");
cookie["xmlContent"] = hide_XML.Value;
Response.Cookies.Add(cookie);
cookie.Expires = DateTime.Now.AddMinutes(20);
Response.Write("<script>window.open('XML_Editor.aspx', '_blank', 'toolbar=no, location=no, resizable=yes, width=800px, height=500px', true);</script>");
}
In XML_Editor.aspx, I wrote code like this:
protected void Page_Load(object sender, EventArgs e)
{
Page lastPage = (Page)Context.Handler;
if (!IsPostBack)
{
HttpCookie cookie = Request.Cookies["RequestedXML"];
if (cookie != null)
{
TextBox1.Text = cookie["xmlContent"];
}
}
}
the problem is that the cookie always return null to me in Page_Load in XML_Editor.aspx, why is that?
Your problem can be you code, try it:
HttpCookie cookie = new HttpCookie("RequestedXML");
cookie.Value =hide_XML.Value;
cookie.Expires = DateTime.Now.AddMinutes(20);
Response.Cookies.Add(cookie);
Response.Write("<script>window.open('XML_Editor.aspx', '_blank', 'toolbar=no, location=no, resizable=yes, width=800px, height=500px', true);</script>");
XML_Editor.aspx
Page lastPage = (Page)Context.Handler;
if (!IsPostBack)
{
var cookie = Request.Cookies["RequestedXML"];
if (cookie != null)
{
Response.Write(cookie.Value);
}
}

How to stop opening a login page in (asp.net webforms) when user is already logged in the same browser in different tab

I have logged in as a user and it works fine , but when i try to open the login in a different tab in same browser it still goes to the login.aspx without the actual member page
Please help !
Aboutus.aspx
protected void Page_Load(object sender, EventArgs e)
{
if(Session["Username"] == null)
{
Response.Redirect("Login.aspx");
}
else
{
string Username = Session["Username"].ToString();
Label1.Text = Username;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Session.Abandon();
Response.Redirect("Login.aspx");
}
}
Login.aspx
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select COUNT(*)FROM [dbo].[Reg] WHERE Username='" + Login1.UserName + "' and Password=#pass");
cmd.Connection = con;
MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
////create an array of bytes we will use to store the encrypted password
Byte[] hashedBytes;
////Create a UTF8Encoding object we will use to convert our password string to a byte array
UTF8Encoding encoder = new UTF8Encoding();
////encrypt the password and store it in the hashedBytes byte array
hashedBytes = md5Hasher.ComputeHash(encoder.GetBytes(Login1.Password));
cmd.Parameters.AddWithValue("#pass", hashedBytes);
var username = Login1.UserName;
int OBJ = Convert.ToInt32(cmd.ExecuteScalar());
if (OBJ > 0)
{
if (username == "admin")
{
Session["Username"] = Login1.UserName;
Response.Redirect("AdminPanel.aspx");
}
else
{
Session["Username"] = Login1.UserName;
Response.Redirect("About.aspx");
}
}
else
{
Label1.Text = "Invalid username or password";
this.Label1.ForeColor = Color.Red;
}
}
}
}
In Page_Load of Login.aspx do this:
if(Session["Username"] != null)
{
string username = Convert.ToString(Session["Username"]);
if (username == "admin")
{
Response.Redirect("AdminPanel.aspx");
}
else
{
Response.Redirect("About.aspx");
}
}
Your page laod method on Loginpage must be like this
protected void Page_Load(object sender, EventArgs e)
{
if(Session["Username"] == null)
{
}
else
{
Response.Redirect("index.aspx",false);
}
}
I hope this helps

Putting Data from Cookie into a List<string> with ASP.net

I'm trying to make a shoppingcart using a cookie.
Every item has a Id which is put into the cookie.
Now I'm trying to put my cookie values into a List but I can't really find how to do it.
I want every value to be in a seperate index, is this possible?
Making the cookie:
HttpCookie myCookie = new HttpCookie("MyTestCookie");
Response.Cookies.Add(myCookie);
Adding a Id on buttonclick:
protected void Button1_Click(object sender, EventArgs e)
{
Request.Cookies["MyTestCookie"].Values.Add("", "3");
Response.Write(Request.Cookies["MyTestCookie"].Values.ToString());;
}
Try this
public void SetCookiesList(List<string> listOfCookies)
{
var req = HttpContext.Current.Request;
HttpCookie cookie = req.Cookies["cookieName"];
if (cookie != null)
{
var cookieVal = cookie.Value;
if (!string.IsNullOrEmpty(cookieVal))
listOfCookies.Add(cookieVal);
}
}

asp.net cookies are getting overwritten

I have an asp.net web application with one drop down box containing language preferences (English, French). When I select French I write cookie as following -
protected void ddChoice_SelectedIndexChanged(object sender, EventArgs e)
{
HttpCookie cookie = new HttpCookie("pref");
cookie.Value = ddChoice.SelectedValue;
cookie.Expires = DateTime.Now.AddYears(1);
Response.SetCookie(cookie);
Thread.CurrentThread.CurrentCulture = new CultureInfo(ddChoice.SelectedValue);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(ddChoice.SelectedValue);
Server.Transfer(Request.Path);
}
and read this cookie in begin request as follows -
protected void Application_BeginRequest(object sender, EventArgs e)
{
string lang = string.Empty;//default to the invariant culture
HttpCookie cookie = Request.Cookies["pref"];
if (cookie != null && cookie.Value != null && !string.IsNullOrEmpty(cookie.Value.Trim()))
lang = cookie.Value;
if (string.IsNullOrEmpty(lang))
lang = "en-US";
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(lang);
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(lang);
}
This time if I check the browser cookie it is rightly set to "fr-FR". But after this, when I go to home page and refresh this page cookie gets set to blank.
I'm not sure where it is getting overwritten. Any help?
I suppose that ddChoice_SelectedIndexChanged event is generated with empty SelectedValue and therefore your cookie is empty. Try to put breakpoint in the mehod or comment it out.
As your test case in the step 4 when you hit F5 page getting postback and language dropdown of language gets set with the default top language.
For that you need to write a function in control or page where your language dropdown is placed which set the selected lanaguage.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
setLangDropdown();
}
}
private void setLangDropdown()
{
HttpCookie cookie = Request.Cookies["pref"];
string lang = string.Empty;
if (cookie != null && cookie.Value != null && !string.IsNullOrEmpty(cookie.Value.Trim()))
lang = cookie.Value;
if (!string.IsNullOrEmpty(lang))
ddChoice.SelectedValue = lang;
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
HttpCookie cookie = new HttpCookie("pref");
cookie.Value = ddChoice.SelectedValue;
cookie.Expires = DateTime.Now.AddYears(1);
Response.SetCookie(cookie);
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(ddChoice.SelectedValue);
Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(ddChoice.SelectedValue);
}

Cookies or Session and how to begin

Heey Stackoverflow,
I have an question im started to learn asp.net language csharp and i have the following login code my question is how to begin or where can i learn to write down the session cookie and than i can get back to the other page to read this cookie out again for the username and password that did match ty very much
public partial class Administratie : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
string cnnString = ConfigurationManager.ConnectionStrings["Stefan"].ConnectionString;
using (SqlConnection con = new SqlConnection(cnnString))
using (SqlCommand cmd = new SqlCommand("select [Username],[Password] from Admin where [Username] = #Username and [Password] = #Password", con))
{
string Username = (textUsername.Text.Length > 0) ? textUsername.Text : null;
string Password = (TextPassword.Text.Length > 0) ? TextPassword.Text : null;
cmd.Parameters.Add("#Username", System.Data.SqlDbType.VarChar).Value = textUsername.Text;
cmd.Parameters.Add("#Password", System.Data.SqlDbType.VarChar).Value = TextPassword.Text;
con.Open();
using (SqlDataReader dr = cmd.ExecuteReader())
{
if (dr.Read())
if (Page.IsValid)
{
// Login Succeed
// Response.Redirect("Admin.aspx");
}
}
}
}
catch (Exception) { }
// Login Failed
Response.Write("Wrong Username ");
}
}
Try look here:
Create and retrieve Cookie data (C#)
Read a Cookie:
HttpCookie cookie = Request.Cookies["Preferences"];
if (cookie == null)
{
lblWelcome.Text = "<b>Unknown Customer</b>";
}
else
{
lblWelcome.Text = "<b>Cookie Found.</b><br><br>";
lblWelcome.Text += "Welcome, " + cookie["Name"];
}
Set a Cookie
HttpCookie cookie = Request.Cookies["Preferences"];
if (cookie == null)
{
cookie = new HttpCookie("Preferences");
}
cookie["Name"] = txtName.Text;
cookie.Expires = DateTime.Now.AddYears(1);
Response.Cookies.Add(cookie);
If you want to store data in a Session just set it:
Session["username"]=username;
and read:
string username=Session["username"];
You can use session to store username and password. If you want to use remember me option you can save the username and password in cookies.
Please check the links for using session and cookies

Resources