How to set session value from class files - c#

I am using the below code to assign a session variable from class file. But i got the error message "Object reference not set to be an instance of object".
HttpContext.Current.Session.Add("UserSession", "dsafd");

The right way to achive your goal is (translated in c# with online tools take care to check () or []):
if ((Session("UserSession") == null))
{
//example with simple string
Session.Add("UserSession", "thisIsASimpletString");
//Exmple with an Object NOTE: the constructor new if is required or you may handling in exception like your
List<string> list = new List<string>();
Session.Add("UserSession", list);
}
else
{
//different case where session exist
Session("UserSession") = "thisIsASimpletString";
//case with object
List<string> list = new List<string>();
Session("UserSession") = list;
}
If this asnser match your goal mark as answer.
In case you talking about a class which set session value you need to pass context to your calss but is not a very good idea.Is better that you return a value from class to the session or persist the object(class) into the session too
in example( but not suggested and assume that you populated you name and surname properties) :
protected void Page_Load(object sender, EventArgs e)
{
MyObject _class = new MyObject(HttpContext.Current);
_class.SetNameAndSurname();
Response.Write(Session("UserInfo").ToString);
}
private class MyObject
{
public void SetNameAndSurname()
{
if ((this.Context.Session("UserInfo") == null)) {
this.Context.Session.Add("UserInfo", this.Surname + "-" + this.Name);
} else {
this.Context.Session("UserInfo") = this.Surname + "-" + this.Name;
}
}
private string _Name;
public string Name
{
get { return _Name; }
set { _Name = value; }
}
private string _Surname;
public string Surname
{
get { return _Surname; }
set { _Surname = value; }
}
private HttpContext _context;
public HttpContext Context
{
get { return _context; }
set { _context = value; }
}
public MyObject(HttpContext Context)
{
this._context = Context;
}
public MyObject()
{
}
}
And there's many other way to achieve same goals in example:SameClass with properties,methods:
protected void Load()
{
MyObject _class = new MyObject;
_class.surname="Surname";
_class.name="Name";
context.Session.add("UserInfo"),_class.name + "-" + _class.surname);
}
All depend from your class,methods,properties and logic.

Related

HttpSessionStateBase losing property values of inherited type

