如何分配复杂的配置文件值



基于这篇文章,我能够相当轻松地获得全名。

我有以下类也有子类:

[DataContract]
[Serializable]
public class SettingSection
{
    public SettingSection()
    {
        this.UserSettings = new List<UserSettingPair>();
    } // SettingSection - Constructor
    public SettingSection(List<UserSettingPair> UserSettings)
    {
        this.UserSettings = UserSettings;
    } // SettingSection - Constructor
    [DataMember(Name = "sectionName")]
    public string SectionName { get; set; }
    [DataMember(Name = "userSettings")]
    public List<UserSettingPair> UserSettings { get; set; }
} // SettingSection - Class
[DataContract]
[Serializable]
public class UserSettingPair
{
    [DataMember(Name = "key")]
    public string Key { get; set; }
    [DataMember(Name = "value")]
    public string Value { get; set; }
} // UserSettingPair - Class

然后,我有一种方法可以使用以下代码将其序列化为 JSon:

public static string Serialize<T>(object input)
{
    string Result = "";
    DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
    using (MemoryStream ms = new MemoryStream())
    {
        ser.WriteObject(ms, input);
        Result = Encoding.Default.GetString(ms.ToArray());
    }
    return Result;
}

当我执行上述文章中的内容时,以下工作:

UserProfileContract.CurrentUser.FullName = "Testing";

当我尝试使用我的列表/复杂对象(现在是 json 格式字符串)时......

base["sectionSettings"] = (Utilities.Serialize<List<SettingSection>>(Settings)).ToString();
Save();

