CommunityServer 的对象持久化

 2023-09-15 阅读 23 评论 0

摘要:CommunityServer中广泛应用了一种对象持久化的机制,这种机制和.Net2.0中的Profile是相同的原理,把对象序列化为一个字符串保存到数据库的一个字段中,同时使用另一个字段保存对象所在字符串的位置,看看一个例子:[PropertyNames]字段的值:EnableAllPreview:S:0:5:EnablePreviewR
CommunityServer中广泛应用了一种对象持久化的机制,  这种机制和.Net2.0中的Profile是相同的原理,把对象序列化为一个字符串保存到数据库的一个字段中,同时使用另一个字段保存对象所在字符串的位置,看看一个例子:

[PropertyNames]字段的值:
None.gifEnableAllPreview:S:0:5:EnablePreviewResumeAttachment:S:5:4:EnablePreviewBaseInfo:S:9:4:EnablePreviewDetailInfo:S:13:4:EnablePreviewJobExp:S:17:5:EnablePreviewEduExp:S:22:5:EnablePreviewUserSkill:S:27:5:EnablePreviewUserLanguage:S:32:5:EnablePreviewCertificate:S:37:5:EnablePreviewAdvUser:S:42:5:EnablePreviewTrainingExperience:S:47:5:EnablePreviewProjectExperience:S:52:5:
[PropertyValues]字段的值:
None.gifFalseTrueTrueTrueFalseFalseFalseFalseFalseFalseFalseFalse
上面代码中的"S:0:5"表示了对象在字符串中的位置和类型
"S"表示这个对象是一个字符串
"0"表示这个对象在字符串中开始的索引
"5"表示这个对象的长度
根据这些信息,程序或都SQL代码都可以提取出所需要的对象,例如:
EnableAllPreview:S:0:5: 表示EnableAllPreview表示这个对象保存在[PropertyValues]中是一个字符串的形式,并且它的开始位置是从0开始,长度为5个字符,根据这样的条件可以得到对象的值是False

      CommunityServer内部已经封装好了一些方法用于方便使用这样的持久化机制.

1.为想使用这种持久化机制的表添加两个字段:
None.gifALTER TABLE Job_ResumeState ADD PropertyNames ntext NULL
None.gif
ALTER TABLE Job_ResumeState ADD PropertyValues ntext NULL

2.表对应的对象继承于ExtendedAttributes对象,对象中封装了一些方法,让你可以非常方便的添加扩展属性.
None.gif    [Serializable]
None.gif    
public class ExtendedAttributes
ExpandedBlockStart.gifContractedBlock.gif    
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif        
public ExtendedAttributes() dot.gif{ }
InBlock.gif
InBlock.gif        NameValueCollection extendedAttributes 
= new NameValueCollection();
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 获取扩展属性
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        public string GetExtendedAttribute(string name)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
string returnValue = extendedAttributes[name];
InBlock.gif
InBlock.gif            
if (returnValue == null)
InBlock.gif                
return string.Empty;
InBlock.gif            
else
InBlock.gif                
return returnValue;
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 设置扩展属性
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        public void SetExtendedAttribute(string name, string value)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
if ((value == null|| (value == string.Empty))
InBlock.gif                extendedAttributes.Remove(name);
InBlock.gif            
else
InBlock.gif                extendedAttributes[name] 
= value;
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 扩展属性的数量
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        public int ExtendedAttributesCount
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif            
get dot.gifreturn extendedAttributes.Count; }
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 获取Bool型的扩展属性
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        public bool GetBool(string name, bool defaultValue)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
string b = GetExtendedAttribute(name);
InBlock.gif            
if (b == null || b.Trim().Length == 0)
InBlock.gif                
return defaultValue;
InBlock.gif            
try
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
return bool.Parse(b);
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockStart.gifContractedSubBlock.gif            
catch dot.gif{ }
InBlock.gif            
return defaultValue;
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 获取整型扩展属性
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        public int GetInt(string name, int defaultValue)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
string i = GetExtendedAttribute(name);
InBlock.gif            
if (i == null || i.Trim().Length == 0)
InBlock.gif                
return defaultValue;
InBlock.gif
InBlock.gif            
return Int32.Parse(i);
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 获取日期型扩展属性
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        public DateTime GetDateTime(string name, DateTime defaultValue)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
string d = GetExtendedAttribute(name);
InBlock.gif            
if (d == null || d.Trim().Length == 0)
InBlock.gif                
return defaultValue;
InBlock.gif
InBlock.gif            
return DateTime.Parse(d);
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 获取字符型扩展属性
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        public string GetString(string name, string defaultValue)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
string v = GetExtendedAttribute(name);
InBlock.gif            
return (String.IsNullOrEmpty(v)) ? defaultValue : v;
ExpandedSubBlockEnd.gif        }

