How to define a global variable in ASP.net web app - c#

I have face a requirement,
I want client access a data center but without use database , so I want my web app can retain a global or Application session variable, that contains the data, every client can access the same data... I am try to declare in golabl, but seem it only can store String but others ...
how to solve this problem ?
thanks.

Another option of defining a global variable is by creating a static class with a static property:
public static class GlobalVariables
{
public static string MyGlobalVariable { get; set; }
}
You can make this more complex if you are going to use this as a data store, but the same idea goes. Say, you have a dictionary to store your global data, you could do something like this:
public static class GlobalData
{
private static readonly object _syncRoot = new object();
private static Dictionary<string, int> _data;
public static int GetItemsByTag(string tag)
{
lock (_syncRoot)
{
if (_data == null)
_data = LoadItemsByTag();
return _data[tag];
}
}
private static Dictionary<string, int> LoadItemsByTag()
{
var result = new Dictionary<string, int>();
// Load the data from e.g. an XML file into the result object.
return result;
}
}

To Share the data with all application users, you can use ASP.NET Application object. Given is the sample code to access Application object in ASP.NET:
Hashtable htblGlobalValues = null;
if (Application["GlobalValueKey"] != null)
{
htblGlobalValues = Application["GlobalValueKey"] as Hashtable;
}
else
{
htblGlobalValues = new Hashtable();
}
htblGlobalValues.Add("Key1", "Value1");
htblGlobalValues.Add("Key2", "Value2");
this.Application["GlobalValueKey"] = htblGlobalValues;
Application["GlobalValueKey"] can be used anywhere in the whole application by any user. It will be common to all application users.

You can stuff data into the Application object if you want. It isn't persistent across application instances, but that may sufficient.
(I'm not for a minute going to suggest this is a best practice, but without a clearer picture of the requirements, that's all I can suggest.)
http://msdn.microsoft.com/en-us/library/system.web.ui.page.application.aspx
http://msdn.microsoft.com/en-us/library/system.web.httpapplication.aspx

If you are using WebApplication or MVC just go to Global.asax (in WebSite project you need to add Global.asax from the add new item menu).
I will explain to deploy two global variables for your web application:
Open the Global.asax file, then define your variable in Application_Start function as following:
void Application_Start(object sender, EventArgs e)
{
Application.Lock();
Application["variable1"] = "Some Value for variable1";
Application["variable2"] = "Some Value for variable2";
Application.UnLock();
}
If you want to use that those global variables in aspx pages just need to call them like this:
<p>I want to call variable1 <%=Application["variable1"].ToString() %></p>
<p>I want to call variable1 <%=Application["variable2"].ToString() %></p>
But if you want to use that those global variables in server-side call'em like this:
protected void Page_Load(object sender, EventArgs e)
{
string str1 = Application["variable1"].ToString();
string str2 = Application["variable2"].ToString();
}
Note: You must be aware that these global variables are public to all users and aren't suitable for authentication jobs.

You can also use Cache, which has advantages like ability to set expire time/date.

Related

adding value to a list via session in C#

