2012-06-22 6 views
0

this article을 기반으로 FullName을 쉽게 얻을 수있었습니다. 내가 무엇을 할 때복잡한 프로필 값을 할당하는 방법

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

: 다음 다음 코드로 JSON에이 직렬화하는 방법이

[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 

:

은 나뿐만 아니라 자식 클래스가 다음과 같은 클래스가 위의 기사에서는 다음과 같은 작업을 수행합니다.

UserProfileContract.CurrentUser.FullName = "Testing"; 

내 List/Complex 개체 (지금 JSON 형식 문자열) ... 나는 위의 다음과 같은 오류 (주 얻을

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

I도 두 배로 .toString()하지만 운 문자열로 강제 :

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

분명히 잘못된 일을하고 있습니다. ASP.Net 기본 프로필 공급자에 json 데이터를 저장하려는 첫 번째 사용자가 아니라고 가정해야합니다. 어떤 도움이라도 대단히 감사하겠습니다.

답변

0

Working.FinalName에 Utilities.Serialize ... 코드를 넣은 테스트를 수행 한 결과 작동했습니다. 그런 다음 FullName을 FullNameXX로 변경했는데 실패했습니다. 몇 가지 테스트를 한 후 프로파일에 저장된 모든 속성이 문자열이어야한다는 결론에 이르렀습니다. (또는 Binary로 가정해야하지만 SQL에서 PropertyValuesBinary 데이터 필드를 사용하지 않습니다.) 그래서 복잡한 필드 , 내 List와 마찬가지로 List를 얻고 저장하는 프로그래머를위한 속성과 동일한 속성의 문자열 버전을 저장했습니다. 이제 SectionSettings 및 SectionSettingsValue 속성이 생겼습니다. 필요한 또 다른 조정은 DataContract와 Serializable이 아닌 것만 만들거나 IMHO가 좋지 않은 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 

내 정적 유틸리티 클래스입니다 : 여기

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 속성뿐만 아니라 여러 섹션에 데이터를 저장하는 방법 :

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

의 문자열 버전 여기 I가 SectionSetting 추출 쉽게 값들 있도록 만든 확장 방법 내가 넣은 값 :

[{"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 = ... 예에서 ret 데이터가 "Primart Thing"이지 "Primary Thing"이 아니기 때문에 urns null입니다.

희망이 있으면 도움이 될 것입니다.

관련 문제