InBlock.gif
ContractedSubBlock.gifExpandedSubBlockStart.gif        
Serialization#region Serialization
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 获取扩属性的序列化数据
InBlock.gif        
/// </summary>
ExpandedSubBlockEnd.gif        
/// <returns></returns>

InBlock.gif        public SerializerData GetSerializerData()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            SerializerData data 
= new SerializerData();
InBlock.gif            
//data.Bytes = Serializer.ConvertToBytes(this.extendedAttributes);
InBlock.gif

InBlock.gif            
string keys = null;
InBlock.gif            
string values = null;
InBlock.gif
InBlock.gif            Serializer.ConvertFromNameValueCollection(
this.extendedAttributes, ref keys, ref values);
InBlock.gif            data.Keys 
= keys;
InBlock.gif            data.Values 
= values;
InBlock.gif
InBlock.gif            
return data;
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 设置扩属性的序列化数据
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        public void SetSerializerData(SerializerData data)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
//            if(data.Bytes != null)
InBlock.gif            
//            {
InBlock.gif            
//                try
InBlock.gif            
//                {
InBlock.gif            
//                    extendedAttributes = Serializer.ConvertToObject(data.Bytes) as NameValueCollection;
InBlock.gif            
//                }
InBlock.gif            
//                catch{}
InBlock.gif            
//            }
InBlock.gif

InBlock.gif            
if (this.extendedAttributes == null || this.extendedAttributes.Count == 0)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
this.extendedAttributes = Serializer.ConvertToNameValueCollection(data.Keys, data.Values);
ExpandedSubBlockEnd.gif            }

InBlock.gif
InBlock.gif            
if (this.extendedAttributes == null)
InBlock.gif                extendedAttributes 
= new NameValueCollection();
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif        
#endregion

InBlock.gif
ExpandedBlockEnd.gif    }

其中的public SerializerData GetSerializerData()和public void SetSerializerData(SerializerData data)用于获取和添加序列化数据时使用,在下面的例子中会有更详细的讨论,而其它方法都是为了方便从序列化中获取或者设置对象的助手方法.
看一下继承于此扩展属性类的类:
None.gif    [Serializable]
None.gif    
public class ResumeState : ExtendedAttributes
ExpandedBlockStart.gifContractedBlock.gif    
dot.gif{
InBlock.gif        
private Guid resumeid;
InBlock.gif        
public Guid Resumeid
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif            
get dot.gifreturn resumeid; }
ExpandedSubBlockStart.gifContractedSubBlock.gif            
set dot.gif{ resumeid = value; }
ExpandedSubBlockEnd.gif        }

InBlock.gif        
public bool EnableAllPreview
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif            
get dot.gifreturn GetBool("EnableAllPreview"false); }
ExpandedSubBlockStart.gifContractedSubBlock.gif            
set dot.gif{ SetExtendedAttribute("EnableAllPreview", value.ToString()); }
ExpandedSubBlockEnd.gif        }

InBlock.gif        
public bool EnablePreviewBaseInfo
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif            
get dot.gifreturn GetBool("EnablePreviewBaseInfo"false); }
ExpandedSubBlockStart.gifContractedSubBlock.gif            
set dot.gif{ SetExtendedAttribute("EnablePreviewBaseInfo", value.ToString()); }
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedBlockEnd.gif    }
其中的EnableAllPreview和EnablePreviewBaseInfo属性就是一个扩展属性,这属性是使用序列化的机制进行保存的,它伴随着对象进行获取,添加,更新,删除,只要框架定好了添加一个新的扩展属性并不需要任何数据库操作就能够快速的实现.

