how to get the session variable in many pages in C#? - c#

I have a field named username as the session variable. I have added a class which inherits the base page. Now I want the code to get the session variable in all the pages that the user moves through.
Please help me with the code.

You should be able to access the Session variable form all pages in the following way:
var username = Session["Username"].ToString();
Hope this helps

You can access your current session variables using the Session object with an index, like
var myvalue = Session["mysessionvariable"];

Use session["username"] to get the value. Then use this value as per your need

You can add a property in a base class (which is inherited from Page class) which will encapsulate the Session variable and inherit that base class in every page you create
public string UserNameInSession
{
get
{
return HttpContextCurrent["UserNameSessionKey"].ToString();
}
set
{
HttpContextCurrent["UserNameSessionKey"] = value;
}
}
And then you can use this property either to set or get the Username from/to session like
string UserName = UserNameInSession; //Get it
UserNameInSession = string.Empty();//set it

Related

Setting unique Session variables at Application level

I have a Web Forms application that does not have a login page. Technically a user can access any page directly. However, I need to be able to identify who the logged-in user is on each page. I don't want to add code to each page. I would rather set a unique session variable at the start of the session. For this I added into my Global.asax.cs the following:
protected void Session_Start(object sender, EventArgs e)
{
if (Session["LoggedInUser"] == null)
{
string networkId = HttpContext.Current.User.Identity.Name;
using (UnitOfWork unit = new UnitOfWork())
{
if (networkId.IndexOf("HLM\\") > -1) { networkId = networkId.Substring(4, networkId.Length - 4); }
loggedInUser = unit.PersonRepository.GetByNetworkID(networkId);
Session["LoggedInUser"] = loggedInUser;
}
}
else
{
loggedInUser = (Person)Session["LoggedInUser"];
}
}
I now see that it sets the loggedInUser to whatever user last created a session. Meaning, if Mike goes to the site he will see data that represents him as the loggedInUser. However, if Kate goes to the site after him, Mike will now see Kate's data. Basically, the last one in overwrites everyone's settings and Session_Start is overwriting the value for loggedInUser for all active Sessions.
Based on this link: https://books.google.com/books?id=nQkyi4i0te0C&pg=PA202&lpg=PA202&dq=C%23+set+unique+session+variable+in+global.asax&source=bl&ots=GV9nlEUzE5&sig=E4TT3NDbjp1GwEehgU3pLXKdvr0&hl=en&sa=X&ved=0ahUKEwiU9f322tvSAhVF7yYKHYaXCtwQ6AEITzAI#v=onepage&q=C%23%20set%20unique%20session%20variable%20in%20global.asax&f=false
It reads that I should be able to set unique session variables for each new session but my results don't show that.
Am I misunderstanding how this works? I need to set a unique session value at the beginning of each session for each user.
I found the issue. The Session_Start is doing what is supposed to at a unique session level. The way I was referencing the session value was all wrong. Instead of accessing the session value I was actually doing:
Person loggedInUser = Global.loggedInUser;
Which makes sense that it was returning the latest user to start a session.

Access same object value in another location

I have a simple C# login system (Winform application). I have a separated class (ActiveUser) to store user details when they're logging in.
In ActiveUser class, I have a variable called loggedInUserID.
So, when the user logs in, on the login form, I set a value to that variable.
ActiveUser obj = new ActiveUser();
obj.setLoggedUserID(UserID);
Now I have a CheckLoggedIn() method in each form that checks whether the user is logged in or not. So, that I can block users from accessing unauthorized pages.
So, how to check that ? If I did like this, it's just another object.
CheckLoggedIn(){
ActiveUser obj = new ActiveUser();
if(obj.getLoggedUserID() != 0){
MessageBox.Show("Logged In");
}
}
So, how to check the object value I create when the user logging in ?
I think the Singleton Pattern is the most suitable in this situation.
Let's make ActiveUser a simple singleton class.
In the ActiveUser class, add something like this:
public static readonly ActiveUser User = new ActiveUser();
To SetLoggedUserID, just do:
ActiveUser.User.SetLoggedUser(...);
And you can check it like this:
void CheckLoggedIn(){
if(ActiveUser.User.getLoggedUserID() != 0){
MessageBox.Show("Logged In");
}
}
To avoid accidentally creating a new instance of ActiveUser, I recommend you to make the constructor private:
private ActiveUser() { ... }

c# class in a session state?

