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

时间:2012-06-22 16:36:03

标签: c#-4.0 asp.net-profiles

基于this article,我能够轻松地使FullName工作。

我有以下有类子类的类:

[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";

当我使用我的List / Complex对象(现在是json格式化字符串)尝试...

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

我收到以下错误(请注意上面我甚至将其强制转换为带有.ToString()的字符串,但没有运气:

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

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

1 个答案:

答案 0 :(得分:0)

在做了一些测试后,我将Utilities.Serialize ...代码放入工作的FullName中,这有效。然后我将FullName重命名为FullNameXX,但失败了。经过几次测试后,我得出的结论是,要保存在Profile中的所有属性都需要是字符串(或者我假设是Binary,但我没有在SQL中使用PropertyValuesBinary数据字段。)所以当我有一个复杂的字段时就像我的List那样,我有一个程序员的属性,它获取并设置一个List以及存储的相同属性的字符串版本。所以我现在有了一个SectionSettings和一个SectionSettingsValue属性。需要进行的另一个调整是使它只是一个DataContract而不是Serializable,否则你会获得额外的值,比如k_backingField,这个值很糟糕。

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

这是我的DataContract:

[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

这是我的静态Utilities类:

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;

这是我创建的扩展方法,可以更轻松地提取SectionSetting值:

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,因为数据是“Primart Thing”而不是“Primary Thing”。

希望这可以帮助那些人。