收到以下错误(注意上面我什至用 .ToString() 但没有运气:

The settings property 'sectionSettings' is of a non-compatible type.

显然做错了什么,我必须假设我不是第一个想要将 json 数据保存在 ASP.Net 默认配置文件提供程序中的人。 任何帮助将不胜感激。

在做了一些测试后,我把实用程序.序列化...代码到工作全名中,这奏效了。 然后我将 FullName 重命名为 FullNameXX,它失败了。 经过几次测试,我得出的结论是,要保存在配置文件中的所有属性都需要是字符串(或我假设的二进制,但我没有在SQL中使用PropertyValuesBinary数据字段。 因此,当我有一个复杂的字段(例如我的 List)时,我为程序员提供了一个属性,该属性获取和设置了一个 List,以及存储的相同属性的字符串版本。 所以我现在有一个 SectionSettings 和一个 SectionSettingsValue 属性。 另一个需要的调整是使其仅是数据合约而不是可序列化的,否则您将获得额外的值,例如恕我直言k__backingField看起来很糟糕。

以下应该是完整的代码...

这是我的数据合约:

[DataContract]
public class UserProfileContract : ProfileBase
{
    #region Constructors
    public UserProfileContract()
    {
    } // UserProfileContract - Constructor
    public UserProfileContract(List<SettingSection> SectionSettings)
    {
        this.SectionSettings = SectionSettings;
    } // UserProfileContract - Constructor
    #endregion Constructors
    public static UserProfileContract CurrentUser
    {
        get { return (UserProfileContract)(ProfileBase.Create(Membership.GetUser().UserName)); }
    }
    public string FullNameValue { get; set; }
    public string SectionSettingsValue { get; set; }
    [DataMember(Name = "FullName")]
    public string FullName
    {
        get { return ((string)(base["FullNameValue"])); }
        set {
            base["FullNameValue"] = value;
            Save();
        }
    } // FullName - Property
    [DataMember(Name = "SectionSettings")]
    public List<SettingSection> SectionSettings
    {
        get { return Utilities.Deserialize<List<SettingSection>>(base["SectionSettingsValue"].ToString()); }
        set
        {
            base["SectionSettingsValue"] = Utilities.Serialize<List<SettingSection>>(value);
            Save();
        }
    } // SectionSettings - Property
} // UserProfileContract - Class
[DataContract]
public class SettingSection
{
    public SettingSection()
    {
        this.UserSettings = new List<UserSettingPair>();
    } // SettingSection - Constructor
    public SettingSection(List<UserSettingPair> UserSettings)
    {
        this.UserSettings = UserSettings;
    } // SettingSection - Constructor
    [DataMember]
    public string SectionName { get; set; }
    [DataMember]
    public List<UserSettingPair> UserSettings { get; set; }
} // SettingSection - Class
[DataContract]
public class UserSettingPair
{
    [DataMember]
    public string Key { get; set; }
    [DataMember]
    public string Value { get; set; }
} // UserSettingPair - Class

这是我的静态实用程序类:

public static T Deserialize<T>(string json)
{
    var obj = Activator.CreateInstance<T>();
    if (string.IsNullOrWhiteSpace(json))
        return obj;
    using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
    {
        var serializer = new DataContractJsonSerializer(obj.GetType());
        obj = (T)serializer.ReadObject(ms);
        return obj;
    } // using the memory stream
} // Deserialize - Method
public static string Serialize<T>(object input)
{
    string Result = "";
    DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
    using (MemoryStream ms = new MemoryStream())
    {
        ser.WriteObject(ms, input);
        Result = Encoding.Default.GetString(ms.ToArray());
    }
    return Result;
} // Serialize - Method

下面是如何在多个部分中保存数据以及 FullName 属性的示例:

// First Section
SettingSection s = new SettingSection();
s.SectionName = "ContractSearch";
UserSettingPair usp = new UserSettingPair();
usp.Key = "Default Control";
usp.Value = "txtFirstTextBox";
s.UserSettings.Add(usp);
usp = new UserSettingPair();
usp.Key = "Field1Choice";
usp.Value = "SchoolName";
s.UserSettings.Add(usp);
List<SettingSection> ss = new List<SettingSection>();
ss.Add(s);
// Second Section
s = new SettingSection();
s.SectionName = "Workflow Settings";
usp = new UserSettingPair();
usp.Key = "Primart Thing";
usp.Value = "Blabla bla";
s.UserSettings.Add(usp);
usp = new UserSettingPair();
usp.Key = "Allowable Tries";
usp.Value = "3";
s.UserSettings.Add(usp);
usp = new UserSettingPair();
usp.Key = "Extra Value";
usp.Value = "Gigity";
s.UserSettings.Add(usp);
ss.Add(s);
UserProfileContract.CurrentUser.FullName = "Grigsby";
UserProfileContract.CurrentUser.SectionSettings = ss;

这是我创建的扩展方法,用于简化 SectionSet 值的提取:

public static T GetSectionValue<T>(this UserProfileContract up, string Section, string Property)
{
    string value = (from ss in up.SectionSettings
                                        from us in ss.UserSettings
                                        where ss.SectionName == Section
                                        && us.Key == Property
                                        select us.Value).FirstOrDefault();
    try
    {
        return (T)Convert.ChangeType(value, typeof(T));
    }
    catch (InvalidCastException)
    {
        return default(T);
    }
} // GetSectionValue - Extension Method

最后,上述扩展方法的示例:

string k = x.GetSectionValue<string>("Workflow Settings", "Primary Thing");
string g = x.GetSectionValue<string>("Workflow Settings", "Extra Value");
int three = x.GetSectionValue<int>("Workflow Settings", "Allowable Tries");

这是我输入的值的字符串版本:

[{"SectionName":"ContractSearch","UserSettings":[{"Key":"Default Control","Value":"txtFirstTextBox"},{"Key":"Field1Choice","Value":"SchoolName"}]},{"SectionName":"Workflow Settings","UserSettings":[{"Key":"Primart Thing","Value":"Blabla bla"},{"Key":"Allowable Tries","Value":"3"},{"Key":"Extra Value","Value":"Gigity"}]}]Grigsby

在上面的字符串中 k = ...例如,请注意它返回 null,因为数据是"原始事物"而不是"主要事物"。

希望这对那里的人有所帮助。

相关内容

  • 没有找到相关文章

最新更新