in my page1.aspx.cs I have this
resultsHtml.Append("<a class='btn btn-warning' href='report.aspx?asset=" + rd["n_asset_id"].ToString() + "'><i class='fa fa-paw'></i></a> ");
so in my report.aspx I will catch the value.
Session["passThis"] = Request.QueryString["asset"];
However in my action.cs I created a class that will store the list. I'm thinking of adding a session there but everytime i will the store() it will just create another List.
public static void store() {
List<string> ast = new List<string>();
}
How can I achieve this feat? I'm running out of ideas.
I think that the best approach would be to extract assets list into property (so you can easily access it from other parts of code. In property getter, code checks if there's list in session.
In Store method you're accessing List of assets (List<string) and, if there is asset parameter in current Request, adds it to your list of assets. Notice that accessing Session is done through HttpContext.Current.Session because of static metod/property.
public static void Store()
{
string assetValue = HttpContext.Current.Request["asset"];
if (!string.IsNullOrEmpty(assetValue))
AssestsList.Add(assetValue);
}
public static List<string> AssestsList
{
get
{
if (HttpContext.Current.Session["assets"] == null)
{
HttpContext.Current.Session["assets"] = new List<string>();
}
return HttpContext.Current.Session["assets"] as List<string>;
}
set
{
HttpContext.Current.Session["assets"] = value;
}
}
so, to use this, just call Store() from your code.
If you have some questions, feel free to ask.

How can I store static class objects for recall on any page?

I want to store static values in a class for later use use on any page in the web. The values will be the same for all users.
Page_Init: Retrieve global variables from their respective sources and assign them to their static objects inside the classes within the GlobalStaticVariables class.
I call to set the static values from the MasterPage like so
protected void Page_Init(object sender, EventArgs e)
{
Web.StartUp.SetGlobalStaticVariables(this.Page);
}
///Removed most objects for the sake of brevity
public static Info.GlobalStaticVariables SetGlobalStaticVariables(object _this)
{
Info.GlobalStaticVariables.Some_StringValue = ConfigurationManager.AppSettings["Some_StringValue"].ToString();
Info.GlobalStaticVariables.Database.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
Info.GlobalStaticVariables.IIS.DomainName = ((Page)_this).Request.Url.Host;
}
///Removed most objects for the sake of brevity
public class Info
{
public class GlobalStaticVariables
{
public static string Some_StringValue { get; set; }
public class Database
{
public static string ConnectionString { get; set; }
}
public class Ldap
{
public static List<string> ServerList { get; set; }
}
}
}
I thought that I should first see if the Session object exists, then create if it doesn't as I have read that sometimes static values can be lost due to appPool recycle, etc.
I figured I should do this from the MasterPage since I have to reference "Session" but I don't know how I would pass the Page object to a property in a class file.
I use the following in the MasterPage to store the current user so I thought that I could do a similar thing with global variables. So far I have been unsuccessful.
public MyClass.Users.CurrentUser GetSetCurrentUser
{
get
{
if (Session["CurrentUser"] == null) GetSetCurrentUser = new MyClass.Users.CurrentUser();
return (MyClass.Users.CurrentUser)Session["CurrentUser"];
}
set { Session.Add("CurrentUser", value); }
}
With the previous though, I also have to add the following to each page that wants to reference the GetSetCurrentUser property (Master.GetSetCurrentUser ), but I would prefer to avoid this if possible.
<%# MasterType VirtualPath="~/mp.Master" %>
Unfortunately when I tried the same with GlobalStaticVariables no intellisense appeared aside from .Equals, .GetHashCode, .GetType and .ToString.
I want to be able to call the property GlobalStaticVariables from any page for easy access to it's static values.
Perhaps my thought process is flawed in attempting to do it this way, but I can't think of another way. Perhaps I needs to step away from this for awhile and enjoy the holiday, but I can't, I'm on a mission. :-)
Thank-you for you time and suggestions.
You're looking for HttpApplicationState that is available in your page by Context property which holds an Application property.
How you can use it:
void Page_Load(object sender, EventArgs e)
{
var last = Context.Application["lastActivity"];
lblLastActivity.Text = last == null?"(none)": ((DateTime) last).ToString();
Context.Application["lastActivity"] = DateTime.Now;
}
One other option is the use of Cache which works similar but objects stored in the Cache can get removed from the cache (to free memory). You should be able to reload the objects in that case though.

c# stateserver maintains session between machines

I am sure that I have made some painfully obvious blunder(s) that I just cannot see. I am hoping one of you can set me straight.
I my session management is working perfectly except that if a user on one machine enters data, a user who starts a session on another machine will also retreive the session information from the first. Not so good. :(
I call my sessions like this:
UserInfo userinfo = UserInfo.Session;
My session mgt class uses this:
static UserInfo userInfo;
static public UserInfo Session
{
get
{
if (userInfo == null)
{
userInfo = new UserInfo();
userInfo.ResetSessionTime();
}
return userInfo;
}
}
I read and write the data like this. I realize that I could serialize the entire class, but it seems like a lot more overhead to serialize and deserialize an entire class each time the class is called as opposed to just grabbing the one or two items I need.
Decimal _latitude;
private String SessionValue(String sKey, String sValue, String sNewValue)
{
String sRetVal = "";
if (sNewValue == null)//not wanting to update anything
{
if (sValue == null)//there is no existing value
{
sRetVal = (String)System.Web.HttpContext.Current.Session[sKey];
}
else
{
sRetVal = sValue;
}
}
else
{
System.Web.HttpContext.Current.Session[sKey] = sNewValue;
sRetVal = sNewValue;
}
return sRetVal;
}
public Decimal Latitude
{
get { return SessionValue("Latitude", _latitude); }
set { _latitude = SessionValue("Latitude", _latitude, value); }
}
Thanks for your help
1) You're using statics for your UserInfo, which means that a single instance of this class is shared among all requests coming to your web server.
2) You're not only storing values in the session (which isn't shared among users) but also in an instance variable, which in this case WILL be shared among users.
So the value of _latitude is causing you this issue. A simple solution is this:
public class Userinfo
{
public Decimal Latitude
{
get { return System.Web.HttpContext.Current.Session["Latitude"]; }
set { System.Web.HttpContext.Current.Session["Latitude"] = value; }
}
}
A better, more testable version would be:
public class UserInfo
{
private HttpSessionStateWrapper _session;
public UserInfo(HttpSessionStateWrapper session)
(
// throw if null etc
_session = session;
)
public Decimal Latitude
{
get { return _session["Latitude"]; }
set { _session["Latitude"] = value; }
}
}
In the second instance, within a request you just construct a new instance of the HttpSessionStateWrapper (using the current Session) and pass it to the UserInfo instance. When you test, you can just pass in a mock Wrapper.
No matter what, the UserInfo instance shouldn't be shared among sessions and it should write and read directly from the Session. Don't try to prematurely optimize things by keeping local versions of your session values. You aren't saving any time and you're just opening yourself up to bugs.
This happens because you store your user info in a static field. Static instances are shared between all requests, and lives the entire lifetime of your application.
In other words, all your users will get the same UserInfo instance from UserInfo.Session.
To fix this you could:
Serialize the whole class into session. I don't know which other properties you have, but I would guess it would not be too much of an overhead.
Create an instance of UserInfo per request, so that the user always reads from a new instance, which in turn will refresh it's values from Session.