We are using HttpSessionStateBase to store messages in a set up similar to this working example:
public class HttpSessionMessageDisplayFetch : IMessageDisplayFetch
{
protected HttpSessionStateBase _session;
private IList<ICoreMessage> messages
{
get
{
if (_session[EchoCoreConstants.MESSAGE_KEY] == null)
_session[EchoCoreConstants.MESSAGE_KEY] = new List<ICoreMessage>();
return _session[EchoCoreConstants.MESSAGE_KEY] as IList<ICoreMessage>;
}
}
public HttpSessionMessageDisplayFetch()
{
if (HttpContext.Current != null)
_session = new HttpSessionStateWrapper(HttpContext.Current.Session);
}
public void AddMessage(ICoreMessage message)
{
if (message != null)
messages.Add(message);
}
public IEnumerable<IResultPresentation> FlushMessagesAsPresentations(IResultFormatter formatter)
{
var mToReturn = messages.Select(m => m.GetPresentation(formatter)).ToList();
messages.Clear();
return mToReturn;
}
}
When we pass in a QualityExplicitlySetMessage (which inherits from ICoreMessage, see below) it is saved correctly to messages.
This is how the object looks after being inserted into the messages list, at the end of AddMessage(ICoreMessage message) above.
But when we come to access it after changing controllers the inherited member's properties are null, which causes a variety of null reference exceptions.
This is how the object now looks after we call FlushMessagesAsPresentations. I've commented out var mToReturn... as this tries to access one of these null ref properties.
I'd like to ask the following:
Why is the HttpSessionStateBase failing to capture these values taken
by the inherited type?
Is this an issue in saving to the HttpSession or in retrieving?
Is this anything to do with, as I suspect, inheritance?
Or is the fact I'm potentially calling a new controller that dependency injects the HttpSessionMessageDisplayFetch causing an issue?
I'm a first-time poster so please let me know if I'm making any kind of faux pas - Super keen to learn! Any input is very welcome.
Some potentially useful code snippets:
QualityExplicitlySetMessage
public class QualityExplicitlySetMessage : QualityChangeMessage
{
public QualityExplicitlySetMessage(IQPossession before, IQPossession after, IQEffect qEffect)
: base(before, after, qEffect)
{
IsSetToExactly = true;
}
}
QualityChangeMessage - Working example
public abstract class QualityChangeMessage : CoreMessage, IQualityChangeMessage
{
protected PossessionChange Change;
public PossessionChange GetPossessionChange()
{
return Change;
}
protected QualityChangeMessage(IQPossession before, IQPossession after, IQEffect qEffect)
{
Change = new PossessionChange(before, after, qEffect);
StoreQualityInfo(qEffect.AssociatedQuality);
}
public override IResultPresentation GetPresentation(IResultFormatter formatter)
{
return formatter.GetQualityResult(this);
}
#region IQualityChangeMessage implementation
public int LevelBefore
{
get { return Change.Before.Level; }
}
//... And so on with values dependent on the Change property.
}
CoreMessage - Working example
public abstract class CoreMessage : ICoreMessage
{
public string MessageType
{
get { return GetType().ToString(); }
}
public string ImageTooltip
{
get { return _imagetooltip; }
set { _imagetooltip = value; }
}
public string Image
{
get { return _image; }
set { _image = value; }
}
public int? RelevantQualityId { get; set; }
protected void StoreQualityInfo(Quality q)
{
PyramidNumberIncreaseLimit = q.PyramidNumberIncreaseLimit;
RelevantQualityId = q.Id;
RelevantQualityName = q.Name;
ImageTooltip = "<strong>" + q.Name + "</strong><br/>" + q.Description + "<br>" +
q.EnhancementsDescription;
Image = q.Image;
}
public virtual IResultPresentation GetPresentation(IResultFormatter formatter)
{
return formatter.GetResult(this);
}
}
UserController - Working example.
public partial class UserController : Controller
{
private readonly IMessageDisplayFetch _messageDisplayFetch;
public UserController(IMessageDisplayFetch messageDisplayFetch)
{
_messageDisplayFetch = messageDisplayFetch;
}
public virtual ActionResult MessagesForStoryletWindow()
{
var activeChar = _us.CurrentCharacter();
IEnumerable<IResultPresentation> messages;
messages = _messageDisplayFetch.FlushMessagesAsPresentations(_storyFormatter);
var vd = new MessagesViewData(messages)
{
Character = new CharacterViewData(activeChar),
};
return View(Views.Messages, vd);
}
}

Debug and properties loading

I have an object that represents a record of a table in my database, for example 'Project'.
My User class has different properties which are the records of other tables, for example, 'Client' or 'Accountancy'. Those also have properties to related tables.
Each of these properties returns a local value (already loaded) if not null, and there is no loaded information, it generates a request to get this value from database.
My issue is the following : when I set a breakpoint, and check the object in the debug window, it loads automatically all the values of the properties, and so, requests the database.
With this scenario, I cannot have a precise and static snapshot of my object at the moment.
Is there a way, in code, not to go through this part of code if in debug window ?
For instance, something like that:
public MyBaseObject GetProperty<T>(string columnName_, string alias_ = null) where T : MyBaseObject, new()
{
var ret = GetExtract<T>(columnName_, alias_);
// if the data are loaded
if (ret.Id != null)
return ret;
// Fake boolean I would like
if(InDebugWindowAfterAbreakPointForInstance)
return ret;
else
ret = LoadFromDatabase<T>(columnName_, alias_)
return ret;
}
I've found different attributes with the debugger, like the DebuggerStepperBoundaryAttribute, but nothing that could do something like that.
In situations like this the only way I know of is to use a DebuggerTypeProxy for each of your types then in that proxy have it access the backing field directly instead of going through the property that causes the database lookup to happen.
Here is a simple example program.
public class Program
{
public static void Main(string[] args)
{
var client = new Client();
Debugger.Break();
Debugger.Break();
}
}
[DebuggerTypeProxy(typeof(ClientDebugView))]
public class Client : MyBaseObject
{
private string _firstName;
private string _lastName;
public string FirstName
{
get
{
if (_firstName == null)
_firstName = GetProperty<string>("FirstName");
return _firstName;
}
set
{
if (Equals(_firstName, value))
return;
_firstName = value;
UpdateDatabase(_firstName, "FirstName");
}
}
public string LastName
{
get
{
if (_lastName == null)
_lastName = GetProperty<string>("LastName");
return _lastName;
}
set
{
if (Equals(_lastName, value))
return;
_lastName = value;
UpdateDatabase(_lastName, "LastName");
}
}
internal class ClientDebugView : MyBaseObjectDebugView
{
private readonly Client _client;
public ClientDebugView(Client client)
: base(client)
{
_client = client;
}
public string FirstName
{
get { return _client._firstName; }
}
public string LastName
{
get { return _client._lastName; }
}
}
}
[DebuggerTypeProxy(typeof(MyBaseObjectDebugView))]
public class MyBaseObject
{
private Guid? _id;
public Guid? Id
{
get
{
if (_id == null)
_id = GetProperty<Guid?>("Id");
return _id;
}
set
{
if (Equals(_id, value))
return;
_id = value;
UpdateDatabase(_id, "Id");
}
}
//Fake loading data from a database.
protected T GetProperty<T>(string columnName)
{
object ret = null;
switch (columnName)
{
case "Id":
ret = Guid.NewGuid();
break;
case "LastName":
ret = "Smith";
break;
case "FirstName":
ret = "John";
break;
default:
ret = null;
break;
}
return (T)ret;
}
protected void UpdateDatabase<T>(T id, string s)
{
throw new NotImplementedException();
}
internal class MyBaseObjectDebugView
{
private readonly MyBaseObject _baseObject;
public MyBaseObjectDebugView(MyBaseObject baseObject)
{
_baseObject = baseObject;
}
public Guid? Id
{
get { return _baseObject._id; }
}
}
}
If you view the client object in the debugger you will see it leaves the backing fields null between the two breakpoints unless you open the "Raw View" at the first breakpoint.