3.扩展属性是如何加载到对象的,这里看一段代码从数据库返回的IDataReader填充对象的操作:
None.gif        public static ResumeState PopulateResumeStateFromIDataReader(IDataReader dr)
ExpandedBlockStart.gifContractedBlock.gif        
dot.gif{
InBlock.gif            ResumeState state 
= new ResumeState();
InBlock.gif            SerializerData data 
= new SerializerData(); 
InBlock.gif
InBlock.gif            state.Resumeid 
= (Guid)dr["Resumeid"];
InBlock.gif            state.ViewType 
= (ViewType)dr["ViewType"];
InBlock.gif
InBlock.gif            data.Keys 
= ProviderHelper.GetString(dr, "PropertyNames"null);
InBlock.gif            data.Values 
= ProviderHelper.GetString(dr, "PropertyValues"null);
InBlock.gif
InBlock.gif            state.SetSerializerData(data);
InBlock.gif              
InBlock.gif            
return state;
ExpandedBlockEnd.gif        }

SerializerData data = new SerializerData(); 是用来保存对象名值对的自定义对象
None.gif    public class SerializerData
ExpandedBlockStart.gifContractedBlock.gif    
dot.gif{
InBlock.gif        
public string Keys;
InBlock.gif        
public string Values;
ExpandedBlockEnd.gif    }
事实上对象的提取就是根据键值进行提取的,这个对象会在state.SetSerializerData(data);方法中填充并反序列化到一个NameValueCollection对象中,这个对象就是保存在ExtendedAttributes类中的NameValueCollection extendedAttributes
有了这个NameValueCollection后就可以根据键来得到其相应的值,例如:
get { return GetBool("EnableAllPreview", false); }就可以获取EnableAllPreview属性的值

4.扩展属性如何保存到数据库字段中?
None.gif        public override int InsertResumeState(ResumeState resumeState)
ExpandedBlockStart.gifContractedBlock.gif        
dot.gif{
InBlock.gif            Database db 
= DatabaseFactory.CreateDatabase();
InBlock.gif
InBlock.gif            SerializerData data 
= resumeState.GetSerializerData();
InBlock.gif
InBlock.gif            
string sqlCommand = "Job_ResumeState_Insert";
InBlock.gif            DbCommand dbCommand 
= db.GetStoredProcCommand(sqlCommand);
InBlock.gif            db.AddInParameter(dbCommand, 
"@Resumeid", DbType.Guid, resumeState.Resumeid);
InBlock.gif            db.AddInParameter(dbCommand, 
"@ViewType", DbType.Int32, resumeState.ViewType);
InBlock.gif            db.AddInParameter(dbCommand, 
"@PropertyNames", DbType.String, data.Keys);
InBlock.gif            db.AddInParameter(dbCommand, 
"@PropertyValues", DbType.String, data.Values);
InBlock.gif            db.AddOutParameter(dbCommand, 
"@retvar", DbType.Int32, 4);
InBlock.gif
InBlock.gif            
try
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                db.ExecuteNonQuery(dbCommand);
InBlock.gif                
return (int)db.GetParameterValue(dbCommand, "@retvar");
ExpandedSubBlockEnd.gif            }

InBlock.gif            
catch
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
return -1;
ExpandedSubBlockEnd.gif            }

ExpandedBlockEnd.gif        }
如上例子,在添加一新简历状态时只需要使用封装好的方法获取当前对象的扩展属性的SerializerData对象
SerializerData data = resumeState.GetSerializerData();
因为ResumeState是继承于ExtendedAttributes属性的,所以可以直接使用GetSerializerData()方法序列化出一个含有扩展属性的序列化字符串,从而可以保存到数据库:
None.gif            db.AddInParameter(dbCommand, "@PropertyNames", DbType.String, data.Keys);
None.gif            db.AddInParameter(dbCommand, 
"@PropertyValues", DbType.String, data.Values);