ResourceProviderFactory periodic refreshing

I've created a custom resource provider which returns strings from our database to use for whatever.
The issue is I haven't found a way to "bust" the cache on these items and reload them from the database. Ideally I'd do this every x minutes or manually when we update the cache and want to reload it.
Technically, that's easy. I'm storing everything in a hashtable so just nuke that and reload when needed. However since the ResourceProviderFactory handles the loading of each resource class and I'm not sure how to enumerate the classes it has created.
An overview of the code:
public class ResourceProvider : IResourceProvider
{
private Dictionary<string, Dictionary<string, object>> _resourceCache
= new Dictionary<string, Dictionary<string, object>>();
private string _virtualPath;
private string _className;
public ResourceProvider(string virtualPath, string className)
{
_virtualPath = virtualPath;
_className = className;
}
public object GetObject(string resourceKey, CultureInfo culture)
{
...
}
}
public class ResourceProviderFactory :System.Web.Compilation.ResourceProviderFactory
{
public override IResourceProvider CreateGlobalResourceProvider(string classKey)
{
return new Cannla.Business.Resource.ResourceProvider(string.Empty, classKey);
}
...
...
}
What I was planning to do was add a reference every time CreateGlobalResourceProvider is called (e.g. add the new object to a collection and then enumerate that and nuke everything inside that object when I need to) but I'm unsure if this is going to do something weird to the ResourceProviderFactory.
Is there any ResourceProviderFactory IEnumerable method or something that will give me all those objects in a easy way before I go building all this code?
If you can use ASP.Net cache system
Just use it. You can access it using HttpRuntime.Cache and add timed invalidation check the example below:
var Key = "Resources:" + ResourceType + ResourceKey + Cutlure.Name;
HttpRuntime.Cache.Insert(Key, ValueToCache,
null, DateTime.Now.AddMinutes(1d),
System.Web.Caching.Cache.NoSlidingExpiration);
If you can't use ASP.Net cache system
You can put the logic that triggers cache invalidation inside of IResourceProvider.
ie. just check in GetObject if the cache expired.

How to access session variables from any class in ASP.NET?

