Remove key value pairs - c#

I have class library which is already developed and in it the following code has been written,
public static PersistenceManager Instance
{
get
{
if (_instance == null)
{
_instance = new PersistenceManager();
}
return _instance;
}
}
where PersistenceManager is a class. I have a WPF application in which i am calling this dll and just before showing login page there is a code written as below,
if (string.IsNullOrWhiteSpace(PersistenceManager.Instance["user"]))
{
StartupUri = new Uri("Login.xaml", UriKind.Relative);
}
else
{
StartupUri = new Uri("Messenger.xaml", UriKind.Relative);
}
I have already registered so it always shows messanger window. Now i want to clear the keyvalue of user so that i can show the login page. I am unable to perform below code ,
PersistenceManager.Instance["user"] = string.Empty;
An unhandled exception of type 'System.ArgumentException' occurred
Any suggesions?
Index-Operator looks like:
public string this[string key]
{
get
{
try
{
return _settingsDictionary[key].Decrypt(ENCKEY);
}
catch (Exception)
{
return string.Empty;
}
}
set
{
if(!string.IsNullOrWhiteSpace(key))
_settingsDictionary[key] = value.Encrypt(ENCKEY);
}
}

rewrite the index operator as following:
public string this[string key]
{
get
{
string value;
_settingsDictionary.TryGetValue(key, out value);
if (string.IsNullOrEmpty(value)) return string.Empty;
return value.Decrypt(ENCKEY);
}
set
{
if (string.IsNullOrEmpty(value)) _settingsDictionary.Remove(key);
else _settingsDictionary[key] = value.Encrypt(ENCKEY);
}
}

Related

property private set crashes unity

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;
}

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.

After Implementing an UITestPropertyProvider, AccessibleName is still not a valid Searchproperty

