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.
Related
I have a custom class that gets some data from the web.
When I get this data I want to set it to the value of a property but when I do this unity crashes. The commented line generates the crash without this line everything works fine. See my code below:
using System;
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
public class GetDB
{
private readonly Main m;
private readonly string Url;
public string DBData {
get
{
if(DBData == null)
return null;
else
return DBData;
}
private set
{
DBData = value;
}
}
public GetDB(Main m, string url)
{
this.m = m;
this.Url = url;
}
public void GetServerData(){
m.StartCoroutine(GetText(Url, (result) =>{
this.DBData = result; //THIS LINE CRASHES UNITY
Debug.Log(result);
}));
}
IEnumerator GetText(string url, Action<string> result) {
UnityWebRequest www = UnityWebRequest.Get(url);
yield return www.SendWebRequest();
if(www.isNetworkError || www.isHttpError) {
Debug.Log(www.error);
}
else {
if (result != null)
result(www.downloadHandler.text);
}
}
}
How would I go about fixing this, and what exactly is happening here?
If anything is unclear let me know so I can clarify.
You have to use a backing field for the property:
string _dbData;
public string DBData
{
get
{
if(_dbData == null)
return null;
else
return _dbData;
}
private set
{
_dbData= value;
}
}
A property is just syntactic sugar for a getter and setter methods. So you can rewrite your property like:
public string GetDBData()
{
if(_dbData == null)
return null;
else
return _dbData;
}
public void SetDBData(string value)
{
_dbData = value;
}
The way you have implemented the property:
public void SetDBData(string value)
{
// you will never get out of here
SetDBData(value);
}
Properties act as accessors for variables. What is happening in your case is basically an endless loop - whenever somebody tries to get the value of your property, it keeps returning the property itself. Instead, you want a backing field _dbData:
private string _dbData;
public string DBData
{
get
{
return _dbData;
}
private set
{
_dbData = value;
}
}
Now your property controls the accesss to this field.
Your accessor can be really simplified.
Doing :
get
{
if(DBData == null)
return null;
else
return DBData;
}
Will provide exactly the same result than doing :
get
{
return DBData; //if DBData is null, it will return null
}
So, you can write your accessor that way :
public string DBData
{
get;
private set;
}
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);
}
}
Before I started encapsulation and learn how to use properties, I was looking at Setters and Getters methods.
I understood how SetID and GetID methods works but I wasn't sure about SetName, GetName and GetPassMark methods.
using System;
public class Student
{
private int _id;
private string _Name;
private int _PassMark = 35;
public void SetId(int Id)
{
if (Id<=0)
{
throw new Exception("Student Id cannot be negative");
}
this._id = Id;
}
public int GetId()
{
return this._id;
}
public void SetName(string Name)
{
if(string.IsNullOrEmpty(Name))
{
throw new Exception("Name cannot be null or empty");
}
this._Name = Name;
}
public string GetName()
{
if(string.IsNullOrEmpty(this._Name))
{
return "No Name";
}
else
{
return this._Name;
}
}
public int GetPassMark()
{
return this._PassMark;
}
}
public class Program
{
public static void Main()
{
Student C1 = new Student();
C1.SetId(101);
C1.SetName("Mark");
Console.WriteLine("ID = {0}" , C1.GetId());
Console.WriteLine("Student Name = {0}", C1.GetName());
Console.WriteLine("PassMark = {0}", C1.GetPassMark());
}
}
When I looked at SetName, I understood that if the string is either empty or null, we throw exception and otherwise this._Name = Name.
But when I looked at GetName, I didn't really understand why there is the if statement.
If Name was null or empty, there wouldn't have been this._Name as we throw exception in SetName.
Can't we just write down return this._Name in GetName?
Also in GetPassMark method why is this. necessary in return this._PassMark?
Because _Name is not being set when you are creating the object. So there is a possibility that a Student object will have null _Name. You can fix it by setting the _Name in the constructor, then you can just return it.
Many people prefer to use this even when it's not really necessary since it makes the code more obvious. It's just a syntactical preference.
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.
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.