I have created a class file in the App_Code folder in my application. I have a session variable
Session["loginId"]
I want to access this session variables in my class, but when I am writing the following line then it gives error
Session["loginId"]
Can anyone tell me how to access session variables within a class which is created in app_code folder in ASP.NET 2.0 (C#)
(Updated for completeness)
You can access session variables from any page or control using Session["loginId"] and from any class (e.g. from inside a class library), using System.Web.HttpContext.Current.Session["loginId"].
But please read on for my original answer...
I always use a wrapper class around the ASP.NET session to simplify access to session variables:
public class MySession
{
// private constructor
private MySession()
{
Property1 = "default value";
}
// Gets the current session.
public static MySession Current
{
get
{
MySession session =
(MySession)HttpContext.Current.Session["__MySession__"];
if (session == null)
{
session = new MySession();
HttpContext.Current.Session["__MySession__"] = session;
}
return session;
}
}
// **** add your session properties here, e.g like this:
public string Property1 { get; set; }
public DateTime MyDate { get; set; }
public int LoginId { get; set; }
}
This class stores one instance of itself in the ASP.NET session and allows you to access your session properties in a type-safe way from any class, e.g like this:
int loginId = MySession.Current.LoginId;
string property1 = MySession.Current.Property1;
MySession.Current.Property1 = newValue;
DateTime myDate = MySession.Current.MyDate;
MySession.Current.MyDate = DateTime.Now;
This approach has several advantages:
it saves you from a lot of type-casting
you don't have to use hard-coded session keys throughout your application (e.g. Session["loginId"]
you can document your session items by adding XML doc comments on the properties of MySession
you can initialize your session variables with default values (e.g. assuring they are not null)
Access the Session via the thread's HttpContext:-
HttpContext.Current.Session["loginId"]
The problem with the solution suggested is that it can break some performance features built into the SessionState if you are using an out-of-process session storage. (either "State Server Mode" or "SQL Server Mode"). In oop modes the session data needs to be serialized at the end of the page request and deserialized at the beginning of the page request, which can be costly. To improve the performance the SessionState attempts to only deserialize what is needed by only deserialize variable when it is accessed the first time, and it only re-serializes and replaces variable which were changed. If you have alot of session variable and shove them all into one class essentially everything in your session will be deserialized on every page request that uses session and everything will need to be serialized again even if only 1 property changed becuase the class changed. Just something to consider if your using alot of session and an oop mode.
The answers presented before mine provide apt solutions to the problem, however, I feel that it is important to understand why this error results:
The Session property of the Page returns an instance of type HttpSessionState relative to that particular request. Page.Session is actually equivalent to calling Page.Context.Session.
MSDN explains how this is possible:
Because ASP.NET pages contain a default reference to the System.Web namespace (which contains the HttpContext class), you can reference the members of HttpContext on an .aspx page without the fully qualified class reference to HttpContext.
However, When you try to access this property within a class in App_Code, the property will not be available to you unless your class derives from the Page Class.
My solution to this oft-encountered scenario is that I never pass page objects to classes. I would rather extract the required objects from the page Session and pass them to the Class in the form of a name-value collection / Array / List, depending on the case.
In asp.net core this works differerently:
public class SomeOtherClass
{
private readonly IHttpContextAccessor _httpContextAccessor;
private ISession _session => _httpContextAccessor.HttpContext.Session;
public SomeOtherClass(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public void TestSet()
{
_session.SetString("Test", "Ben Rules!");
}
public void TestGet()
{
var message = _session.GetString("Test");
}
}
Source: https://benjii.me/2016/07/using-sessions-and-httpcontext-in-aspnetcore-and-mvc-core/
I had the same error, because I was trying to manipulate session variables inside a custom Session class.
I had to pass the current context (system.web.httpcontext.current) into the class, and then everything worked out fine.
MA
This should be more efficient both for the application and also for the developer.
Add the following class to your web project:
/// <summary>
/// This holds all of the session variables for the site.
/// </summary>
public class SessionCentralized
{
protected internal static void Save<T>(string sessionName, T value)
{
HttpContext.Current.Session[sessionName] = value;
}
protected internal static T Get<T>(string sessionName)
{
return (T)HttpContext.Current.Session[sessionName];
}
public static int? WhatEverSessionVariableYouWantToHold
{
get
{
return Get<int?>(nameof(WhatEverSessionVariableYouWantToHold));
}
set
{
Save(nameof(WhatEverSessionVariableYouWantToHold), value);
}
}
}
Here is the implementation:
SessionCentralized.WhatEverSessionVariableYouWantToHold = id;

Categories

Resources