session not working asp.net - asp.net

I got a problem this session :
it's not working
protected bool ValidateForm()
{
if (username.Text == "")
{
Err.Text = "please enter username" + "<br/>";
return false;
}
if (password.Text == "")
{
Err.Text = "please enter password" + "<br/>";
return false;
}
return true;
}
protected void login_Click(object sender, EventArgs e)
{
if (ValidateForm())
{
SqlDataReader rd1 = Connection.Query("select count(id) as count from sarcadmintable where username ='" + username.Text+"'",true);
if(rd1.Read())
{
if (rd1["count"].ToString() == "0") Err.Text = "please check your username" + "<br/>";
else
{
SqlDataReader rd = Connection.Query("select * from sarcadmintable where username ='" + username.Text + "'", true);
if (rd.Read())
{
if (rd["password"].ToString() != password.Text)
Err.Text = "password is not correct" + "<br/>";
else
{
Session["id"] = rd["user_id"].ToString();
Session["prev"] = rd["prev"].ToString();
if (!String.IsNullOrEmpty(Request.QueryString["Return"].ToString()))
Response.Redirect(Encryption.Decypt_URL(Request.QueryString["Return"]));
else
Response.Redirect("Main/Default.aspx");
}
}
}
}
}
}
thats the code for login its work fine
... in the header of the master.site I put this code :
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["user_id"] == null || Session["user_id"].ToString() == "" || Session["user_id"].ToString() == "0") Response.Redirect("~/Login.aspx?Return=" + Encryption.Encypt_URL(Request.Url + ""));
SqlDataReader rd = Connection.Query("select firstname + ' ' + lastname as name from sarcuser where id=" + int.Parse(Session["id"].ToString()), true);
if (rd.Read())
{
label1.Text = rd["name"].ToString();
}
}
}
and in the web.config :
<!--<sessionState cookieless="true" regenerateExpiredSessionId="true" timeout="525600" mode="InProc" stateNetworkTimeout="525600"/>-->
<globalization requestEncoding="utf-8" responseEncoding="utf-8" culture="he-IL"/>
</system.web>
I make the session as a comment so I take the default for session
but its not working ... every time I press login with true username and password ... its redirect me to the login page ... and take the session as empty string
but the login code is fine and recover the right value ... any help ?

