EDIT: made variables not-static.
I have a variable in code-behind class and want to access it from another.
Here's the C# code for the "Signup" page:
public partial class Webform_Signup : System.Web.UI.Page
{
private string user;
public string User
{
get { return user; }
set { user = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
if(HttpContext.Current.Request["submit"] != null)
{
user = HttpContext.Current.Request["user"];
Response.Redirect("Login.aspx");
}
}
}
And here's the code for another code-behind class in an .aspx class "Login":
public partial class Webform_Login : System.Web.UI.Page
{
public string loguser = "";
protected void Page_Load(object sender, EventArgs e)
{
if(HttpContext.Current.Request["logsubmit"] != null)
{
loguser = HttpContext.Current.Request["loguser"];
if (loguser == Webform_signup.User)
{
Response.Redirect("Start");
}
}
}
}
The problem is that when I try to access Webform_signup.user, it displays an error saying:
The name Webform_Signup does not exist in the current context.
Anyone has an idea of how to fix it?
The dirt simplest way (and probably not the best way) is to just stick it in a session variable and read it from there instead.
public partial class Webform_Signup : System.Web.UI.Page
{
private string user;
public string User
{
get { return user; }
set { user = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
if(HttpContext.Current.Request["submit"] != null)
{
user = HttpContext.Current.Request["user"];
HttpContext.Current.Session["user"] = user; //Save to session
Response.Redirect("Login.aspx");
}
}
}
public partial class Webform_Login : System.Web.UI.Page
{
public string loguser = "";
protected void Page_Load(object sender, EventArgs e)
{
if(HttpContext.Current.Request["logsubmit"] != null)
{
loguser = HttpContext.Current.Request["loguser"];
var user = HttpContext.Current.Session["user"]; //Read from session
if (loguser == user)
{
Response.Redirect("Start");
}
}
}
}
This is assuming of course that you have session state enabled.
You need to keep in mind lifecycles. You're ignoring them, and the results would be disastrous in this case.
Any time you declare a variable as static, there will only be one instance of that variable in your application. That means no matter what user is using your app, the Webform_Signup.User field will be shared. That could result in users accessing other users' information! That's really, really bad.
Also, page classes should not be referring to other page classes. A page only exists when a user is accessing that page.
If you want to login a user, then perhaps you should research Forms Authentication. Or better yet, learn a modern framework like ASP.NET Core MVC instead of Web Forms, which is a deadend platform.
Related
I want to change masterpagefile using another class function
Example:
public class XYZClass
{
public void CheckLogin(object ses,bool ipb,ref MasterPage page)
{
if (!(ses == null))
{
if (ses.ToString() == "Admin")
page.MasterPageFile = "~/Admin.master";
else
page.MasterPageFile = "~/MasterPage.master";
}
else
{
Response.Redirect("~/frmLogin.aspx");
}
}
}
public partial class frmDoctorHistory : System.Web.UI.Page
{
BLLcheckLogin checkLogin = null;
protected void Page_PreInit(object sender, EventArgs e)
{
checkLogin = new BLLcheckLogin();
checkLogin.CheckLogin(Session["usertype"], IsPostBack, ref MasterPageFile);
}
}
and I call this function from another aspx source file, and it gives me an error like
"A property, indexer or dynamic member access may not be passed as an out or ref parameter".
You can set the Master Page no later than in the PreInit event.
See the code sample from MSDN as a reference.
void Page_PreInit(Object sender, EventArgs e)
{
this.MasterPageFile = "~/NewMaster.master";
}
You have to rewrite your current code as:
public void CheckLogin(object ses,bool ipb, Page page)
{
if (!(ses == null))
{
if (ses.ToString() == "Admin")
page.MasterPageFile = "~/Admin.master";
else
page.MasterPageFile = "~/MasterPage.master";
}
else
{
Response.Redirect("~/frmLogin.aspx");
}
}
protected void Page_PreInit(object sender, EventArgs e)
{
checkLogin = new BLLcheckLogin();
MasterPage mp;
checkLogin.CheckLogin(Session["usertype"], IsPostBack, this);
}
I altered your code to pass in the Page rather than the MasterPageFile property. Ref isn't necessary any more then.
in windows application , when i want to call a customized form , i ueses this method :
result frm = new result();
frm.firstparameter = "first parameter";
frm.secondparameter = "second parameter";
frm.showdialog();
but in web application , i do not know how to handle it .
here is my webapplication source code :
in WebForm1.aspx.cs :
protected void sumbitbtn_Click(object sender, EventArgs e)
{
result frm = new result();
frm.firstparameter = "firstparameter";
frm.secondparameter = "secondparameter";
// frm.showpage() ???
// Response.Redirect("~/result.aspx");
}
in result.aspx.cs :
public partial class result : System.Web.UI.Page
{
private string Firstparameter = string.Empty;
public string firstparameter
{
get{return Firstparameter;}
set { Firstparameter = value; }
}
private string Secondtparameter = string.Empty;
public string secondparameter
{
get{return Secondparameter;}
set { Secondparameter = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
firstlbl.Text=Firstparameter;
secondlbl.Text=Secondtparameter;
}
}
ASP.NET does not work that way. If you want to open one page after the other - you need to send a redirect request to do so. Of course you can also open popup, or make server transfer, but in your case redirect seems to be the best thing to do. Also note that parameters are not just passed into constructor or property - you need to attach them to the request, for example with query string.
So, in WebForm1.aspx.cs:
protected void sumbitbtn_Click(object sender, EventArgs e)
{
string url = string.Format("~/result.aspx?fp={0}&sp={1}", "firstparameter", "secondparameter");
Response.Redirect(url);
}
In result.aspx.cs :
public partial class result : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
firstlbl.Text = Request["fp"];
secondlbl.Text = Request["sp"];
}
}
Note that this code leaves a lot of things out (parameter null handling for one), it just shows the point.
I am pretty new to .NET - I am making a site that has an admin section that should only be visible to logged in users.
I have created the login code and once a user is authenticated, I then assign them a session variable.
My question is : is there a more efficient way to check the session variable rather than having the following function on each page?
protected void Page_Load(object sender, EventArgs e)
{
checkSession();
}
public void checkSession()
{
if (Session["LoggedIn"] != "true")
{
Response.Redirect("default.aspx");
}
}
thanks kindly!
if you are using a MasterPage you can put the checking code in the MasterPage's Page_Load event if not use either the Global.asax or a custom HttpModule and put the cheking code inside the the AcquireRequestState event handler for the first and the PostRequestHandlerExecute event handler for the second
Exmaple with Global.asax
public class Global : System.Web.HttpApplication
{ ...
void Application_AcquireRequestState(object sender, EventArgs e)
{
HttpContext context = HttpContext.Current;
// CheckSession() inlined
if (context.Session["LoggedIn"] != "true")
{
context.Response.Redirect("default.aspx");
}
}
...
}
You should probably consider using forms authentication:
http://www.asp.net/web-forms/videos/authentication/using-basic-forms-authentication-in-aspnet
You can configure a page, or folder to always require authorization, so the runtime will take care of that requirement rather than you having to check manually.
You could make your page a class that inherits from a base class that checks for logged in users.
Derive your pages from a custom class that derives from Page
override the Load method by adding your session check code
now all your pages have the validation
public class MyPage : System.Web.UI.Page
protected void Page_Load(object sender, EventArgs e)
{
if (Session["yoursession"] != "true")
{
//code
}
}
public class yourCustomPage1 : MyPage
{
protected void Page_Load(object sender, EventArgs e)
{
//you don't have to check or call any method..
}
}
public class yourCustomPage2 : MyPage
{
protected void Page_Load(object sender, EventArgs e)
{
//you don't have to check or call any method..
}
}
etc...
A good way to start to understand forms authentication in ASP.Net is creating a brand new website.
Go in Visual Studio and create New Project, select Web, then ASP.NET Web Application.
Check it out in Account folder to understand the process and ASP.Net methods.
You can create BasePage and inherit all your page from this base page , set the function in your basepage.
public class BasePage : Page
{
protected void checkSession()
{
if (Session["LoggedIn"] != "true")
{
Response.Redirect("default.aspx");
}
}
}
Your Page
public partial class YourPage : BasePage
{
....
}
Another solution :
In your Http Module, create Principal(Roles) and Identity in order to set authentification and authorization functionnalities, in your http module attach theses informations to current thread.
link : http://msdn.microsoft.com/en-us/library/system.security.principal.iidentity.isauthenticated.aspx
public class BasePage : Page
{
protected void checkSession()
{
if (Session["LoggedIn"] == null)
{
Response.Redirect("~/default.aspx/");
}
}
}
1st Way : Global.asax.cs ADD
void Application_AcquireRequestState(object sender, EventArgs e)
{
HttpContext context = HttpContext.Current;
Page page = context.Handler as Page;
if ((string)context.Session["LoggedIn"] != "true"
&& !(page.AppRelativeVirtualPath == "~/Default.aspx"))
context.Response.Redirect("default.aspx");
}
2nd Way : You can have the same session management in Master page. Page Load event.
Hope this helps.
You can add this code in the GLOBAL.asax.cs this will check if the session is empty and also it will not redirect if this the request is initialized from the Login page otherwise it will stuck in a loop.
void Application_AcquireRequestState(object sender, EventArgs e)
{
HttpContext context = HttpContext.Current;
// CheckSession() inlined
if (Context.Request.Url.LocalPath != "/UIComponents/User/Login.aspx")
{
if (context.Session["Name"] == null)
{
FormsAuthentication.RedirectToLoginPage();
}
}
}
i have a user control class named EmployeeInformation.aspx.cs with a Textfield txtRegistrationNo
public partial class EmployeeInformation : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
public string TextRegistrationNo
{
get
{
return txtRegistrationNo.Text;
}
}
}
Now in another class named SeparationInfo.aspx.cs how can i access txtRegistrationNo field?
You have to access it through object of your custom control, suppose the instance of EmployeeInformation is EmployeeInformation1
string TextRegistrationNo = EmployeeInformation1.TextRegistrationNo;
EmployeeInformation objEmployeeInfo = new EmployeeInformation();
string temp = objEmployeeInfo.TextRegistrationNo;
I am having 3 classes. One is AuthenticateUser which let me to set and get user information such as username and password. In other class, AddEntryWindow is a WinForm in which I am trying to display content of the Password and UserName properties from AuthenticateUser. third class is another WinForm class which let me to set username and password to the AuthenticateUser class. As I try, in this simplified example, to display username and password from a WinForm class I am getting a blank message box. Also, when using another message box in AuthenticateUserWindow I am able to get the content of properties.
How can I fix this to be able to view content of the property in AddEntryWindow class? I have been staring blank for past hour on this.
Probably it's something with line: AuthenticateUser authenticateUser = new AuthenticateUser(); which create a new object. But where would it go instead?
Most likely problem in AddEntryWindow.cs
using System;
using System.Windows.Forms;
// Needed to be used with StringBuilder
using System.Text;
// Needed to be used with ArrayList.
using System.Collections;
namespace Store_Passwords_and_Serial_Codes
{
public partial class AddEntryWindow : Form
{
// Making authentication possible.
AuthenticateUser authenticateUser = new AuthenticateUser();
// Default constructor to initialize the form.
public AddEntryWindow()
{
InitializeComponent();
}
private void btnAddEntry_Click(object sender, EventArgs e)
{
MessageBox.Show(authenticateUser.UserName + authenticateUser.Password);
}
}
}
AuthenticateUser.cs
using System;
namespace Store_Passwords_and_Serial_Codes
{
class AuthenticateUser
{
private string userName, password;
public AuthenticateUser()
{
}
public AuthenticateUser(string userNamePassed, string passwordPassed)
{
this.userName = userNamePassed;
this.password = passwordPassed;
}
public string UserName
{
get
{
return userName;
}
set
{
userName = value;
}
}
public string Password
{
get
{
return password;
}
set
{
password = value;
}
}
}
}
AuthenticateUserWindow.cs
using System;
using System.Windows.Forms;
namespace Store_Passwords_and_Serial_Codes
{
public partial class AuthenticationWindow : Form
{
// Most important log in information needs to be entered
// for encrypting and decrypting binary file.
AuthenticateUser authenticateUser;
public AuthenticationWindow()
{
InitializeComponent();
}
private void btnClose_Click(object sender, EventArgs e)
{
// Closing Authentication Window form.
Close();
}
private void btnClear_Click(object sender, EventArgs e)
{
// Clearing text boxes txtUserName and txtPassword
// after Clear Form button is clicked.
txtUserName.Clear();
txtPassword.Clear();
}
private void btnAuthenticate_Click(object sender, EventArgs e)
{
if (txtUserName.Text == string.Empty || txtPassword.Text == string.Empty)
{
MessageBox.Show("Please fill both information first.");
}
else
{
// Passing the values to object AuthenticateUser.
authenticateUser = new AuthenticateUser(txtUserName.Text, txtPassword.Text);
MessageBox.Show(authenticateUser.UserName + authenticateUser.Password);
Close();
}
}
}
}
Regards.
Like John said, you need to change the code as follows:
public partial class AddEntryWindow : Form
{
// Making authentication possible.
AuthenticateUser authenticateUser = new AuthenticateUser();
// Default constructor to initialize the form.
public AddEntryWindow()
{
InitializeComponent();
}
private void btnAddEntry_Click(object sender, EventArgs e)
{
new AuthenticationWindow(authenticateUser).ShowDialog();
MessageBox.Show(authenticateUser.UserName + authenticateUser.Password);
}
}
...
public partial class AuthenticationWindow : Form
{
// Most important log in information needs to be entered
// for encrypting and decrypting binary file.
AuthenticateUser authenticateUser;
public AuthenticationWindow(AuthenticateUser user)
{
InitializeComponent();
authenticateUser = user;
}
...
private void btnAuthenticate_Click(object sender, EventArgs e)
{
if (txtUserName.Text == string.Empty || txtPassword.Text == string.Empty)
{
MessageBox.Show("Please fill both information first.");
}
else
{
// Passing the values to object AuthenticateUser.
authenticateUser.UserName = txtUserName.Text;
authenticateUser.Password = txtPassword.Text;
MessageBox.Show(authenticateUser.UserName + authenticateUser.Password);
Close();
}
}
}
You are creating two separate instances of AuthenticateUser, one in AddEntryWindow and one in AuthenticationWindow. Just because they have the same name doesn't mean they are in the same scope.
Without knowing how your program works I can't give you the best option, but one would be to create a static class that acts as a global for AuthenticateUser. Another option would be to figure out how to pass the information between your Forms. If you create the AuthenticationWindow from the AddEntryWindow you could set an instance of AuthenticateUser as public in AuthenticationWindow and then access it when the window closes before you dispose of it.
Here i could infer a bit of workaround for your question, i do hope it is what your looking for.
If your invoking or launching AddWindowEntry form from AuthenticationWindow assuming that AuthenticationWindow is the parent form, then you have created AuthenticateUser object in this class. Pass this instance to the child form i.e AddWindowEntry and set to a local variable there. So when btnAddEntry_Click event gets executed, then you can display this local variables content in the message box.