session variable not recognizable - c#

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

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.

Cache my static data in server for all user C#

I want to cache some static data in server. if any user request for same data cache should return that.
if i go with HttpContext.cache, it will vary by user. please help me how to do that in c#?
What I have tried:
HttpContext.Cache.Insert(cacheKey, Sonarresult, null, DateTime.Now.AddSeconds(Timeduration), Cache.NoSlidingExpiration);
i tried this but for all users will store into cache. i dont want that. first user only has to store it.
Using the application cache just like you would a session variable can do the trick for you.
e.g.
// get
string message = Application["somemessage"].ToString();
will be the same for all users.
to elaborate further, be careful where on your code you set the value for application variables because once they change, they will change for all.
// set
Application["somemessage"] = "your message";
Global.asax would be a could place to set the value of Application variables if they never change:
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
// here we set the value every time the application starts
Application["somemessage"] = "your message";
// the following line will get the SiteName from the web.config setting section
Application["SiteName"] = ConfigurationManager.AppSettings["SiteName"].ToString();
}
You can use application cache to do this.
void Application_Start ()
{
_cache = Context.Cache;
_cache.Insert ("mycahce", mystaticvariabledata, null,
Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration,
CacheItemPriority.Default,null);
}

What's the precise differences between the following three lines in a MVC controller inheriting from ServiceStackController

What's the precise differences between the following three lines in a MVC controller inheriting from ServiceStackController?
(I cannot find the difference explained in any documentation)
//A - (default: reload = true)
var session = GetSession();
//B
var session = GetSession(false);
//C
var session = SessionAs<IAuthSession>();
GetSession is better named GetOrCreateSession as it will either Get a Typed Session or create a new one if it doesn't exist. It also stores the instance of the Session in HTTP Request Context where if reload:false will return the local instance when it exists:
IAuthSession session = GetSession(reload:false);
IAuthSession session = GetSession(reload:true);
If reload:true it will always retrieve the Session from the underlying ICacheClient.
SessionAs<T> always gets the Session from the ICacheClient and returns an empty instance if it doesn't exist. It also returns a typed version of your Custom AuthUserSession:
CustomUserSession session = SessionAs<CustomUserSession>();

how to get the session variable in many pages in 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

Check Validity for a QueryString using Entity Framework

I use C# Asp.Net and EF 4.
I have a scenario like MasterPage and DetailsPage.
So from my MasterPage I pass a variable as a QeryString to the DetailsPage, the DetailsPage will show up details for a specifc item in my DataBase.
I need to check the validity for my QueryString, in details I need:
Check if is Null, Empty or White Spaces.
Check if is NOT of type INT (just numbers not any letters).
Check if the Object NOT exists in my DB.
In case if Check result True, I will redirect the User.
At the moment I wrote this script. It is works but I would like to know if you know a better approch/code to solve this.
Also I would like to know if make sense to have this logic on every time the page Load, or would be enought us just on !Page.IsPostBack.
Thanks once again for your support guys!
protected void Page_Load(object sender, EventArgs e)
{
#region Logic Check Query String.
// Query String is Null or Empty.
if (string.IsNullOrWhiteSpace(ImageIdFromUrl))
RedirectToPage();
// Query String is not valid Type of INT.
int ImageId;
bool isInt = Int32.TryParse(ImageIdFromUrl, out ImageId);
if (isInt)
{
// Check if a valid Object request exist in Data Source.
using (CmsConnectionStringEntityDataModel context = new CmsConnectionStringEntityDataModel())
{
if (!context.CmsImagesContents.Any(x => x.ImageContentId == ImageId))
{
RedirectToPage();
}
}
}
else
RedirectToPage();
#endregion
}
You don't need to check it on every postback, only on a full page load. The query string is not sent to the server on postbacks.
I suggest you move all the query string validation logic to separate functions.

Categories

Resources