Consider this code in Page_Load
if (Session["user_id"] == null || Session["user_id"].ToString() == "" || Session["user_id"].ToString() == "0") Response.Redirect("~/Login.aspx?Return=" + Encryption.Encypt_URL(Request.Url + ""));
you are checking for user_id (Session["user_id"]) while you are storing with key id (Session["id"] = ....) in login button click handler
Edit: The above solution added
Previously provided out of context answer, left below as I think it may be useful for someone to know about this
The code that you are writing in the Page_Load event handler of master page, put that code in PreRender event handler and your label will be updated properly.
protected override void OnPreRender(EventArgs e)
{
if (!IsPostBack)
{
if (Session["user_id"] == null || Session["user_id"].ToString() == "" || Session["user_id"].ToString() == "0")
Response.Redirect("~/Login.aspx?Return=" + Encryption.Encypt_URL(Request.Url + ""));
SqlDataReader rd = Connection.Query("select firstname + ' ' + lastname as name from sarcuser where id=" + int.Parse(Session["id"].ToString()), true);
if (rd.Read())
{
label1.Text = rd["name"].ToString();
}
}
}
Now why this is happening?
This is happening because the Page_Load of the master page is called before the button_Click of the content page (Refer: Sequence that events are raised for Pages, UserControls, MasterPages and HttpModules. So the execution happens as follows:
Your browser request the page (login.aspx)
Login class is instantiated
OnPreInit of Login page is invoked (which specifies the master page)
Master page is instantiated
Login.Page_Load is executed
Master.Page_Load is executed
Your browser is requested to redirect to login.aspx
Execution terminates (why? because Response.Redirect causes current thread to terminate. If you want to prevent this abnormal termination and execute the complete page, pass 'false' as second parameter to Response.Redirect(url, false)
So, as you can see above, your button_click is never executed.
How to make user login
There are multiple options:
Do not use the same master page for the login page.
On the master page, check if current page is login.aspx, ignore the checking of login
Create a master page that specify the UI design and functionality that is same across public and authenticated access (call this master1.master). Create another master page (master2.master) which specify the check for authenticated user and functionality specific to authenticated user. Now login page will user master1.master as the master page and authenticated pages will user master2.master as master page. (somewhat same as first point, but the UI design is now placed in one master page only)
Any other that developers out there could suggest
Note: As suggested above, checking for authenticated user in PreRender is not recommended at all (that was just to update the label) as it may cause some code to be executed which should be prevented in one case or the other.

I don't see any actual user.authenticate() in your code. Is your page managed by another layer of authentication somewhere? For eg. I go to an open page, enter my credentials, you check my credentials, redirect me to a page that authenticates me and then boom I am back at login page. Also you might consider moving your authentication to the page_init unless you want to do it on every postback. I think you need to post a bit more here.

Related

Passing querystring with login control in asp.net 4?

Scenario:
I am doing project in C# ASP.NET 4.
I have a page of question. When somebody clicks on question (ie a Link Button) he is redirected to page where user can give answer but first he needs to login. So I put Login to Answer button that redirects user to GuestLogin.aspx with question id like this :
protected void LoginToAnswwer_Click(object sender, EventArgs e)
{
int qidrequest = int.Parse(Request.QueryString["qid"]);
Response.Redirect("~/GuestLogin.aspx?qid=" + qidrequest);
//This is working OK
}
And then when I am redirected to GuestLogin.aspx, I am putting below code in LoginButton of built in Login Control.
protected void LoginButton_Click(object sender, EventArgs e)
{
int qidrequest = int.Parse(Request.QueryString["qid"]);
Response.Redirect("QDisplay.aspx?qid=" + qidrequest);
}
Which is not working.
Question:
How to pass querystring with login button of built login control in asp.net 4 ?
You could pass a return URL to the login page, like this:
Response.Redirect(String.Format("/auth/login.aspx?return={0}", Server.UrlEncode(Request.Url.AbsoluteUri)));
In the login page, after authenticating the user:
Response.Redirect(Request.QueryString["return"]);
Pass Parameters from One Page to Another Page using QueryString :
//Set the Querystring parameters
Note: Maximum length of the
string that can be passed through QueryString is 255.
string URL =“QueryString.aspx?Name=” + txtFirstName.Text + “&Address=” + txtAddress.Text + “&City=” + txtCity.Text ;
//After Setting the Querystring Paramter values Use Response.Redirect to navigate the page
Response.Redirect(URL);
In the Page Load Event of the Navigated
Page,You can access the querystring parameter values like below :
lblName.Text = Request.QueryString["Name"].ToString();
lblAddress.Text = Request.QueryString["Address"].ToString();
lblCity.Text= Request.QueryString["City"].ToString();
That's how you have to use QueryString for passing parameters

Using ASP.NET Cache/ViewState/Session

I'm trying to learn about Cache, Page ViewState, and Session. I created an ASP.NET web app in VS2010 and added 3 text boxes and a button to the page. I run in debug mode, enter random text into each, press the button, and nothing seems to be saved (all text is "null", as you'll see in the code). Am I performing these action in the wrong place? Do I need to add something to the web.config? Here is the code I'm using:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
if (Cache["textbox1"] != null)
TextBox1.Text = (string)Cache["textbox1"];
else
TextBox1.Text = "null";
if (ViewState["textbox2"] != null)
TextBox2.Text = (string)ViewState["textbox2"];
else
TextBox2.Text = "null";
if (Session["textbox3"] != null)
TextBox3.Text = (string)Session["textbox3"];
else
TextBox3.Text = "null";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Cache["textbox1"] = "(Cache) " + TextBox1.Text;
ViewState["textbox2"] = "(VS) " + TextBox2.Text;
Session["textbox3"] = "(Session) " + TextBox3.Text;
}
And the page header:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="State._Default" EnableSessionState="True" EnableViewState="True" %>
Thanks, and sorry for the rookie question. I'm very new to this.
Page_Load happens before Button1_Click. So on Page_Load you always replace textbox text with something from statebags ("null" at first and then "(Cache)" + "null" etc). What you enter in textboxes never lives until Button1_Click.
Use Page_PreRender instead.
Right now, every time you click the button, the code in your Page_Load procedure is overwriting the TextBox.Text values before the Button1_Click event gets a chance to save them.
If you change if (IsPostBack) to if (!IsPostBack), the values will only attempt to be loaded from session/viewstate/cache when you initially request the page. So you would have to request the page, set new values with the button, then re-request (Enter key in address bar) to run the code in Page_Load.
What I would suggest is you create a new button called "Load Values" whose Click event will run the code currently found in your Page_Load. That way you don't have to tie that code to whether the request was a postback or not. I think it would make your test results much easier to understand.