My senior project is building a reservation system in ASP.NET/C#. Part of my senior project is to have c# classes (and basically use everything ive learned in the past few years). One thing Im trying to do is after I instantiate a new "user" class I need it to travel between the pages. I know session states holds variables, so I figured a session state would work where I can simply type "Session["blah"]." and have access to its members. But I dont see that happening. I realize session states are HTTP context, so i doubted it would work anyway. But is there any other way in which I can accomplish what I need without instantiating a new user class every time? I know its a webpage...but im also trying to make it as much as a functional online program as I can.
Just for coder's sake, heres the code snippet im working with:
cDatabaseManager cDM = new cDatabaseManager();
string forDBPass = Encryptdata(pass_txt.Text.ToString());
string fullName = fname_txt.Text.ToString() + " " + lname_txt.Text.ToString();
cDM.regStudent(email_txt.Text.ToString(), forDBPass, fullName, num_txt.Text.ToString(), carrier_ddl.SelectedValue.ToString(), this);
//ADD - getting a cStudent
cUser studentUser = new cStudent(fullName, forDBPass, email_txt.Text.ToString());
//ADD - session states
Session["cStudent"] = studentUser;
//Session["cStudent"]. //session state will not work with what I am doing
//ADD - transfer to campus diagram
Thanks in advance!!
EDIT:
I want to thank all of you who posted and commented! Ive learned alot from this short discussion. All your answers helped me understand!
From your comment:
The issue is when I type "Session["cStudent"]." I don't have access to my functions. Example: Session["cStudent"].getName() does not give my functionality.
This is because the [] indexer for Session sets/returns objects. The compiler does not know that you stored a cUser object and so you can't access the properties directly without a cast:
string name = ((cUser)Session["cStudent"]).getName();
There are two things that could go wrong here:
If Session["cStudent"] is null you will get a NullReferenceException
If Session["cStudent"] is not really a cUser you will get an InvalidCastException
You should check these conditions and react appropriately if one of them is true.
Also, as others have pointed out, the cUser class needs to be marked as Serializable in order to be stored in Session state.
Session stores item as objects. As long as your class inherits from Object (which it does) you can store it there. Quick caveat, it stores that object using Serialization, so your class must be serializable.
Add a property to your class like so:
public cStudent CurrentStudent
{
get {
if(Session["CurrentUser"] == null)
return null;
return (cStudent)Session["CurrentUser"];
}
set {
Session["CurrentUser"] = value;
}
}
When retrieving an object value from session state cast it to appropriate type.
[Serializable]
public class student
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
In Page1:
student s1 = new student();
s1.FirstName ="James";
s1.LastName = "Bond";
Session["blah"] = s1;
And when you want to access Session["blah"] in page 2
student s2 = (Session["blah"] !=null ? (student)Session["blah"] : null);
Now you can access properties of s2 as s2.FirstName, s2.LastName

session variable not recognizable

string Landcode = Session("landcode");
gives a fault message:
Error 2 The name 'Session' does not exist in the current context
I see the word session in the intellisense. And the session variable is declared in the global.asax.
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
string landcode = Request["strLandCode"];
}
`
Where are you trying to access the Session object from?
The code for getting the Session value would be (you would also want to check it is not null before calling .ToString():
string landcode = Session["landcode"].ToString();
The Request object and Session object are not the same object too. You would have to do the following to add landcode to the Session:
Session["landcode"] = strLandCode;
Use HttpContext.Current.Session["landcode"]
Session is some kind of dictionary and so you index into it with [] rather than use a method call ie ()
And in C# you also have to cast each object so when getting string object precede with (string), when getting an int precede with (int) etc...
This is How to use session in ASP.NET and C#
//This how to add value in session "ID" Is the name of the session and "1" is the value
Session.Add("ID", 1);
//How to retrieve the value which is in the Session
int ID = Convert.ToInt16(Session["ID"]);
//write session Value
Response.Write(ID.ToString());
Please Try it and tell us the result

How do I check for a URL's top-level domain in ASP.NET/C#?

Let's say "www.mysite.fr/home" is the URL ..Now how do I fetch "fr" out of this ? JUST "fr"
actually what I am trying to do is change masterpages at runtime after detecting a visitor's country..Yes I can use the countryCode variable which is there in some other class but thot may be I can do it like this only..just wanted to try..logic basically is:-
if(its "fr")
{
//apply masterpage 1
}
if(its "in")
{
//apply masterpage 2
}
Is it possible ? What will be the right way anyway ? Making that class that contains CountryCode variable as a utility class and using the variable from there in my new class
OR
fetch this value "fr" or "in" off the URL ?? How do I do this ? Is it possible?
if (Request.Url.Host.ToLower().EndsWith(".fr"))
{
...
}
There is no method to be used directly. Maybe you can write an extension yourself:
public static string GetDomainTypeName(this Uri uri)
{
if (!uri.HostNameType.Equals(UriHostNameType.Dns) || uri.IsLoopback)
return string.Empty; // or throw an exception
return uri.Host.Split('.').Last();
}
And be careful about the word case! WWW.GOOGLE.FR may make your code incorrect.
I think this should be possible. You can use regex to get the code (fr, in etc.) and change the master page but you'll have to do this before the page_load. By the time asp.net reaches page_load the master page is already set (if I remember correctly). You'll need to handle the PreInit event and set the master page you want to set. So basically do all the regex and master page changing in the PreInit event and you're good to go :)
Here's a description of PreInit (Source: http://msdn.microsoft.com/en-us/library/ms178472.aspx):
PreInit
Raised after the start stage is complete and before the initialization stage begins.
Use this event for the following:
•Check the IsPostBack property to determine whether this is the first time the page is being processed. The IsCallback and IsCrossPagePostBack properties have also been set at this time.
•Create or re-create dynamic controls.
•Set a master page dynamically.
•Set the Theme property dynamically.
•Read or set profile property values.
For the Current Scenario you can try with the following snippet:
string url = "www.mysite.fr/home";
int nStrLength = url.Length;
int nDot = url.LastIndexOf(".")+1;
int nRestStringLngth = nStrLength - nDot;
string baseDomain = url.Substring(nDot, nRestStringLngth);
int nSlash = baseDomain.IndexOf("/");
baseDomain = baseDomain.Substring(0, nSlash);
Console.WriteLine(baseDomain);
In france it work with EndsWith .fr but in England you have .co.uk or in austria you have .co.at and also .at
You can use the following nuget package. (Install-Package Nager.PublicSuffix)
https://www.nuget.org/packages/Nager.PublicSuffix/
Example:
var domainParser = new DomainParser();
var data = await domainParser.LoadDataAsync();
var tldRules = domainParser.ParseRules(data);
domainParser.AddRules(tldRules);
var domainName = domainParser.Get("sub.test.co.uk");
//domainName.Domain = "test";
//domainName.Hostname = "sub.test.co.uk";
//domainName.RegistrableDomain = "test.co.uk";
//domainName.SubDomain = "sub";
//domainName.TLD = "co.uk";

Categories

Resources