I need to implement automatic UI Tests for a Delphi Application with Visual Studio Coded UI Tests. I have already implemented the IAccessible Interface to my Delphi-Contols. It works fine and i get the AccessibleName from the Control.
Then i implemented an extension for visual studio. In this extension i have my own PropertyProvider-, ExtensionPackage- and WinControl-Class.
PropertyProvider:
namespace CUITExtension
{
public class AccessibleNamePropertyProvider : UITestPropertyProvider
{
private static Dictionary<string, UITestPropertyDescriptor> accessibleNamePropertyMap = null;
private static Dictionary<string, UITestPropertyDescriptor> AccessibleNamePropertyMap
{
get
{
if (accessibleNamePropertyMap == null)
{
UITestPropertyAttributes read = UITestPropertyAttributes.Readable
| UITestPropertyAttributes.DoNotGenerateProperties;
accessibleNamePropertyMap = new Dictionary<string, UITestPropertyDescriptor>
(StringComparer.OrdinalIgnoreCase);
accessibleNamePropertyMap.Add("AccessibleName", new UITestPropertyDescriptor(typeof(string), read));
}
return accessibleNamePropertyMap;
}
}
public override UITestPropertyDescriptor GetPropertyDescriptor(UITestControl uiTestControl, string propertyName)
{
return AccessibleNamePropertyMap[propertyName];
}
public override ICollection<string> GetPropertyNames(UITestControl uiTestControl)
{
if (uiTestControl.ControlType.NameEquals("Custom"))
{
// the keys of the property map are the collection of property names
return AccessibleNamePropertyMap.Keys;
}
throw new NotSupportedException();
}
public override object GetPropertyValue(UITestControl uiTestControl, string propertyName)
{
if (String.Equals(propertyName, "AccessibleName", StringComparison.OrdinalIgnoreCase))
{
object[] native = uiTestControl.NativeElement as object[];
IAccessible acc = native[0] as IAccessible;
return acc.accName;
}
throw new NotSupportedException();
}
public override int GetControlSupportLevel(UITestControl uiTestControl)
{
if (string.Equals(uiTestControl.TechnologyName, "MSAA",
StringComparison.OrdinalIgnoreCase) &&
uiTestControl.ControlType.NameEquals("Custom"))
{
return (int)ControlSupport.ControlSpecificSupport;
}
// This is not my control, so return NoSupport
return (int)ControlSupport.NoSupport;
}
public override string[] GetPredefinedSearchProperties(Type specializedClass)
{
return null;
}
public override string GetPropertyForAction(UITestControl uiTestControl, UITestAction action)
{
return null;
}
public override string[] GetPropertyForControlState(UITestControl uiTestControl, ControlStates uiState, out bool[] stateValues)
{
stateValues = null;
return null;
}
public override Type GetPropertyNamesClassType(UITestControl uiTestControl)
{
if (uiTestControl.ControlType.NameEquals("Custom"))
return typeof(AccessibleControl.PropertyNames);
return null;
}
public override Type GetSpecializedClass(UITestControl uiTestControl)
{
if (uiTestControl.ControlType.NameEquals("Custom"))
return typeof(AccessibleControl);
return null;
}
public override void SetPropertyValue(UITestControl uiTestControl, string propertyName, object value)
{
return;
}
}
}
ExtensionPackage:
[assembly: Microsoft.VisualStudio.TestTools.UITest.Extension.UITestExtensionPackage(
"AccessibleNameExtensionPackage",
typeof(CUITExtension.AccessibleNameExtensionPackage))]
namespace CUITExtension
{
class AccessibleNameExtensionPackage : UITestExtensionPackage
{
public override string PackageDescription
{
get { return "Supports coded UI testing by using the AccessibleName"; }
}
public override string PackageName
{
get { return "AccessibleName Extension Package"; }
}
public override string PackageVendor
{
get { return "Microsoft (sample)"; }
}
public override Version PackageVersion
{
get { return new Version(1, 0); }
}
public override Version VSVersion
{
get { return new Version(14, 0); }
}
public override void Dispose() { }
public override object GetService(Type serviceType)
{
if (serviceType == typeof(UITestPropertyProvider))
{
if (propertyProvider == null)
{
propertyProvider = new AccessibleNamePropertyProvider();
}
return propertyProvider;
}
return null;
}
private UITestPropertyProvider propertyProvider = null;
}
}
WinControl:
namespace CUITExtension
{
public class AccessibleControl : WinControl
{
public AccessibleControl(UITestControl c) : base(c)
{
TechnologyName = "MSAA";
SearchProperties.Add(UITestControl.PropertyNames.ControlType, "Custom");
}
public virtual string AccessibleName
{
get
{
return (string)GetProperty("AccessibleName");
}
}
}
}
Now the Coded UI Test Builder is showing the AccessibleName and is also generating AccessibleName as a SearchProperty.
UIMap:
public AccessibleControl UIItemCustom
{
get
{
if ((this.mUIItemCustom == null))
{
this.mUIItemCustom = new AccessibleControl(this);
#region Search Criteria
this.mUIItemCustom.SearchProperties["AccessibleName"] = "UniqueName1";
this.mUIItemCustom.SearchProperties[WinControl.PropertyNames.ClassName] = "TEdit";
this.mUIItemCustom.WindowTitles.Add("Title");
#endregion
}
return this.mUIItemCustom;
}
}
*I have changed the Searchproperties here (only for the post, i didnt changed the generated code)
Now when I start the test, I get an exception that says that AccessibleName is not an valid searchproperty. I got this exception before, when i havent implemented the extension yet. But I thougth by implementing the propertyprovider AccessibleName should be a valid searchproperty now.
I tried to debug it, but it seems like by searching the Control it doesnt use the propertyprovider and i have no idea why?
I hope you can help me and if you need more information just ask.
Paul
I got the problem with the valid searchproperty to work.
I overrode the GetValidSearchProperties method from WinControl.
protected override Dictionary<string, bool> GetValidSearchProperties()
{
Dictionary<string, bool> searchProperties = base.GetValidSearchProperties();
if (!searchProperties.ContainsKey("AccessibleName"))
searchProperties.Add("AccessibleName", true);
return searchProperties;
}

Singleton pattern for a property in c#