Read Response.write in another Page

I have a page www.senderdomain.com/sender.aspx, from which i need to write a string to another page in other domain www.receiverdomain.com/receiver.aspx
In sender.aspx i have written
Response.Write("Hello");
Response.Redirect(Request.UrlReferrer.ToString());
It gets redirected to respective receiver.aspx page, but I am not sure how to get the text "Hello" in receiver.aspx page. Can any pl help on this?
It seems you have a value on Sender.aspx that you need to display in receiver.aspx. This is how you can do it.
//On Page_Load of sender.aspx
Session["fromSender"] = "Hello";
Respone.Redirect("receiver.aspx");
Response.End();
//On Page_Load of receiver.aspx
if(!string.IsNullOrEmpty(Session["fromSender"].ToString()))
Response.Write(Session["fromSender"].ToString());
EDIT
In case of change in domain, immediate easy way is to pass the value in query-string.
//On Page_Load of sender.aspx
Response.Redirect("http://www.receiverdomain.com/receiver.aspx?fromSender=Hello");
Response.End();
//On Page_Load of receiver.aspx
if(!string.IsNullOrEmpty(Request.QueryString["fromSender"].ToString()))
Response.Write(Request.QueryString["fromSender"].ToString());
You may observe that the code pattern remains the same and container that is used to transfer the value changes from Session to QueryString.
EDIT2
If security is a concern with you in this case and you don't wish to expose the value ["Hello"], then here comes another way that can help you. In this solution we will first redirect the page to receiver and then from receiver it shall ask for the value to sender. So first we'll write the code for receiver.
//On Page_Load of receiver.aspx
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//Remember to use System.Net namespace
HttpWebRequest requestToSender = (HttpWebRequest)WebRequest.Create("http://www.senderdomain.com/sender.aspx?cmd=getvalue");
HttpWebResponse responseFromSender = (HttpWebResponse)requestToSender.GetResponse();
string fromSender = string.Empty;
//Remember to use System.IO namespace
using (StreamReader responseReader = new StreamReader(responseFromSender.GetResponseStream()))
{
fromSender = responseReader.ReadToEnd();
}
Response.Write(fromSender);
Response.End();
}
}
And in the sender.aspx
//On Page_Load of sender.aspx
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (!string.IsNullOrEmpty(Request.QueryString["cmd"].ToString()))
{
string cmd = Request.QueryString["cmd"].ToString();
if (cmd.Equals("getvalue", StringComparison.OrdinalIgnoreCase))
{
Response.Clear();
Response.Write("Hello");
Response.End();
}
}
Response.Redirect("http://www.receiverdomain.com/receiver.aspx");
Response.End();
}
}
You need to pass the value in the url or post it in a cross page postback.
For secure cross domain communication, take a look at SAML (Security Assertion Markup Language). It is a standard way of passing information securely across domain boundaries. It is most often used in Single Sign On scenarios, but it can be used to pass data securely. Are you using certificates? What type of encryption are you using?
Another option would be to save state to a database or filesystem that is accessible to both domains.
pass data in query string because can not do like this
for example
Response.Redirect(Request.UrlReferrer.ToString() + "?mytext=hello");
And in receiver page access querystring data, will resolve your issue.
use private algorithm like
string message = "hello";
add 1 to each char so that hello become ifmmp
and on receiver side -1 from each char so it will be hello
The Response.Redirect method will scrap everything that you have written to the page, and replace it with a redirection page, so you can't send any content along with the redirect.
The only option to send data along in a redirect (that works between differnt domains and different servers) is to put it in the URL itself. Example:
string message = "Hello";
Response.Redirect(Request.UrlReferrer.ToString() + "?msg=" + Server.UrlEncode(message));
Another option is to output a page containing a form that is automatically posted to the destination:
string message = "Hello";
Response.Write(
"<html>" +
"<head><title>Redirect</title></head>" +
"<body onload=\"document.forms[0].submit();\">" +
"<form action=\"" + Server.HtmlEncode(Request.UrlReferrer.ToString()) + "\" method=\"post\">" +
"<input type=\"hidden\" name=\"msg\" value=\"" + Server.HtmlEncode(message) + "\">" +
"</form>" +
"</body>" +
"</html>"
);
Response.End();
You can use Request.Form["msg"] on the recieving page to get the value.
Don't use the built-in URL encode, if you want to avoid all sorts of problems later.
String UrlEncode(String value)
{
StringBuilder result = new StringBuilder();
foreach (char symbol in value)
{
if ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~".IndexOf(symbol) != -1) result.Append(symbol);
else result.Append("%u" + String.Format("{0:X4}", (int)symbol));
}
return result.ToString();
}
The above supports unicode, and pretty much everything.

