I have the following code which I'm trying to use to save and load data from a settings XML file on my phone (the caller is accessed via an interface in a PCL)
// caller
public void SetStringValue(string name, string val)
{
UserData.SetPropertyValue(this, name, val);
}
// userdata file
namespace PreferencesXML.iOS
{
public static class UserData
{
public static object GetPropertyValue(object data, string propertyName)
{
return data.GetType().GetProperties().SingleOrDefault(pi => pi.Name == propertyName).GetValue(data, null);
}
public static void SetPropertyValue<T>(object data, string propertyName, T value)
{
data.GetType().GetProperties().SingleOrDefault(pi => pi.Name == propertyName).SetValue(data, value);
}
private static string pUserSettingsFile;
private static UserSetting userSetting;
public static UserSetting UserSetting
{
get
{
if (userSetting == null)
{
if (File.Exists(UserSettingsFile))
{
userSetting = Serialiser.XmlDeserializeObject<UserSetting>(UserSettingsFile);
}
else
{
userSetting = new UserSetting();
Serialiser.XmlSerializeObject(userSetting, UserSettingsFile);
}
}
return userSetting;
}
set
{
if (value == null)
{
throw new ArgumentNullException("value is null!");
}
// end if
userSetting = value;
if (File.Exists(UserSettingsFile))
{
File.Delete(UserSettingsFile);
}
Serialiser.XmlSerializeObject(userSetting, UserSettingsFile);
}
}
public static string UserSettingsFile
{
get
{
if (string.IsNullOrEmpty(pUserSettingsFile))
{
pUserSettingsFile = Path.Combine(AppDelegate.Self.ContentDirectory, "UserSettings.xml");
}
return pUserSettingsFile;
}
}
public static string Company
{
get
{
return UserSetting.companyName;
}
set
{
UserSetting settings = UserSetting;
settings.companyName = value;
UserSetting = settings;
}
}
public static double Pi
{
get
{
return UserSetting.pi;
}
set
{
UserSetting settings = UserSetting;
settings.pi = value;
UserSetting = settings;
}
}
public static bool OnOff
{
get
{
return UserSetting.onOff;
}
set
{
UserSetting settings = UserSetting;
settings.onOff = value;
UserSetting = settings;
}
}
}
public class UserSetting
{
public string companyName{ get; set; }
public double pi{ get; set; }
public bool onOff{ get; set; }
}
}
As you can see, it's not doing anything mind boggling difficult. The reader part of this works fine, but the SetPropertyValue
constantly returns a fail at the SingleOrDefault
.
This is down to the caller extension method extending the class the caller is in rather than the UserData class.
As the UserData
class is static, I can't create an object instance of it and pass that in in place of the this parameter, neither can I pass UserData in directly or as a generic parameter (such as this.SetPropertyValue<UserData>(...)
). I've attempted to make the class non-static, which gets me a bit further, but not much.
Is there a way that I can use this code to store data to and from my UserData class?
No comments:
Post a Comment