I am trying to adapt singleton policy for my CsvConfiguration Property.
If the configuration is already available, just return the configuration. else, get the configuration and return the same and I am able to build this code.
public Rootpdf pdfConfiguration
{
get
{
Rootpdf pdfConfiguration = null;
try
{
if (pdfConfiguration == null)
{
//retrieve the configuration file.
//load the configuration and return it!
}
else
{
return pdfConfiguration;
}
}
catch (Exception e)
{
Log.Error("An error occurred while reading the configuration file.", e);
}
return pdfConfiguration;
}
}
Advantages (i hope): Whenever my pdfConfiguration is wanted, if already it is available, i can return it. Need not load the configuration file eachtime
and calculate the configuration.
My Query: The resharper! The resharper tells that the code
if (pdfConfiguration == null) //The expression is always true.
Is it really a problem with resharper that it doesn't understand I am following this singleton pattern ?
or
Am I not following singleton pattern at all?
You're setting the singleton to null at the top of your get clause:
Rootpdf pdfConfiguration = null;
//THIS IS THE PROBLEM.
Note: 99% of the time, ReSharper is smarter than you. I don't like it, but it's true.
think you have to use a local variable out of the getter
private static Rootpdf _pdfConfiguration ;
public static Rootpdf pdfConfiguration
{
get
{
try
{
if (_pdfConfiguration == null)
{
//retrieve the configuration file.
//load the configuration and return it!
}
else
{
return _pdfConfiguration;
}
}
catch (Exception e)
{
Log.Error("An error occurred while reading the configuration file.", e);
}
return _pdfConfiguration;
}
}
and as you want a singleton, i made it a static property... hope it's what you need.
Here is what your class should look like:
public class RootPdf
{
private static RootPdf instance;
private RootPdf()
{
//retrieve the configuration file.
//load the configuration and return it!
}
public static RootPdf Instance
{
get
{
if (instance == null)
{
try
{
instance = new RootPdf();
}
catch (Exception e)
{
Log.Error("An error occurred while reading the configuration file.", e);
return null;
}
}
return instance;
}
}
}
And here is how you will call the object:
var pdf = RootPdf.Instance;
class MySingletonClass
{
private static UserSettings instance = null;
/// <summary>
/// Default protected constructor.
/// </summary>
protected MySingletonClass()
{
}
/// <summary>
/// Invoke the singleton instance.
/// </summary>
public static MySingletonClass Instance()
{
if (instance == null)
instance = new MySingletonClass();
return instance;
}
}
This woud be invoked/instanciated like
MySingletonClass msc = MySingletonClass.Instance();
You can also use an accessor/Property to return the instance
public MySingletonInstance Instance
{
get
{
if (instance == null)
instance = new MySingletonInstance();
return instance;
}
}
Where this is invoked/instantiated via
MySingletonClass msc = MySingletonClass.Instance;
I like the first method of the above.
I hope this helps.
As already mentioned this is a not a singleton pattern.
If you want to stick with the idea you described then I would change your code to :
internal class Config
{
private readonly Lazy<Rootpdf> _config;
public Config()
{
_config = new Lazy<Rootpdf>(ReadConfiguration);
}
private Rootpdf ReadConfiguration()
{
throw new NotImplementedException();
}
public Rootpdf pdfConfiguration
{
get
{
try
{
return _config.Value;
}
catch (Exception e)
{
Log.Error("An error occurred while reading the configuration file.", e);
}
return null;
}
}
This line: if (pdfConfiguration == null) will always be true due to this line (just before) Rootpdf pdfConfiguration = null;. What you need to do is to place the last line (Rootpdf pdfConfiguration = null;) outside the Get method. This will stop the variable to be initialized to null each time.
private static Rootpdf pdfConfiguration = null;
public Rootpdf PdfConfiguration
{
get
{
try
{
if (pdfConfiguration == null)
....
More information on the Singleton Pattern is available here.
Alternatively, you can use a Static Constructor:
A static constructor is used to initialize any static data, or to
perform a particular action that needs to be performed once only. It
is called automatically before the first instance is created or any
static members are referenced.
public class Foo {
private static Rootpdf pdfConfiguration = null;
static Foo()
{
pdfConfiguration = ....
}
public Rootpdf pdfConfiguration
{
get
{
return pdfConfiguration;
}
....
Nowadays , I think since C# 6.0, you can use initial values with properties, like this:
static public Rootpdf pdfConfiguration { get; } = new Func<Rootpdf>(() => {
//retrieve the configuration file.
//load the configuration and return it!
return new Rootpdf(); // Something like this perhaps..?
})();

Why I get this "infinite loop" on Class properties?

This is my property on my code :
public KPage Padre
{
get
{
if (k_oPagina.father != null)
{
this.Padre = new KPage((int)k_oPagina.father);
}
else
{
this.Padre = null;
}
return this.Padre;
}
set { }
}
but it says :
An unhandled exception of type 'System.StackOverflowException' occurred in App_Code.rhj3qeaw.dll
Why? How can I fix it?
EDIT
After correct the code, this is my actual code :
private KPage PadreInterno;
public KPage Padre
{
get
{
if (PadreInterno == null)
{
if (paginaDB.father != null)
{
PadreInterno = new KPage((int)paginaDB.father);
}
else
{
PadreInterno= null;
}
}
return PadreInterno;
}
}
What do you think about?
The property is calling itself... usually properties call underlying fields:
public KPage Padre
{
get
{
if (k_oPagina.father != null)
{
_padre = new KPage((int)k_oPagina.father);
}
else
{
_padre = null;
}
return _padre;
}
set { }
}
private KPage _padre;
Your old code was recursively calling the get of the Padre property, hence the exception.
If your code only "gets" and doesn't need to store the value, you could also get rid of the backing field entirely:
public KPage Padre
{
get
{
return k_oPagina.father != null
? new KPage((int)k_oPagina.father)
: (KPage)null;
}
}
That said, I'd put this in a method.
This is also the same issue as the one you asked a couple of days ago:
An unhandled exception of type 'System.StackOverflowException' occurred

Categories