Login Control - Response.Redirect

I have a usercontrol on a page that has a login control in it. This controls the display of another user control (if the user is not logged in they get the login control user control). I have some authentication code (see below) that runs when the user clicks the "Login" button. Basically I want it to post back to the same page so they will be logged in and able to now see the other protected user control. This code is not working. Perhaps there is something going on in another page that is making this not work, but does this code itself seem like it should work?
string userName = Membership.GetUserNameByEmail(Login1.UserName);
if (userName != null)
{
e.Authenticated = Membership.ValidateUser(userName, Login1.Password);
}
else
{
e.Authenticated = false;
}
if (e.Authenticated)
{
Login1.UserName = userName;
ImageButton loginButton = (ImageButton)Login1.FindControl("LoginButton");
if (loginButton != null)
{
//loginButton.PostBackUrl = Request.Url.ToString();
Response.Redirect(Request.Url.ToString());
}
}
The issue is the login control will itself do a redirect setting a cookie or an encrypted authentication ticket in the url (cookieless).
I think the login control has some properties where you can tell it where it will be redirecting to (which overrides the one in the web.config).
DestinationPageUrl is the property... soo Login1.DestinationPageUrl = "~/whatever.aspx";

UpdatePanel doesn't Refresh

I have got a simple page with a HtmlInputHidden field. I use Javascript to update that value and, when posting back the page, I want to read the value of that HtmlInputHidden field. The Value property of that HtmlInputHidden field is on postback the default value (the value it had when the page was created, not the value reflected through the Javascript). I also tried to Register the HtmlInputHidden field with ScriptManager.RegisterHiddenField(Page, "MyHtmlImputHiddenField", "initialvalue") but it still only lets me read the 'initialvalue' even though I (through javascript) can inspect that the value has changed.
I tried to hardcoded the rowid and, to my surprise, after postback gridview was exactly the same before the delete but the record was deleted from the database. (I´ve called the databind method).
protected void gridViewDelete(object sender, GridViewDeleteEventArgs e)
{
bool bDelete = false;
bool bCheck = false;
if (hfControl.Value != "1")
{
// check relationship
bCheck = validation_method(.......);
if (bCheck)
{
bDelete = true;
}
}
else
{
hfControl.Value = "";
bDelete = true;
}
if (bDelete)
{
//process delete
}
else
{
string script = string.Empty;
script += " var x; ";
script += " x = confirm('are u sure?'); ";
script += " if (x){ " ;
script += " document.getElementById('hfControl').value = '1'; ";
script += " setTimeOut(__doPostBack('gridView','Delete$"
+ e.RowIndex + "'),0);";
script += " } ";
ScriptManager.RegisterClientScriptBlock(this,
Page.GetType()
, "confirm"
, script
,true);
}
}
On a postback, when the page loads is the view of the hidden field what was posted back or is it the value you set when the page loads? It may be that you have to worry about the case where in the postback you aren't resetting a value to what it was originally. Another point is that if you do a delete, are you refreshing the data that you show or is it the same? Those would be my suggestions.
When I do a postback the value is the same what was postedback. I think updatepanel wasnt refresh. I tried to do __doPostBack('UpdatePanel1',''), didnt work either.

Resources