Za selektivno cuvanje vrednosti svojstava koristi sistem atributa kao i kod serijalizacije.
U nastavku teksta sam ti dao kod kojim mozes sacuvati vrednosti svojstava nekog objekta u string (metoda
SaveProperties) i ucitati vrednosti svojstava nekog objekta iz stringa (metoda
RestoreProperties). Ovaj kod ignorise svojstva koja sadrze atribut
XmlIgnoreAttribute.
U slucaju da ti imas vise svojstava koja treba ignorisati od onih koja treba sacuvati, prepravi kod da cuva samo svojstva koja sadrze atribut
XmlIncludeAttribute.
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using System.Text;
using System.Xml.Serialization;
namespace WindowsApplication1
{
public class MemberHelpers
{
/// <summary>
/// Returns TypeConverter for specified type.
/// </summary>
public static TypeConverter GetTypeConverter(Type type)
{
return (type != null ? TypeDescriptor.GetConverter(type) : null);
}
/// <summary>
/// Returns TypeConverter for specified object.
/// </summary>
public static TypeConverter GetTypeConverter(object component)
{
return (component != null ? GetTypeConverter(component.GetType()) : null);
}
/// <summary>
/// Sets object field or property to specified string value.
/// </summary>
public static bool SetMemberValueAsString(object obj, MemberInfo mi, string value, ref Exception ex)
{
if(obj != null && mi != null && (mi.MemberType == MemberTypes.Property || mi.MemberType == MemberTypes.Field)) {
// use a type converter to convert string value
try {
TypeConverter tc = GetTypeConverter(mi);
if(tc != null) {
if(mi.MemberType == MemberTypes.Property) {
PropertyInfo pi = mi as PropertyInfo;
if(pi != null) {
if(tc.CanConvertFrom(typeof(string))) {
object val = tc.ConvertFromInvariantString(value);
pi.SetValue(obj, val, null);
return true;
} else if(pi.PropertyType == typeof(Type)) {
pi.SetValue(obj, Type.GetType(value), null);
return true;
}
}
} else if(mi.MemberType == MemberTypes.Field) {
FieldInfo fi = mi as FieldInfo;
if(fi != null) {
if(tc.CanConvertFrom(typeof(string))) {
object val = tc.ConvertFromInvariantString(value);
fi.SetValue(obj, val);
return true;
} else if(fi.FieldType == typeof(Type)) {
fi.SetValue(obj, Type.GetType(value));
return true;
}
}
}
}
} catch(Exception e) {
ex = e;
}
}
return false;
}
/// <summary>
/// Sets object field or property to specified string value.
/// </summary>
public static bool SetMemberValueAsString(object obj, MemberInfo mi, string value)
{
Exception ex = null;
return SetMemberValueAsString(obj, mi, value, ref ex);
}
/// <summary>
/// Gets field or property value in string form.
/// </summary>
public static bool GetMemberValueAsString(object obj, MemberInfo mi, ref string value, ref Exception ex)
{
if(obj != null && mi != null && (mi.MemberType == MemberTypes.Property || mi.MemberType == MemberTypes.Field)) {
try {
TypeConverter tc = GetTypeConverter(mi);
if(tc != null) {
if(mi.MemberType == MemberTypes.Property) {
PropertyInfo pi = mi as PropertyInfo;
if(pi != null) {
object objValue = pi.GetValue(obj, null);
if(tc.CanConvertFrom(typeof(string)) && tc.CanConvertTo(typeof(string))) {
value = tc.ConvertToInvariantString(objValue);
return true;
} else if(pi.PropertyType == typeof(Type)) {
value = ((Type)objValue).AssemblyQualifiedName;
return true;
}
}
} else if(mi.MemberType == MemberTypes.Field) {
FieldInfo fi = mi as FieldInfo;
if(fi != null) {
object objValue = fi.GetValue(obj);
if(tc.CanConvertFrom(typeof(string)) && tc.CanConvertTo(typeof(string))) {
value = tc.ConvertToInvariantString(objValue);
return true;
} else if(fi.FieldType == typeof(Type)) {
value = ((Type)objValue).AssemblyQualifiedName;
return true;
}
}
}
}
} catch(Exception e) {
ex = e;
}
}
return false;
}
/// <summary>
/// Gets field or property value in string form.
/// </summary>
public static bool GetMemberValueAsString(object obj, MemberInfo mi, ref string value)
{
Exception ex = null;
return GetMemberValueAsString(obj, mi, ref value, ref ex);
}
/// <summary>
/// Gets field or property value in string form.
/// </summary>
public static string GetMemberValueAsString(object obj, MemberInfo mi)
{
Exception ex = null;
string value = string.Empty;
GetMemberValueAsString(obj, mi, ref value, ref ex);
return value;
}
/// <summary>
/// Replaces special characters in string with specific escape string that can be later restored:
/// '\\' -> "\\\\"
/// '\r' -> "\\r"
/// '\n' -> "\\n"
/// '\t' -> "\\t"
/// </summary>
public static string EscapeSpecialCharacters(string text)
{
if(text == null) return null;
System.Text.StringBuilder result = new System.Text.StringBuilder();
for(int i = 0; i < text.Length; i++) {
if(text[i] == '\\') {
result.Append("\\\\");
} else if(text[i] == '\r') {
result.Append("\\r");
} else if(text[i] == '\n') {
result.Append("\\n");
} else if(text[i] == '\t') {
result.Append("\\t");
} else {
result.Append(text[i]);
}
}
return result.ToString();
}
/// <summary>
/// Restores special characters in string that where replaced using ReplaceSpecialCharacters method.
/// Restoration is performed using following patterns:
/// "\\\\" -> '\\'
/// "\\r" -> '\r'
/// "\\n" -> '\n'
/// "\\t" -> '\t'
/// </summary>
public static string RestoreSpecialCharacters(string text)
{
if(text == null) return null;
System.Text.StringBuilder result = new System.Text.StringBuilder();
for(int i = 0; i < text.Length; i++) {
if(text[i] == '\\' && i < (text.Length - 1)) {
if(text[i + 1] == '\\') {
result.Append("\\"); i++;
} else if(text[i + 1] == 'r') {
result.Append("\r"); i++;
} else if(text[i + 1] == 'n') {
result.Append("\n"); i++;
} else if(text[i + 1] == 't') {
result.Append("\t"); i++;
} else {
result.Append(text[i]);
}
} else {
result.Append(text[i]);
}
}
return result.ToString();
}
/// <summary>
/// Saves specified object properties values to a string.
/// </summary>
public static string SaveProperties(object obj)
{
if(obj != null) {
StringBuilder s = new StringBuilder();
foreach(PropertyInfo pi in obj.GetType().GetProperties()) {
if(!pi.CanRead) continue;
if(pi.GetCustomAttributes(typeof(XmlIgnoreAttribute), true).Length != 0) continue;
string value = string.Empty;
if(GetMemberValueAsString(obj, pi, ref value)) {
if(s.Length > 0) s.Append('|');
s.Append(pi.Name + "=" + EscapeSpecialCharacters(value));
}
}
return s.ToString();
}
return string.Empty;
}
/// <summary>
/// Restores specified object properties values from a specified string.
/// </summary>
public static void RestoreProperties(object obj, string savedProperties)
{
if(obj != null && !string.IsNullOrEmpty(savedProperties)) {
string[] properties = savedProperties.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
if(properties != null && properties.Length > 0) {
Type type = obj.GetType();
if(obj is ISupportInitialize) ((ISupportInitialize)obj).BeginInit();
foreach(string property in properties) {
int index = property.IndexOf('=');
if(index > 0) {
string name = property.Substring(0, index);
if(name.Length > 0) {
PropertyInfo pi = type.GetProperty(name);
if(pi != null) {
string value = property.Substring(index + 1);
SetMemberValueAsString(obj, pi, RestoreSpecialCharacters(value));
}
}
}
}
if(obj is ISupportInitialize) ((ISupportInitialize)obj).EndInit();
}
}
}
}
}