session does not appear in the label - c#

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.

Related

How do I read and write to the local storage in Blazor server side using Blazored?

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.

One time validation of user input to run application

I've made a WinForms application in C#.NET.
On first run I'm checking if 2 strings are equal, if its TRUE then the main form appears. However currently, this check is done whenever I start the program.
How can I pass this "validation result" to the computer so that every next run of the application, there will be no more checks needed?
One option is to store validation data in the registry. If the lines are equal, then create a branch in the registry and write the necessary data into it. Next, at the next start, we check for the presence of a branch and data in it. I attach a quick example.
string FisrtString = "Temp";
string SecondString = "Temp";
string SubBaseKeyString = #"SOFTWARE\ApplicationName";
RegistryKey vmsBaseKey = Registry.CurrentUser.OpenSubKey(SubBaseKeyString, true);
if (vmsBaseKey != null)
{
var Value = vmsBaseKey.GetValue("Validate");
if (Value != null)
{
if (Value.ToString() == "1")
{
//The user check passed here, you can open the window
}
}
else
{
//Here you must specify the action if the key is missing. Additional string comparison possible
}
}
else
{
if (FisrtString == SecondString)
{
//If the first line is equal to the second line, then assign a value
//The user check passed here, you can open the window
RegistryKey KEY_CREATE = Registry.CurrentUser.CreateSubKey(SubBaseKeyString);
KEY_CREATE.SetValue("Validate", "1");
KEY_CREATE.Close();
}
else
{
//If the first line is not equal to the second line, then we perform the desired action
}
}
You could save the result of your check into a config file and read it next time your program starts from the config file

retrieving session variable from another controller

Is is possible to retrieve a Session variable from a different controller it was created from?
I create this in my Account controller
System.Web.HttpContext.Current.Session["Session"] = sessionGuid;
and from a different controller I'm trying
if (System.Web.HttpContext.Current.Session["Session"] != null)
{
return Json(System.Web.HttpContext.Current.Session["Session"].ToString());
}
return null;
which always returns null.
as a Test I added some code to my Login controller and in that part i do get the value out of it
if (System.Web.HttpContext.Current.Session["Session"] != null)
{
test = System.Web.HttpContext.Current.Session["Session"].ToString();
}
else
{
test = "no";
}
i always got the actual result, not the"no" part of the code
For some reason its different into how i have to access the session, at the other controller i changed to this code and it worked
if (HttpContext.Session["Session"] != null)
{
return Json(HttpContext.Session["Session"].ToString());
}
return null;
if controller is within the same website/virtual directory then YES, however if you are saying your session was created in a different site and you trying to access it within a controller which belongs to different site then you cannot.

Tracking the beginning of a new Session in C#

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.

EventReceiver doesn't work correctly

I've got an EventReceiver in my SharePoint application where I'm overriding ItemAdding and ItemUpdating methods:
public override void ItemAdding(SPItemEventProperties properties)
{
SPWeb web = properties.OpenWeb();
switch (properties.ListTitle)
{
//some cases
case "Employees":
if (properties.AfterProperties["User"] != null)
{
SPUser user = web.SiteUsers
[
properties.AfterProperties["User"].ToString().Substring
(
properties.AfterProperties["User"].ToString().IndexOf(";#") + 2
)
];
properties.AfterProperties["Title"] = user.Name;
}
break;
}
base.ItemAdding(properties);
}
Code in both methods is exactly the same. But sometimes Title field remains empty after adding an item to list. And if I update that item (without any changes) Title field is filled by username correctly.
I see two potential issues in your code:
processing properties.AfterProperties["User"] by parsing it. It would be better to use code like this (SPUserFieldValue)properties.ListItem.Fields["User"].GetFieldValue(properties.properties.AfterProperties["User"].ToString()). This way suggested by MSDN.
Using SiteUsers indexer throws Exception when user is not found in the collection. You should wrap it by try ... catch statement. It can happen when user is used for the first time in your site collection.

Categories