Hi I am trying to develop a functionality that will track everytime there is a new session created in a web app aka a user logs in.
I have created a class called "StateBag.cs"
using System;
using System.Text;
[Serializable()]
public class StateBag
{
#region Business Methods
// To catch the event of a New Session //
private bool _NewSession = false;
public bool NewSession
{
get { return _NewSession; }
set { _NewSession = value; }
}
#endregion
}
On the login page, just before login:-
// Declaration Region. //
private StateBag _Bag;
if (Session.IsNewSession)
{
_Bag = new StateBag();
_Bag.NewSession = true;
// ViewState["StateBag"] = _Bag;
Session["NewSession"] = _Bag;
}
On the Main page, after a successful login:-
// Declaration region. //
StateBag _Bag
{
get
{
return (StateBag)Session["NewSession"];
}
}
if (_Bag.NewSession == true)
{
// Do my stuff........ //
_Bag.NewSession = false; // set new Session back to false//
}
I m having problems retrieving _Bag... it comes back as Null...
hence an error message :-
"Object reference not set to an instance of an object."
Can anyone help me retrieve the NewSession property which I set to "True" on the login page?
You're storing it in ViewState:
ViewState["StateBag"] = _Bag;
And retrieving it from Session:
return (StateBag)Session["NewSession"];
ViewState and Session are two completely different things, they don't share the same objects. You need to pick one place to persist the data and always retrieve it from that same place.
Note: ViewState renders data to the client, so I wouldn't suggest using that to store anything that you don't want a client to be able to see/modify.
Related
Working on a Blazor server side project. I am using Blazored Local Storage for this: https://github.com/Blazored/LocalStorage
I have a dropdown, when a value is selected I want to store the value in local storage so that when the user returns to the page later the dropdown will be at the same value.
To accomplish this I bound the dropdown to the value _store and added a getter and setter. This part works:
private int _store {
get { return GetStoreValue(); }
set { SetStoreValue(value); }
}
Where it falls apart is the two functions for getting and setting:
private int GetStoreValue()
{
var returnValue = 0;
string storedValue = _storage.GetItemAsync<string>("UserListSelectedStore").ToString();
if (!string.IsNullOrEmpty(storedValue))
{
int storedValueInt = Int32.Parse(storedValue);
if (storedValueInt > 0)
{
returnValue = storedValueInt;
}
else
{
returnValue = _storeValue;
}
}
else
{
returnValue = _storeValue;
}
return returnValue;
}
private void SetStoreValue(int value)
{
_storage.SetItemAsStringAsync("UserListSelectedStore", value.ToString());
_storeValue = value;
}
Essentially, if there is a stored store value, use that. Otherwise return whatever was set when the component was initialized.
The problem - The value of storedValue is always an empty string "". It appears to write the value to storage correctly, but has problems reading it. Since this is a server side project, I have to use async for reading, I am not sure if that is the issue but I tried blindly changing it a few times and couldn't get it to work.
How do I get Blazor to read the stored value and return it if it exists?
Figured it out. I needed to add it to the OnInitializedAsync() method so everything gets set before the DOM loads.
In my controller, the method that returns the View also initializes a few values for some class-level properties:
private string igc = String.Empty;
private string igcCode = String.Empty;
private bool isSuggested = false;
public ActionResult Codes(Codes objCodes)
{
try
{
FillDropDowns(objCodes);
igc = String.Empty;
if (objICDCodes.FromWhere.IndexOf("MedicalInfo-Suggested") >= 0)
{
igc = objCodes.FromWhere.Remove(0, "MedicalInfo-Suggested-".Length);
igcCode = igc.Substring(0, igc.IndexOf("-")).Trim();
objCodes.ICGCode = igcCode;
isSuggested = true;
}
}
catch (Exception ex)
{
//logging error
ElmahLogUtility.ErrorException(ex);
}
return View(base.GetViewPath("Codes"), objCodes);
}
Additionally, there is this method which gets called to bind data to a grid on the page:
public JsonResult GetSelectedCodesInfo(List<SearchField> searchFields, GridDataSourceRequest request)
{
//creating the instance of DataSourceResult.
DataSourceResult dataSourceResult = null;
try
{
// Creating the instance of CommonBLL to load the values.
CommonBLL objCommonBLL = new CommonBLL();
if (isSuggested)
{
searchFields.Add(new SearchField() { ElementName = "aIGCode", Value = igcCode });
searchFields.Add(new SearchField() { ElementName = "aFor", Value = "EtiologicDiagnosis" });
}
// Getting the Codes information and storing in the DataSource Result.
dataSourceResult = objCommonBLL.GetSelectedCodesInfo(searchFields, request);
}
catch (Exception ex)
{
//Logging the Exception
ElmahLogUtility.ErrorException(ex);
}
// Returning the Result.
return Json(dataSourceResult, JsonRequestBehavior.AllowGet);
}
isSuggested gets set to true when the View is created, but when the data is bound to the grid isSuggested is set to false for some reason.
My grid is defined in a Razor view like so:
#Html.Grid("CodesSelectionGrid").ReadSource("Controller", "GetSelectedCodesInfo").OnGridDataBound("AssignCodeValues").Lazyload(true).EnableGrouping(false).EnableSorting(true).PageSize(10).Height("390px").Width("610px").EnablePaging(true).EnableFiltering(false).EnableMultiSelect(true).SelectionMode(SelectionMode.Single, "GetSelectedCodeDetails").RowSelection(GridRowSelection.None).ShowToolBar(true).SelectionCSSClass("icd-editable-cell").PageButtonCount(3)
That .ReadSource("Controller", "GetSelectedCodesInfo") bit is what refers to the Controller and the method on the controller to call. So, it's calling the second snippet of code above.
I must be accessing two separate instances of my Controller class, but I do not know how to solve this problem. How can I do this? How could I have my grid pass a reference of the Codes object? Then I could just get the values from there for the grid...
This is the expected behavior. isSuggested is a class level variable. Every time you make an Http request, a new instance of your controller will be created. That means the variable will be initialized to false. Remember, Http is Stateless :)
If you want to persist a variable value between multiple http calls, you need to persist it. You have different options like
Persist to a database table and read from that in the second call
Write to a file in disk and read from that in the second call
Save to user session and read from that in the second call
I created session to move data between pages using c# asp.net but the result does not appear and the program does not give me error in the code
first page code:
Session["New1"] = desc1.Text;
to send data to Label in Second page
code:
var userType = (string)Session["New1"];
if (userType != null)
{
Label1.Text = userType.ToString() ;
}
else
{
// test "2" etc
}
Try this,
if (Session["New1"]!= null)
{
Label1.Text = Session["New1"].ToString() ;
}
else
{
// test "2" etc
}
Try explicitly checking of your Session variable exists before attempting to use it to avoid any null-reference issues :
// Explicitly check that it exists
if (Session["New1"] != null)
{
// Then grab it (if it is a non-string type, then you can use as to cast it
// (e.g. a List might use Session["List"] as List<Widget>;)
Label1.Text = Convert.ToString(Session["New1"]);
}
else
{
// Do something here
}
This assumes that your value will be set prior to this code getting called. Additionally, any hiccups to the web server (e.g. timeouts, restarts, major exceptions, etc.) will clear all of the values within the Session.
I want to access session in handler for that i am inheriting "IRequireSessionState" Class. but while evaluating the session it is coming null, but on the web page it has value. i dont know why this is happening my code of handler is:
public void ProcessRequest(HttpContext context)
{
String Name = Common.GetSessionValue("UserId").ToString() ;
// my code.........
Here is my common method to Get Session's value
public static Guid GetSessionValue(string SessionName)
{
Guid returnvalue = Guid.Empty;
if (HttpContext.Current.Session[SessionName] != null)
{
returnvalue = new Guid(HttpContext.Current.Session[SessionName].ToString());
}
else
{
HttpContext.Current.Response.Redirect("Login.aspx");
}
return returnvalue;
}
Please help me. Thanks in advance
You can try this by Exposing the value to the outside world http://forums.asp.net/t/1506625.aspx/1 and then trying to fetch the value in handler using
context.Request.Form["returnvalue"];
You can see the exposed value in firebug AddOn in Mozilla
I have a class that handles all of my session variables in my asp.net application. Moreover, I sometimes store objects in the session variables so as to allow me to code very similar to a normal .net application.
For example, here is an object in a session variable:
public cUser User
{
get { return (cUser)HttpContext.Current.Session["CurrentUser"]; }
set { HttpContext.Current.Session["CurrentUser"] = value; }
}
And here is the instance of MySessionClass:
public static MySessinClass Current
{
get
{
MySessionClass session = (MySessionClass)HttpContext.Current.Session["MySessionClass"];
if (session == null) {
session = new MySessionClass();
HttpContext.Current.Session["MySessionClass"] = session;
}
return session;
}
}
So, in my code behind aspx page, I would just do something such as
int userID = MySessionClass.Current.User.UserID;
This works great and I love it. However, I want to apply the same principle in javascript from my aspx page:
var userID = <%=MySessionClass.Current.User.UserID%>;
However, when I access that webpage, I get an error saying that it does not recognize the MySessionClass object.
So, given the context that I am in, what would be the best way to reference that UserID variable, from the object, from the session, in javascript? Maybe my syntax to reference it is off or I am going at it the wrong way. Any help would be appreciated, thank you.
Since you've defined it as a static member, you would need to qualify your reference with the page type:
var userID = <%=MyPageType.MySessionClass.Current.User.UserID%>;
That should be enough.