最后贴上一个封装好的序列化和反序化方法:

ExpandedBlockStart.gifContractedBlock.gif        /**//// <summary>
InBlock.gif        
/// Creates a NameValueCollection from two string. The first contains the key pattern and the second contains the values
InBlock.gif        
/// spaced according to the kys
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="keys">Keys for the namevalue collection</param>
InBlock.gif        
/// <param name="values">Values for the namevalue collection</param>
InBlock.gif        
/// <returns>A NVC populated based on the keys and vaules</returns>
InBlock.gif        
/// <example>
InBlock.gif        
/// string keys = "key1:S:0:3:key2:S:3:2:";
InBlock.gif        
/// string values = "12345";
InBlock.gif        
/// This would result in a NameValueCollection with two keys (Key1 and Key2) with the values 123 and 45
ExpandedBlockEnd.gif        
/// </example>

None.gif        public static NameValueCollection ConvertToNameValueCollection(string keys, string values)
ExpandedBlockStart.gifContractedBlock.gif        
dot.gif{
InBlock.gif            NameValueCollection nvc 
= new NameValueCollection();
InBlock.gif
InBlock.gif            
if (keys != null && values != null && keys.Length > 0 && values.Length > 0)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif                
char[] splitter = new char[1dot.gif':' };
InBlock.gif                
string[] keyNames = keys.Split(splitter);
InBlock.gif
InBlock.gif                
for (int i = 0; i < (keyNames.Length / 4); i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    
int start = int.Parse(keyNames[(i * 4+ 2], CultureInfo.InvariantCulture);
InBlock.gif                    
int len = int.Parse(keyNames[(i * 4+ 3], CultureInfo.InvariantCulture);
InBlock.gif                    
string key = keyNames[i * 4];
InBlock.gif
InBlock.gif                    
//Future version will support more complex types    
InBlock.gif
                    if (((keyNames[(i * 4+ 1== "S"&& (start >= 0)) && (len > 0&& (values.Length >= (start + len)))
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
dot.gif{
InBlock.gif                        nvc[key] 
= values.Substring(start, len);
ExpandedSubBlockEnd.gif                    }

ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

InBlock.gif
InBlock.gif            
return nvc;
ExpandedBlockEnd.gif        }

None.gif
ExpandedBlockStart.gifContractedBlock.gif        
/**//// <summary>
InBlock.gif        
/// Creates a the keys and values strings for the simple serialization based on a NameValueCollection
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="nvc">NameValueCollection to convert</param>
InBlock.gif        
/// <param name="keys">the ref string will contain the keys based on the key format</param>
ExpandedBlockEnd.gif        
/// <param name="values">the ref string will contain all the values of the namevaluecollection</param>

None.gif        public static void ConvertFromNameValueCollection(NameValueCollection nvc, ref string keys, ref string values)
ExpandedBlockStart.gifContractedBlock.gif        
dot.gif{
InBlock.gif            
if (nvc == null || nvc.Count == 0)
InBlock.gif                
return;
InBlock.gif
InBlock.gif            StringBuilder sbKey 
= new StringBuilder();
InBlock.gif            StringBuilder sbValue 
= new StringBuilder();
InBlock.gif
InBlock.gif            
int index = 0;
InBlock.gif            
foreach (string key in nvc.AllKeys)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
if (key.IndexOf(':'!= -1)
InBlock.gif                    
throw new ArgumentException("ExtendedAttributes Key can not contain the character \":\"");
InBlock.gif
InBlock.gif                
string v = nvc[key];
InBlock.gif                
if (!String.IsNullOrEmpty(v))
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    sbKey.AppendFormat(
"{0}:S:{1}:{2}:", key, index, v.Length);
InBlock.gif                    sbValue.Append(v);
InBlock.gif                    index 
+= v.Length;
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

InBlock.gif            keys 
= sbKey.ToString();
InBlock.gif            values 
= sbValue.ToString();
ExpandedBlockEnd.gif        }

转载于:https://www.cnblogs.com/chenjunbiao/archive/2006/09/14/1760245.html

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/1/57195.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息