How to add edges by unwind using neo4jclient?

The nodes have existed.
I tried to add edges by unwind,but my function importBuyConnectionIntoNeo4j didn't work,
Is there any one can help me?
the data structure:
class Connection
{
private string type;
public string Type
{
get { return type; }
set { type = value; }
}
private string source;
public string Source
{
get { return source; }
set { source = value; }
}
private string target;
public string Target
{
get { return target; }
set { target = value; }
}
}
class BuyConnection:Connection
{
}
myFunction:
public void importBuyConnectionIntoNeo4j(List<BuyConnection> connectionList)
{
GraphClient client = createConnectionToNeo4j();
client.Cypher
.Unwind(connectionList, "connection")
.Match("(source:Person),(target:Vegetable)")
.Where("source.Name=connection.Source AND target.Type=connection.Target")
.Create("(source)-[:Buy]->(target)")
.ExecuteWithoutResults();
}
I think the issue is with your .where text:
.Where("source.Name=connection.Source AND target.Type=connection.Target")
is the Source and Target the right way around?

Getting property values from a static class using reflection

I have a class that is used for storing user data to a file. It works well, but can't really be placed into a PCL library easily. Outside of the PCL, it's all fine.
The class looks like this
public static class UserData
{
public static object GetPropertyValue(this object data, string propertyName)
{
return data.GetType().GetProperties().Single(pi => pi.Name == propertyName).GetValue(data, null);
}
public static object SetPropertyValue<T>(this object data, string propertyName, T value)
{
data.GetType().GetProperties().Single(pi => pi.Name == propertyName).SetValue(data, value);
return new object();
}
private static string pUserSettingsFile;
private static UserSettings userSetting;
public static bool AccountEnabled
{
get
{
return UserSettings.account_enabled;
}
set
{
UserSettings settings = UserSettings;
settings.account_enabled = value;
UserSettings = settings;
}
}
public static UserSettings UserSettings
{
get
{
if (userSetting == null)
{
if (File.Exists(UserSettingsFile))
{
userSetting = Serializer.XmlDeserializeObject<UserSettings>(UserSettingsFile);
}
else
{
userSetting = new UserSettings();
Serializer.XmlSerializeObject(userSetting, UserSettingsFile);
}
}
return userSetting;
}
set
{
if (value == null)
{
throw new ArgumentNullException("value is null!");
}
userSetting = value;
if (File.Exists(UserSettingsFile))
{
File.Delete(UserSettingsFile);
}
Serializer.XmlSerializeObject(userSetting, UserSettingsFile);
}
}
public static string UserSettingsFile
{
get
{
if (string.IsNullOrEmpty(pUserSettingsFile))
{
pUserSettingsFile = Path.Combine(GroupShootDroid.Singleton.ContentDirectory, "UserSettings.xml");
}
return pUserSettingsFile;
}
}
#endregion
}
public class UserSettings
{
public bool account_enabled { get; set; }
public string address { get; set; }
public string country { get; set; }
}
It's not rocket science, but does what I need it to do.
What I'm trying to do is use the Get/SetPropertyValue methods to return or set any of the properties within the class.
Currently, to access the Get/SetPropertyValue methods I'm using this
public string GetStringValue(string valToGet)
{
string rv = (string)UserData.GetPropertyValue(valToGet);
return rv;
}
public void SetStringValue(string name, string val)
{
UserData.SetPropertyValue(name, val);
}
On compiling though, the GetPropertyValue method is giving an error that No overload for method GetPropertyValue takes 1 argument with the SetPropertyValue complaining that there isn't an overload that takes 2
I'm not sure that the code I'm using will do what I need it to do (from what I've read on here it should be), but I'm more perplexed as to why the errors are showing.
Is there a better way to do what I'm trying to do? The application is a Xam.Forms app, so the PCL accesses the class through an interface using injection.
You are defining extension method, you need an instance of the class to call them:
var o = new Object();
string rv = (string)o.GetPropertyValue(valToGet);
// or, but no sure
string rv = (string)UserData.GetPropertyValue(o, valToGet);
or more probably in your case:
public string GetStringValue(string valToGet)
{
string rv = (string)this.GetPropertyValue(this, valToGet);
//or
//string rv = (string)UserData.GetPropertyValue(this, valToGet);
return rv;
}
I think you're getting confused between the UserData class and the object class. Your extension methods extend object.

Using { get set } Accessors for Multiple Values in MVC

EDIT: Question Reconstructed.
OK, I have revisited my get and set methods, but I am still very unclear on how it all works.
What I want to achieve is the Model is populated by the Controller, from the values that it takes form the form. This is then sent to the Db_Facade, which compares the uName and uPwd, and if they are equal returns the ACCESS, which will be set for the entire scope of the program.
I don't know if the get and set declarations are done correctly, or if they can be bunched together (If this is possible it would be great because I will be using this for much larger collections of data), and I'm pretty sure I'm implementing them wrong as well.
If you can help, my knowledge of Accessors is incredibly limited.
Here is my Compare Login method in my Controller:
public static void Compare_Login(User_Login_View Login_View)
{
User_Model getACCESS = new User_Model(); // Creates a new oject of User_Model
getACCESS.Name = Login_View.txtUsername.Text; //Populates the Model from the Login View
getACCESS.Pwd = Login_View.txtPassword.Text;
if (getACCESS.ACCESSLEVEL > 0)
{
Login_View.Close();
}
else
{
Login_View.lblError.Visible = true;
}
Login_View.Menu.SetMenuView();
}
Here is my Model:
public class User_Model
{
public string Name
{
get
{
return Db_Facade.uName;
}
set
{
Db_Facade.uName = value;
}
}
public string Pwd
{
get
{
return Db_Facade.uPwd;
}
set
{
Db_Facade.uPwd = value;
}
}
public int ACCESSLEVEL
{
get
{
return Db_Facade.ACCESS;
}
set
{
Db_Facade.ACCESS = value;
}
}
}
Here is the dummy database comparison:
class Db_Facade
{
public static string uName;
public static string uPwd;
public static string cPwd;
public static int ACCESS;
public static void getLoginACCESS()
{
uName = "paul";
uPwd = "pwd";
ACCESS = 1;
/* I get a "getACCESS does not exist" error here
if (uName == getACCESS.Name && uPwd == getACCESS.Pwd)
{
getACCESS.ACCESSLEVEL = ACCESS;
}
else
{
getACCESS.ACCESSLEVEL = 0;
}
*/
}
}
I don't know if it's needed, but here is my View
public partial class User_Login_View : Form
{
public Menu_View Menu { get; set; }
public User_Login_View()
{
InitializeComponent();
}
private void btnLogin_Click(object sender, EventArgs e)
{
User_Controller.Compare_Login(this);
}
}
2 Questions / Hints
1.) Where do you call your getLoginACCESS() ?
2.) Why do you think Db_Facade is able to access getACCESSfrom your class User_Controller?
a solution would be to modyfie your getLoginACCESS() to getLoginACCESS(User_Model getACCESS) and than call it in your Compare_Login(User_Login_View Login_View) befor your if like Db_Facade.etLoginACCESS(getACCESS);

Categories