adapdev-commits Mailing List for Adapdev.NET (Page 16)
Status: Beta
Brought to you by:
intesar66
You can subscribe to this list here.
2005 |
Jan
|
Feb
|
Mar
(26) |
Apr
(59) |
May
(37) |
Jun
(53) |
Jul
(13) |
Aug
(7) |
Sep
(5) |
Oct
(74) |
Nov
(404) |
Dec
(14) |
---|---|---|---|---|---|---|---|---|---|---|---|---|
2006 |
Jan
(10) |
Feb
(26) |
Mar
(64) |
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/Runtime/Resource/Loader In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv21354/src/Adapdev.NVelocity/Runtime/Resource/Loader Removed Files: FileResourceLoader.cs ResourceLoader.cs ResourceLoaderFactory.cs ResourceLocator.cs Log Message: --- ResourceLocator.cs DELETED --- --- ResourceLoader.cs DELETED --- --- FileResourceLoader.cs DELETED --- --- ResourceLoaderFactory.cs DELETED --- |
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/Runtime/Parser/Node In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv21354/src/Adapdev.NVelocity/Runtime/Parser/Node Removed Files: ASTIfStatement.cs ASTIncludeStatement.cs ASTIntegerRange.cs ASTLENode.cs ASTLTNode.cs ASTMethod.cs ASTModNode.cs ASTMulNode.cs ASTNENode.cs ASTNotNode.cs ASTNumberLiteral.cs ASTObjectArray.cs ASTOrNode.cs ASTParameters.cs ASTReference.cs ASTSetDirective.cs ASTStringLiteral.cs ASTSubtractNode.cs ASTText.cs ASTTrue.cs ASTVariable.cs ASTWord.cs ASTprocess.cs AbstractExecutor.cs BooleanPropertyExecutor.cs GetExecutor.cs INode.cs NodeUtils.cs ParserVisitor.cs PropertyExecutor.cs SimpleNode.cs Log Message: --- ASTTrue.cs DELETED --- --- ASTObjectArray.cs DELETED --- --- AbstractExecutor.cs DELETED --- --- ASTMulNode.cs DELETED --- --- NodeUtils.cs DELETED --- --- ASTWord.cs DELETED --- --- ASTStringLiteral.cs DELETED --- --- ASTNENode.cs DELETED --- --- ASTReference.cs DELETED --- --- ASTNotNode.cs DELETED --- --- ASTText.cs DELETED --- --- ASTIfStatement.cs DELETED --- --- ParserVisitor.cs DELETED --- --- BooleanPropertyExecutor.cs DELETED --- --- ASTprocess.cs DELETED --- --- ASTMethod.cs DELETED --- --- ASTSetDirective.cs DELETED --- --- ASTIntegerRange.cs DELETED --- --- ASTModNode.cs DELETED --- --- PropertyExecutor.cs DELETED --- --- ASTVariable.cs DELETED --- --- ASTLTNode.cs DELETED --- --- INode.cs DELETED --- --- ASTParameters.cs DELETED --- --- ASTIncludeStatement.cs DELETED --- --- ASTLENode.cs DELETED --- --- ASTOrNode.cs DELETED --- --- ASTSubtractNode.cs DELETED --- --- SimpleNode.cs DELETED --- --- GetExecutor.cs DELETED --- --- ASTNumberLiteral.cs DELETED --- |
From: Sean M. <int...@us...> - 2005-11-16 05:41:34
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/Util/Introspection In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv21354/src/Adapdev.NVelocity/Util/Introspection Removed Files: AmbiguousException.cs ClassMap.cs IntrospectionCacheData.cs Introspector.cs IntrospectorBase.cs MethodMap.cs Twonk.cs Log Message: --- MethodMap.cs DELETED --- --- AmbiguousException.cs DELETED --- --- Introspector.cs DELETED --- --- Twonk.cs DELETED --- --- IntrospectorBase.cs DELETED --- --- ClassMap.cs DELETED --- --- IntrospectionCacheData.cs DELETED --- |
From: Sean M. <int...@us...> - 2005-11-16 05:41:34
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/Tool In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv21354/src/Adapdev.NVelocity/Tool Removed Files: DataInfo.cs IToolInfo.cs ToolLoader.cs Log Message: --- ToolLoader.cs DELETED --- --- IToolInfo.cs DELETED --- --- DataInfo.cs DELETED --- |
From: Sean M. <int...@us...> - 2005-11-16 05:41:34
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/Runtime/Resource In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv21354/src/Adapdev.NVelocity/Runtime/Resource Removed Files: ContentResource.cs Resource.cs ResourceCache.cs ResourceCacheImpl.cs ResourceFactory.cs ResourceManager.cs ResourceManagerImpl.cs Log Message: --- ResourceFactory.cs DELETED --- --- ContentResource.cs DELETED --- --- ResourceCacheImpl.cs DELETED --- --- ResourceCache.cs DELETED --- --- Resource.cs DELETED --- --- ResourceManager.cs DELETED --- --- ResourceManagerImpl.cs DELETED --- |
From: Sean M. <int...@us...> - 2005-11-16 05:41:31
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/Util In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv21354/src/Adapdev.NVelocity/Util Removed Files: Iterator.cs SimplePool.cs StringUtils.cs Log Message: --- StringUtils.cs DELETED --- --- SimplePool.cs DELETED --- --- Iterator.cs DELETED --- |
From: Sean M. <int...@us...> - 2005-11-16 05:41:30
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/Runtime/Visitor In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv21354/src/Adapdev.NVelocity/Runtime/Visitor Removed Files: BaseVisitor.cs NodeViewMode.cs VMReferenceMungeVisitor.cs Log Message: --- NodeViewMode.cs DELETED --- --- VMReferenceMungeVisitor.cs DELETED --- --- BaseVisitor.cs DELETED --- |
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.Cache In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv19977/src/Adapdev.Cache Added Files: AbstractCache.cs Adapdev.Cache.csproj CacheItem.cs CacheItemCollection.cs CacheItemDictionary.cs CacheItemEnumerator.cs CacheManager.cs CacheStats.cs CacheType.cs CacheUtil.cs FileCache.cs ICache.cs ICacheItem.cs ICacheStats.cs ImmutableInMemoryCache.cs MutableInMemoryCache.cs SerializedCacheItem.cs SqlServerCache.cs TypeKey.cs Log Message: Reposting to the repository after it got hosed --- NEW FILE: TypeKey.cs --- using System; namespace Adapdev.Cache { /// <summary> /// Summary description for TypeKey. /// </summary> internal class TypeKey { public static string Build(Type t, string key) { return t.FullName + Separator + key; } public static string GetTypeName(string typekey) { return typekey.Substring(0, typekey.IndexOf(Separator)); } public static Type GetType(string typekey) { return Type.GetType(GetTypeName(typekey)); } public static string GetKey(string typekey) { return typekey.Substring(typekey.IndexOf(Separator), typekey.Length); } public static string Separator { get{return "---";} } } } --- NEW FILE: AbstractCache.cs --- using System; using Adapdev; namespace Adapdev.Cache { using System.Collections; using System.Timers; using Adapdev.Cache.Scavengers; /// <summary> /// Summary description for AbstractCache. /// </summary> public abstract class AbstractCache : LongLivingMarshalByRefObject, ICache { protected ArrayList _timers = new ArrayList(); protected ArrayList _scavengers = new ArrayList(); #region ICache Members public void Add(int key, object o) { this.Add(key.ToString(), o); } public void Remove(Type t, int key) { this.Remove(t, key.ToString()); } public object Get(Type t, int key) { return this.Get(t, key.ToString()); } public CacheItem GetCacheItem(Type t, int key) { return this.GetCacheItem(t, key.ToString()); } public bool Contains(Type t, int key) { return this.Contains(t, key.ToString()); } public void Scavenge(Adapdev.Cache.Scavengers.IScavenger scavenger) { scavenger.Scavenge(this); } public void Copy(ICache cache) { CacheUtil.Copy(cache, this); } public abstract void Add(string key, object o); public abstract void Clear(); public abstract bool Contains(Type t, string key); public abstract int Count{get;} public abstract CacheItem[] Entries{get;} public abstract object Get(Type t, string key); public abstract CacheItem GetCacheItem(Type t, string key); public abstract void Populate(); public abstract void Remove(Type t, string key); #endregion } } --- NEW FILE: CacheItem.cs --- using System; using Adapdev; namespace Adapdev.Cache { /// <summary> /// Summary description for CacheItem. /// </summary> /// [Serializable] public class CacheItem : ICacheItem { protected object _object = null; protected string _key = String.Empty; protected int _ordinal = 0; protected DateTime _created; protected Type _objectType = null; public CacheItem(string key, object o) { this._key = key; this._object = o; this._created = DateTime.Now; this._objectType = o.GetType(); } public DateTime Created { get{return this._created;} } public Type ObjectType { get{return this._objectType;} } public virtual object Object { get{return this._object;} } public string Key { get{return this._key;} } public string TypeKey { get{return Adapdev.Cache.TypeKey.Build(this.ObjectType, this.Key);} } public int Ordinal { get{return this._ordinal;} set{this._ordinal = value;} } public override string ToString() { return Adapdev.Text.StringUtil.ToString(this); } } } --- NEW FILE: CacheManager.cs --- using System; namespace Adapdev.Cache { /// <summary> /// Summary description for CacheManager. /// </summary> public class CacheManager { private static ICache _cache = null; static CacheManager() { } public static ICache Cache { get { if(_cache == null) _cache = new ImmutableInMemoryCache(); return _cache; } set { if(_cache != null) { _cache.Clear(); } _cache = value; } } public static void SetCache(CacheType cacheType, bool copyExisting) { ICache cache = null; switch(cacheType) { case CacheType.File: cache = new FileCache(); if(copyExisting) cache.Copy(Cache); Cache = cache; break; case CacheType.ImmutableInMemory: cache = new ImmutableInMemoryCache(); if(copyExisting) cache.Copy(Cache); Cache = cache; break; case CacheType.MutableInMemory: cache = new MutableInMemoryCache(); if(copyExisting) cache.Copy(Cache); Cache = cache; break; default: break; } } public static void SetCache(CacheType cacheType) { SetCache(cacheType, true); } } } --- NEW FILE: ICacheStats.cs --- namespace Adapdev.Cache { /// <summary> /// Summary description for ICacheStats. /// </summary> public interface ICacheStats { int HitRate { get; } int MissRate { get; } long InsertTime { get; } long RetrieveTime { get; } } } --- NEW FILE: MutableInMemoryCache.cs --- using System; using System.Collections; using Adapdev.Serialization; namespace Adapdev.Cache { /// <summary> /// Summary description for ReadOnlyInMemoryCache. /// </summary> public class MutableInMemoryCache : AbstractCache { private CacheItemDictionary _hashtable = new CacheItemDictionary(); private int _ordinal = 0; public MutableInMemoryCache() { } #region ICache Members public override void Add(string key, object o) { CacheItem c = new CacheItem(key, o); c.Ordinal = ++this._ordinal; this._hashtable[TypeKey.Build(o.GetType(), key)] = c; } public override void Remove(Type t, string key) { this._hashtable.Remove(TypeKey.Build(t, key)); } public override object Get(Type t, string key) { return (this._hashtable[TypeKey.Build(t, key)] as CacheItem).Object; } public override CacheItem GetCacheItem(Type t, string key) { return this._hashtable[TypeKey.Build(t, key)] as CacheItem; } public override void Clear() { this._hashtable.Clear(); } public override bool Contains(Type t, string key) { return this._hashtable.Contains(TypeKey.Build(t, key)); } public override int Count { get { return this._hashtable.Count; } } public override CacheItem[] Entries { get { CacheItem[] items = new CacheItem[this._hashtable.Count]; this._hashtable.Values.CopyTo(items, 0); return items; } } public override void Populate() { } #endregion } } --- NEW FILE: CacheStats.cs --- using System; using Adapdev.Diagnostics; namespace Adapdev.Cache { using System.Text; using Adapdev.Cache.Scavengers; /// <summary> /// Summary description for CacheStats. /// </summary> public class CacheStats : ICache { private ICache _cache = null; private double _retrieveTime; private double _retrieveTimeAvg; private int _retrieved; private double _insertTimeAvg; private double _insertTime; private double _inserted; private int _hitCount; private int _missCount; private readonly IPerfTimer timer = PerfTimerFactory.GetPerfTimer(PerfTimerType.HIRESSECONDS); public CacheStats(ICache cache) { this._cache = cache; } #region ICache Members public void Add(string key, object o) { timer.Start(); this._cache.Add(key, o); timer.Stop(); this._insertTime = timer.Duration; this._insertTimeAvg += timer.Duration; this._inserted++; } public void Add(int key, object o) { this.Add(key.ToString(), o); } public void Remove(Type t, int key) { this.Remove(t, key.ToString()); } public void Remove(Type t, string key) { this._cache.Remove(t, key); } public object Get(Type t, int key) { return this.Get(t, key.ToString()); } public object Get(Type t, string key) { timer.Start(); object o = this._cache.Get(t, key); timer.Stop(); this._retrieveTime = timer.Duration; this._retrieveTimeAvg += timer.Duration; this._retrieved++; if(o == null) this._missCount++; else this._hitCount++; return o; } public CacheItem GetCacheItem(Type t, string key) { return this._cache.GetCacheItem(t, key); } public CacheItem GetCacheItem(Type t, int key) { return this._cache.GetCacheItem(t, key); } public void Clear() { this._cache.Clear(); this._hitCount = 0; this._inserted = 0; this._insertTime = 0; this._insertTimeAvg = 0; this._missCount = 0; this._retrieved = 0; this._retrieveTime = 0; this._retrieveTimeAvg = 0; } public int Count { get { return this._cache.Count; } } public bool Contains(Type t, string key) { return this._cache.Contains(t, key); } public bool Contains(Type t, int key) { return this._cache.Contains(t, key); } public void Scavenge(Adapdev.Cache.Scavengers.IScavenger scavenger) { this._cache.Scavenge(scavenger); } public CacheItem[] Entries { get { return this._cache.Entries; } } public void Populate() { this._cache.Populate(); } public void Copy(ICache cache) { this._cache.Copy(cache); } #endregion public double RetrieveTime { get{return this._retrieveTime;} } public double InsertTime { get{return this._insertTime;} } public double AverageRetrieveTime { get{return this._retrieveTimeAvg / this._retrieved;} } public double AverageInsertTime { get{return this._insertTimeAvg / this._inserted;} } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.AppendFormat("Insert Time: {0}\r\n", this.InsertTime); sb.AppendFormat("Avg. Insert Time: {0}\r\n", this.AverageInsertTime); sb.AppendFormat("Retrieve Time: {0}\r\n", this.RetrieveTime); sb.AppendFormat("Avg. Retrieve Time: {0}\r\n", this.AverageRetrieveTime); sb.AppendFormat("Hit Count: {0}\r\n", this.HitCount); sb.AppendFormat("Miss Count: {0}\r\n", this.MissCount); return sb.ToString(); } public ICache Cache { get{return this._cache;} } public int HitCount { get{return this._hitCount;} } public int MissCount { get{return this._missCount;} } public void Scavenge(IScavenger scavenger, TimeSpan timespan) { this.Scavenge(scavenger, timespan); } } } --- NEW FILE: SqlServerCache.cs --- namespace Adapdev.Cache { /// <summary> /// Summary description for SqlServerCache. /// </summary> public class SqlServerCache : ICache { public SqlServerCache() { // // TODO: Add constructor logic here // } #region ICache Members public void Add(string id, object item) { // TODO: Add SqlServerCache.Add implementation } public void Remove(string id) { // TODO: Add SqlServerCache.Remove implementation } public object Get(string id) { // TODO: Add SqlServerCache.Get implementation return null; } public CacheMetaData GetMetaData(string id) { return null; } public CacheMetaDataDictionary GetMetaData() { return null; } public void Clear() { // TODO: Add SqlServerCache.Clear implementation } public int Count { get { // TODO: Add SqlServerCache.Count getter implementation return 0; } } public void SetScavenger(IScavenger scavenger) { // TODO: Add SqlServerCache.SetScavenger implementation } public bool Contains(string id) { return false; } #endregion } } --- NEW FILE: SerializedCacheItem.cs --- using System; using Adapdev.Serialization; namespace Adapdev.Cache { /// <summary> /// Summary description for SerializedCacheItem. /// </summary> /// [Serializable] public class SerializedCacheItem : CacheItem { public SerializedCacheItem(string key, object o) : base(key, o) { this._key = key; this._object = Serializer.SerializeToBinary(o); this._created = DateTime.Now; this._objectType = o.GetType(); } public override object Object { get { return Serializer.DeserializeFromBinary(this._objectType, this._object as byte[]); } } public byte[] BinaryObject { get{return this._object as byte[];} } } } --- NEW FILE: CacheType.cs --- using System; namespace Adapdev.Cache { /// <summary> /// Summary description for CacheType. /// </summary> public enum CacheType { File, ImmutableInMemory, MutableInMemory } } --- NEW FILE: CacheItemCollection.cs --- /****************************************** * Auto-generated by Codus * 4/20/2005 11:18:21 AM ******************************************/ using System; using System.Collections; namespace Adapdev.Cache { [Serializable()] public class CacheItemCollection : CollectionBase { public CacheItemCollection() { } public CacheItemCollection(IList value) { this.AddRange(value); } public CacheItemCollection(CacheItem[] value) { this.AddRange(value); } public CacheItem this[int index] { get { return ((CacheItem)(List[index])); } set { List[index] = value; } } public int Add(CacheItem value) { return List.Add(value); } public void AddRange(CacheItem[] value) { for (int i = 0; (i < value.Length); i = (i + 1)) { this.Add(value[i]); } } public void AddRange(IList value) { for (int i = 0; (i < value.Count); i = (i + 1)) { this.Add((CacheItem)value[i]); } } public bool Contains(CacheItem value) { return List.Contains(value); } public void CopyTo(CacheItem[] array, int index) { List.CopyTo(array, index); } public int IndexOf(CacheItem value) { return List.IndexOf(value); } public void Insert(int index, CacheItem value) { List.Insert(index, value); } public new CacheItemEnumerator GetEnumerator() { return new CacheItemEnumerator(this); } public void Remove(CacheItem value) { List.Remove(value); } } } --- NEW FILE: Adapdev.Cache.csproj --- <VisualStudioProject> <CSHARP ProjectType = "Local" ProductVersion = "7.10.3077" SchemaVersion = "2.0" ProjectGuid = "{84F894AC-EFD7-4342-B2A5-CF3EF80E0B1C}" > <Build> <Settings ApplicationIcon = "" AssemblyKeyContainerName = "" AssemblyName = "Adapdev.Cache" AssemblyOriginatorKeyFile = "" DefaultClientScript = "JScript" DefaultHTMLPageLayout = "Grid" DefaultTargetSchema = "IE50" DelaySign = "false" OutputType = "Library" PreBuildEvent = "" PostBuildEvent = "" RootNamespace = "Adapdev.Cache" RunPostBuildEvent = "OnBuildSuccess" StartupObject = "" > <Config Name = "Debug" AllowUnsafeBlocks = "false" BaseAddress = "285212672" CheckForOverflowUnderflow = "false" ConfigurationOverrideFile = "" DefineConstants = "DEBUG;TRACE" DocumentationFile = "" DebugSymbols = "true" FileAlignment = "4096" IncrementalBuild = "false" NoStdLib = "false" NoWarn = "" Optimize = "false" OutputPath = "bin\Debug\" RegisterForComInterop = "false" RemoveIntegerChecks = "false" TreatWarningsAsErrors = "false" WarningLevel = "4" /> <Config Name = "Release" AllowUnsafeBlocks = "false" BaseAddress = "285212672" CheckForOverflowUnderflow = "false" ConfigurationOverrideFile = "" DefineConstants = "TRACE" DocumentationFile = "" DebugSymbols = "false" FileAlignment = "4096" IncrementalBuild = "false" NoStdLib = "false" NoWarn = "" Optimize = "true" OutputPath = "bin\Release\" RegisterForComInterop = "false" RemoveIntegerChecks = "false" TreatWarningsAsErrors = "false" WarningLevel = "4" /> </Settings> <References> <Reference Name = "System" AssemblyName = "System" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.dll" /> <Reference Name = "System.Data" AssemblyName = "System.Data" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.Data.dll" /> <Reference Name = "System.XML" AssemblyName = "System.Xml" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.XML.dll" /> <Reference Name = "Adapdev" Project = "{CC30A321-2569-4B1F-8E1A-781B5509B56D}" Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" /> <Reference Name = "log4net" AssemblyName = "log4net" HintPath = "..\..\lib\log4net.dll" /> </References> </Build> <Files> <Include> <File RelPath = "AbstractCache.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "AdapdevAssemblyInfo.cs" Link = "..\AdapdevAssemblyInfo.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "CacheItem.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "CacheItemCollection.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "CacheItemDictionary.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "CacheItemEnumerator.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "CacheManager.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "CacheStats.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "CacheType.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "CacheUtil.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "FileCache.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "ICache.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "ICacheItem.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "ImmutableInMemoryCache.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "MutableInMemoryCache.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "SerializedCacheItem.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "TypeKey.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Scavengers\AbsoluteExpirationScavenger.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Scavengers\GreaterThanOrdinalScavenger.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Scavengers\IScavenger.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Scavengers\LIFONumberScavenger.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Scavengers\SlidingExpirationScavenger.cs" SubType = "Code" BuildAction = "Compile" /> </Include> </Files> </CSHARP> </VisualStudioProject> --- NEW FILE: CacheUtil.cs --- using System; namespace Adapdev.Cache { /// <summary> /// Summary description for CacheUtil. /// </summary> public class CacheUtil { private CacheUtil(){} public static void Copy(ICache source, ICache target) { foreach(CacheItem item in source.Entries) { target.Add(item.Key, item.Object); } } } } --- NEW FILE: CacheItemEnumerator.cs --- /****************************************** * Auto-generated by Codus * 4/20/2005 11:18:21 AM ******************************************/ using System; using System.Collections; namespace Adapdev.Cache { public class CacheItemEnumerator : IEnumerator { private IEnumerator baseEnumerator; private IEnumerable temp; public CacheItemEnumerator(CacheItemCollection mappings) { this.temp = ((IEnumerable)(mappings)); this.baseEnumerator = temp.GetEnumerator(); } public CacheItemEnumerator(CacheItemDictionary mappings) { this.temp = ((IEnumerable)(mappings)); this.baseEnumerator = temp.GetEnumerator(); } public CacheItem Current { get { return ((CacheItem)(baseEnumerator.Current)); } } object IEnumerator.Current { get { return baseEnumerator.Current; } } public bool MoveNext() { return baseEnumerator.MoveNext(); } bool IEnumerator.MoveNext() { return baseEnumerator.MoveNext(); } public void Reset() { baseEnumerator.Reset(); } void IEnumerator.Reset() { baseEnumerator.Reset(); } } } --- NEW FILE: FileCache.cs --- using System; using System.Collections; using System.IO; using Adapdev.Serialization; namespace Adapdev.Cache { /// <summary> /// Summary description for FileCache. /// </summary> public class FileCache : AbstractCache { private string _folderPath = String.Empty; private CacheItemDictionary _items = new CacheItemDictionary(); private static int _ordinal = 0; public FileCache() { this._folderPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "filecache"); if(!Directory.Exists(this._folderPath)) Directory.CreateDirectory(this._folderPath); FileCache._ordinal = this.Count; } public FileCache(string folderName) { this._folderPath = folderName; this._folderPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "filecache"); if(!Directory.Exists(this._folderPath)) Directory.CreateDirectory(this._folderPath); FileCache._ordinal = this.Count; } private string GetFileName(Type t, string key) { return TypeKey.Build(t, key) + ".cache"; } private string GetFullFileName(Type t, string key) { return Path.Combine(this._folderPath, this.GetFileName(t, key)); } private string GetFileNameWithoutExtension(string fileName) { return fileName.Substring(0, fileName.LastIndexOf(".")); } #region ICache Members public override void Add(string key, object o) { SerializedCacheItem c = new SerializedCacheItem(key, o); c.Ordinal = ++FileCache._ordinal; this._items[TypeKey.Build(o.GetType(), key)] = c; Serializer.SerializeToBinary(o, Path.Combine(this._folderPath, this.GetFileName(o.GetType(), key))); } public override void Remove(Type t, string key) { File.Delete(Path.Combine(this._folderPath, this.GetFileName(t, key))); this._items.Remove(TypeKey.Build(t, key)); } public override object Get(Type t, string key) { string typekey = TypeKey.Build(t, key); if(this._items.Contains(typekey)) { return (this._items[typekey] as SerializedCacheItem).Object; } else if(this.Contains(t, key)) { return Serializer.DeserializeFromBinary(t, this.GetFileName(t, key)); } else { return null; } } public override CacheItem GetCacheItem(Type t, string key) { return this._items[TypeKey.Build(t, key)] as SerializedCacheItem; } public override void Clear() { if(Directory.Exists(this._folderPath)) { Directory.Delete(this._folderPath, true); Directory.CreateDirectory(this._folderPath); this._items.Clear(); } } public override int Count { get { return Directory.GetFiles(this._folderPath).Length; } } public override bool Contains(Type t, string key) { return File.Exists(this.GetFullFileName(t, key)); } public override CacheItem[] Entries { get { CacheItem[] items = new CacheItem[this._items.Count]; this._items.Values.CopyTo(items, 0); return items; } } public override void Populate() { foreach(FileInfo f in new DirectoryInfo(this._folderPath).GetFiles()) { string fileName = this.GetFileNameWithoutExtension(f.Name); SerializedCacheItem c = new SerializedCacheItem(TypeKey.GetKey(fileName), Serializer.DeserializeFromBinary(TypeKey.GetType(fileName), f.FullName)); c.Ordinal = FileCache._ordinal++; this._items[f.Name] = c; } } #endregion } } --- NEW FILE: ICache.cs --- using System; using System.Collections; using Adapdev.Cache.Scavengers; namespace Adapdev.Cache { /// <summary> /// Summary description for ICache. /// </summary> public interface ICache { void Add(string key, object o); void Add(int key, object o); void Remove(Type t, int key); void Remove(Type t, string key); object Get(Type t, int key); object Get(Type t, string key); CacheItem GetCacheItem(Type t, string key); CacheItem GetCacheItem(Type t, int key); void Clear(); int Count{get;} bool Contains(Type t, string key); bool Contains(Type t, int key); void Scavenge(IScavenger scavenger); CacheItem[] Entries{get;} void Populate(); void Copy(ICache cache); } } --- NEW FILE: ImmutableInMemoryCache.cs --- using System; using System.Collections; using Adapdev.Serialization; namespace Adapdev.Cache { /// <summary> /// Summary description for ReadOnlyInMemoryCache. /// </summary> public class ImmutableInMemoryCache : AbstractCache { private CacheItemDictionary _hashtable = new CacheItemDictionary(); private int _ordinal = 0; public ImmutableInMemoryCache() { } #region ICache Members public override void Add(string key, object o) { SerializedCacheItem c = new SerializedCacheItem(key, o); c.Ordinal = ++this._ordinal; this._hashtable[TypeKey.Build(o.GetType(), key)] = c; } public override void Remove(Type t, string key) { this._hashtable.Remove(TypeKey.Build(t, key)); } public override object Get(Type t, string key) { return (this._hashtable[TypeKey.Build(t, key)] as CacheItem).Object; } public override CacheItem GetCacheItem(Type t, string key) { return this._hashtable[TypeKey.Build(t, key)] as CacheItem; } public override void Clear() { this._hashtable.Clear(); } public override bool Contains(Type t, string key) { return this._hashtable.Contains(TypeKey.Build(t, key)); } public override int Count { get { return this._hashtable.Count; } } public override CacheItem[] Entries { get { CacheItem[] items = new CacheItem[this._hashtable.Count]; this._hashtable.Values.CopyTo(items, 0); return items; } } public override void Populate() { } #endregion } } --- NEW FILE: ICacheItem.cs --- using System; namespace Adapdev.Cache { /// <summary> /// Summary description for ICacheItem. /// </summary> public interface ICacheItem { DateTime Created{get;} Type ObjectType{get;} object Object{get;} string Key{get;} int Ordinal{get;set;} } } --- NEW FILE: CacheItemDictionary.cs --- using System; using System.Collections; namespace Adapdev.Cache { public class CacheItemDictionary : DictionaryBase { public CacheItem this[ object key ] { get { return( (CacheItem) Dictionary[key] ); } set { Dictionary[key] = value; } } public ICollection Keys { get { return( Dictionary.Keys ); } } public ICollection Values { get { return( Dictionary.Values ); } } public void Add( String key, String value ) { Dictionary.Add( key, value ); } public bool Contains( String key ) { return( Dictionary.Contains( key ) ); } public void Remove( String key ) { Dictionary.Remove( key ); } } } |
From: Sean M. <int...@us...> - 2005-11-16 05:33:40
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev/IO In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv19977/src/Adapdev/IO Added Files: FileUtil.cs FileWatcher.cs Log Message: Reposting to the repository after it got hosed --- NEW FILE: FileWatcher.cs --- // Original Copyright (c) 2004 Brad Vincent - http://www.codeproject.com/csharp/FileWatcherWrapper.asp #region Modified Copyright / License Information /* Copyright 2004 - 2005 Adapdev Technologies, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ============================ Author Log ============================ III Full Name SMM Sean McCormack (Adapdev) ============================ Change Log ============================ III MMDDYY Change SMM 121604 Added IncludeSubDirectories property and functionality */ #endregion using System; using System.IO; namespace Adapdev.IO { /// <summary> /// arguments sent through when an event is fired /// </summary> public class FileWatcherEventArgs : EventArgs { private string mFileName = ""; private string mPath = ""; private string mOldPath = ""; private string mOldName = ""; private FileWatcher.FileWatcherChangeType mChangeType; public FileWatcherEventArgs(string fileName, string path, string oldPath, string oldName, FileWatcher.FileWatcherChangeType changeType) { mFileName = fileName; mPath = path; mOldName = oldName; mOldPath = oldPath; mChangeType = changeType; } public string FileName { get { return mFileName; } } public string OldFileName { get { return mOldName; } } public string Path { get { return mPath; } } public string OldPath { get { return mOldPath; } } public FileWatcher.FileWatcherChangeType ChangeType { get { return mChangeType; } } } /// <summary> /// monitors a folder for file system changes /// </summary> public class FileWatcher { #region enums, constants & fields public enum FileWatcherChangeType { FileAdded, FileDeleted, FileRenamed, Filechanged } private string mPath = "."; //path to watch private string mFilter = "*.*"; //filter to watch private FileSystemWatcher mFsw = new FileSystemWatcher(); private string mCurrentFileName = ""; private string mCurrentPath = ""; private string mCurrentOldPath = ""; private string mCurrentOldName = ""; private bool includeSub = false; private FileWatcherChangeType mChangeType; #endregion #region events and delegates public delegate void ChangedEventHandler(object sender, FileWatcherEventArgs args); public event ChangedEventHandler Changed; #endregion #region constructors public FileWatcher() { CreateFileWatcher(); } public FileWatcher(string path, string filter) : this() { mPath = path; mFilter = filter; } public FileWatcher(string path) : this() { mPath = path; } #endregion #region Properties public string Path { get { return mPath; } set { mPath = value; } } public string Filter { get { return mFilter; } set { mFilter = value; } } public bool isStarted { get { return mFsw.EnableRaisingEvents; } } public string CurrentFileName { get { return mCurrentFileName; } } public string CurrentOldFileName { get { return mCurrentOldName; } } public string CurrentPath { get { return mCurrentPath; } } public string CurrentOldPath { get { return mCurrentOldPath; } } public FileWatcher.FileWatcherChangeType CurrentChangeType { get { return mChangeType; } } public bool IncludeSubDirectories { get { return includeSub; } set { includeSub = value; } } #endregion #region public methods /// <summary> /// start the watcher for a specific folder with a specific filter /// </summary> public void StartWatcher() { mFsw.Path = mPath; if(this.includeSub) mFsw.IncludeSubdirectories = true; else mFsw.IncludeSubdirectories = false; mFsw.Filter = mFilter; mFsw.EnableRaisingEvents = true; } /// <summary> /// to stop the folder watcher from raising events /// </summary> public void StopWatcher() { mFsw.EnableRaisingEvents = false; } #endregion #region file watcher engine /// <summary> /// the heart of the file watcher engine /// </summary> private void CreateFileWatcher() { mFsw = new FileSystemWatcher(mPath,mFilter); mFsw.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.DirectoryName | NotifyFilters.FileName; mFsw.Changed += new FileSystemEventHandler(OnChanged); mFsw.Created += new FileSystemEventHandler(OnCreated); mFsw.Deleted += new FileSystemEventHandler(OnDeleted); mFsw.Renamed += new RenamedEventHandler(OnRenamed); } protected virtual void OnChanged(FileWatcherEventArgs e) { //raises the event to say that a file has changed Changed(this,e); } #endregion #region private file-change methods private void OnCreated(object source, FileSystemEventArgs args) { mCurrentFileName = args.Name; mCurrentPath = args.FullPath; mCurrentOldName = ""; mCurrentOldPath = ""; mChangeType = FileWatcherChangeType.FileAdded; OnChanged(new FileWatcherEventArgs(mCurrentFileName,mCurrentPath,mCurrentOldPath,mCurrentOldName,mChangeType)); } private void OnRenamed(object source, RenamedEventArgs args) { mCurrentFileName = args.Name; mCurrentPath = args.FullPath; mCurrentOldName = args.OldFullPath; mCurrentOldPath = args.OldName; mChangeType = FileWatcherChangeType.FileRenamed; OnChanged(new FileWatcherEventArgs(mCurrentFileName,mCurrentPath,mCurrentOldPath,mCurrentOldName,mChangeType)); } private void OnDeleted(object source, FileSystemEventArgs args) { mCurrentFileName = args.Name; mCurrentPath = args.FullPath; mCurrentOldName = ""; mCurrentOldPath = ""; mChangeType = FileWatcherChangeType.FileDeleted; OnChanged(new FileWatcherEventArgs(mCurrentFileName,mCurrentPath,mCurrentOldPath,mCurrentOldName,mChangeType)); } private void OnChanged(object source, FileSystemEventArgs args) { mCurrentFileName = args.Name; mCurrentPath = args.FullPath; mCurrentOldName = ""; mCurrentOldPath = ""; mChangeType = FileWatcherChangeType.Filechanged; OnChanged(new FileWatcherEventArgs(mCurrentFileName,mCurrentPath,mCurrentOldPath,mCurrentOldName,mChangeType)); } #endregion } } --- NEW FILE: FileUtil.cs --- #region Copyright / License Information /* Copyright 2004 - 2005 Adapdev Technologies, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ============================ Author Log ============================ III Full Name SMM Sean McCormack (Adapdev) ============================ Change Log ============================ III MMDDYY Change */ #endregion namespace Adapdev.IO { using System; using System.IO; public class FileUtil { private FileUtil() { } public static void CreateFile(string filePath, string content) { FileStream fs = null; StreamWriter sw = null; try { if (!Directory.Exists(Path.GetDirectoryName(filePath))) { Directory.CreateDirectory(Path.GetDirectoryName(filePath)); } Console.WriteLine("creating file: " + filePath); fs = new FileStream(filePath, FileMode.Create); sw = new StreamWriter(fs); sw.Write(content); } catch (Exception e) { Console.WriteLine("FileUtil::CreateFile " + e.Message); } finally { if (fs != null) { sw.Close(); fs.Close(); } } } public static string ReadFile(string filePath) { StreamReader sr = null; string content = ""; try { sr = new StreamReader(filePath); content = sr.ReadToEnd(); } catch (Exception e) { } finally { if (sr != null) { sr.Close(); } } return content; } } } |
Update of /cvsroot/adapdev/Adapdev/src/Adapdev/Scheduling/Timer In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv19977/src/Adapdev/Scheduling/Timer Added Files: EventStorage.cs MethodCall.cs ReportTimer.cs Schedule.cs ScheduleFilter.cs ScheduleTimer.cs ScheduledItems.cs TimerJob.cs Log Message: Reposting to the repository after it got hosed --- NEW FILE: ScheduleFilter.cs --- // Original Copyright (c) 2004 Andy Brummer. All Rights Reserved. - http://www.codeproject.com/dotnet/ABTransClockArticle.asp #region Modified Copyright / License Information /* Copyright 2004 - 2005 Adapdev Technologies, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ============================ Author Log ============================ III Full Name SMM Sean McCormack (Adapdev) ============================ Change Log ============================ III MMDDYY Change */ #endregion using System; using System.Collections; namespace Adapdev.Scheduling.Timer { /// <summary> /// This is an empty filter that does not filter any of the events. /// </summary> public class Filter : IResultFilter { public static IResultFilter Empty = new Filter(); private Filter() {} public void FilterResultsInInterval(DateTime Start, DateTime End, ArrayList List) { if (List == null) return; List.Sort(); } } /// <summary> /// This causes only the first event of the interval to be counted. /// </summary> public class FirstEventFilter : IResultFilter { public static IResultFilter Filter = new FirstEventFilter(); private FirstEventFilter() {} public void FilterResultsInInterval(DateTime Start, DateTime End, ArrayList List) { if (List == null) return; if (List.Count < 2) return; List.Sort(); List.RemoveRange(1, List.Count-1); } } /// <summary> /// This causes only the last event of the interval to be counted. /// </summary> public class LastEventFilter : IResultFilter { public static IResultFilter Filter = new LastEventFilter(); private LastEventFilter() {} public void FilterResultsInInterval(DateTime Start, DateTime End, ArrayList List) { if (List == null) return; if (List.Count < 2) return; List.Sort(); List.RemoveRange(0, List.Count-1); } } } --- NEW FILE: Schedule.cs --- // Original Copyright (c) 2004 Andy Brummer. All Rights Reserved. - http://www.codeproject.com/dotnet/ABTransClockArticle.asp #region Modified Copyright / License Information /* Copyright 2004 - 2005 Adapdev Technologies, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ============================ Author Log ============================ III Full Name SMM Sean McCormack (Adapdev) ============================ Change Log ============================ III MMDDYY Change */ #endregion using System; using System.Collections; using System.Collections.Specialized; namespace Adapdev.Scheduling.Timer { /// <summary> /// There have been quite a few requests to allow scheduling of multiple delegates and method parameter data /// from the same timer. This class allows you to match the event with the time that it fired. I want to keep /// the same simple implementation of the EventQueue and interval classes since they can be reused elsewhere. /// The timer should be responsible for matching this data up. /// </summary> public class EventInstance : IComparable { public EventInstance(DateTime time, IScheduledItem scheduleItem, object data) { Time = time; ScheduleItem = scheduleItem; Data = data; } public DateTime Time; public IScheduledItem ScheduleItem; public object Data; public int CompareTo(object obj) { if (obj is EventInstance) return Time.CompareTo(((EventInstance)obj).Time); if (obj is DateTime) return Time.CompareTo((DateTime)obj); return 0; } } /// <summary> /// IScheduledItem represents a scheduled event. You can query it for the number of events that occur /// in a time interval and for the remaining interval before the next event. /// </summary> public interface IScheduledItem { /// <summary> /// Returns the times of the events that occur in the given time interval. The interval is closed /// at the start and open at the end so that intervals can be stacked without overlapping. /// </summary> /// <param name="Begin">The beginning of the interval</param> /// <param name="End">The end of the interval</param> /// <returns>All events >= Begin and < End </returns> void AddEventsInInterval(DateTime Begin, DateTime End, ArrayList List); /// <summary> /// Returns the next run time of the scheduled item. Optionally excludes the starting time. /// </summary> /// <param name="time">The starting time of the interval</param> /// <param name="IncludeStartTime">if true then the starting time is included in the query false, it is excluded.</param> /// <returns>The next execution time either on or after the starting time.</returns> DateTime NextRunTime(DateTime time, bool IncludeStartTime); } /// <summary> /// The event queue is a collection of scheduled items that represents the union of all child scheduled items. /// This is useful for events that occur every 10 minutes or at multiple intervals not covered by the simple /// scheduled items. /// </summary> public class EventQueue : IScheduledItem { public EventQueue() { _List = new ArrayList(); } /// <summary> /// Adds a ScheduledTime to the queue. /// </summary> /// <param name="time">The scheduled time to add</param> public void Add(IScheduledItem time) { _List.Add(time); } /// <summary> /// Clears the list of scheduled times. /// </summary> public void Clear() { _List.Clear(); } /// <summary> /// Adds the running time for all events in the list. /// </summary> /// <param name="Begin"></param> /// <param name="End"></param> /// <param name="List"></param> public void AddEventsInInterval(DateTime Begin, DateTime End, ArrayList List) { foreach(IScheduledItem st in _List) st.AddEventsInInterval(Begin, End, List); List.Sort(); } /// <summary> /// Returns the first time after the starting time for all events in the list. /// </summary> /// <param name="time"></param> /// <param name="AllowExact"></param> /// <returns></returns> public DateTime NextRunTime(DateTime time, bool AllowExact) { DateTime next = DateTime.MaxValue; //Get minimum datetime from the list. foreach(IScheduledItem st in _List) { DateTime Proposed = st.NextRunTime(time, AllowExact); next = (Proposed < next) ? Proposed : next; } return next; } private ArrayList _List; } } --- NEW FILE: ReportTimer.cs --- // Original Copyright (c) 2004 Andy Brummer. All Rights Reserved. - http://www.codeproject.com/dotnet/ABTransClockArticle.asp #region Modified Copyright / License Information /* Copyright 2004 - 2005 Adapdev Technologies, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ============================ Author Log ============================ III Full Name SMM Sean McCormack (Adapdev) ============================ Change Log ============================ III MMDDYY Change */ #endregion using System; namespace Adapdev.Scheduling.Timer { public class ReportEventArgs : EventArgs { public ReportEventArgs(DateTime Time, int reportNo) { EventTime = Time; ReportNo = reportNo; } public int ReportNo; public DateTime EventTime; } public delegate void ReportEventHandler(object sender, ReportEventArgs e); /// <summary> /// Summary description for ReportTimer. /// </summary> public class ReportTimer : ScheduleTimerBase { public void AddReportEvent(IScheduledItem Schedule, int reportNo) { if (Elapsed == null) throw new Exception("You must set elapsed before adding Events"); AddJob(new TimerJob(Schedule, new DelegateMethodCall(Handler, Elapsed, reportNo))); } public void AddAsyncReportEvent(IScheduledItem Schedule, int reportNo) { if (Elapsed == null) throw new Exception("You must set elapsed before adding Events"); TimerJob Event = new TimerJob(Schedule, new DelegateMethodCall(Handler, Elapsed, reportNo)); Event.SyncronizedEvent = false; AddJob(Event); } public event ReportEventHandler Elapsed; delegate void ConvertHandler(ReportEventHandler Handler, int ReportNo, object sender, DateTime time); static ConvertHandler Handler = new ConvertHandler(Converter); static void Converter(ReportEventHandler Handler, int ReportNo, object sender, DateTime time) { if (Handler == null) throw new ArgumentNullException("Handler"); if (sender == null) throw new ArgumentNullException("sender"); Handler(sender, new ReportEventArgs(time, ReportNo)); } } } --- NEW FILE: ScheduledItems.cs --- // Original Copyright (c) 2004 Andy Brummer. All Rights Reserved. - http://www.codeproject.com/dotnet/ABTransClockArticle.asp #region Modified Copyright / License Information /* Copyright 2004 - 2005 Adapdev Technologies, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ============================ Author Log ============================ III Full Name SMM Sean McCormack (Adapdev) ============================ Change Log ============================ III MMDDYY Change */ #endregion using System; using System.Collections; using System.Collections.Specialized; using System.Diagnostics; namespace Adapdev.Scheduling.Timer { public enum EventTimeBase { BySecond = 1, ByMinute = 2, Hourly = 3, Daily = 4, Weekly = 5, Monthly = 6, } /// <summary> /// This class represents a simple schedule. It can represent a repeating event that occurs anywhere from every /// second to once a month. It consists of an enumeration to mark the interval and an offset from that interval. /// For example new ScheduledTime(Hourly, new TimeSpan(0, 15, 0)) would represent an event that fired 15 minutes /// after the hour every hour. /// </summary> [Serializable] public class ScheduledTime : IScheduledItem { public ScheduledTime(EventTimeBase Base, TimeSpan Offset) { _Base = Base; _Offset = Offset; } /// <summary> /// intializes a simple scheduled time element from a pair of strings. /// Here are the supported formats /// /// BySecond - single integer representing the offset in ms /// ByMinute - A comma seperate list of integers representing the number of seconds and ms /// Hourly - A comma seperated list of integers representing the number of minutes, seconds and ms /// Daily - A time in hh:mm:ss AM/PM format /// Weekly - n, time where n represents an integer and time is a time in the Daily format /// Monthly - the same format as weekly. /// /// </summary> /// <param name="StrBase">A string representing the base enumeration for the scheduled time</param> /// <param name="StrOffset">A string representing the offset for the time.</param> public ScheduledTime(string StrBase, string StrOffset) { //TODO:Create an IScheduled time factory method. _Base = (EventTimeBase)Enum.Parse(typeof(EventTimeBase), StrBase, true); Init(StrOffset); } public int ArrayAccess(string[] Arr, int i) { if (i >= Arr.Length) return 0; return int.Parse(Arr[i]); } public void AddEventsInInterval(DateTime Begin, DateTime End, ArrayList List) { DateTime Next = NextRunTime(Begin, true); while (Next < End) { List.Add(Next); Next = IncInterval(Next); } } public DateTime NextRunTime(DateTime time, bool AllowExact) { DateTime NextRun = LastSyncForTime(time) + _Offset; if (NextRun == time && AllowExact) return time; if (NextRun > time) return NextRun; return IncInterval(NextRun); } public DateTime LastSyncForTime(DateTime time) { switch (_Base) { case EventTimeBase.BySecond: return new DateTime(time.Year, time.Month, time.Day, time.Hour, time.Minute, time.Second); case EventTimeBase.ByMinute: return new DateTime(time.Year, time.Month, time.Day, time.Hour, time.Minute, 0); case EventTimeBase.Hourly: return new DateTime(time.Year, time.Month, time.Day, time.Hour, 0, 0); case EventTimeBase.Daily: return new DateTime(time.Year, time.Month, time.Day); case EventTimeBase.Weekly: return (new DateTime(time.Year, time.Month, time.Day)).AddDays(-(int)time.DayOfWeek); case EventTimeBase.Monthly: return new DateTime(time.Year, time.Month, 1); } throw new Exception("Invalid base specified for timer."); } public DateTime IncInterval(DateTime Last) { switch (_Base) { case EventTimeBase.BySecond: return Last.AddSeconds(1); case EventTimeBase.ByMinute: return Last.AddMinutes(1); case EventTimeBase.Hourly: return Last.AddHours(1); case EventTimeBase.Daily: return Last.AddDays(1); case EventTimeBase.Weekly: return Last.AddDays(7); case EventTimeBase.Monthly: return Last.AddMonths(1); } throw new Exception("Invalid base specified for timer."); } private void Init(string StrOffset) { switch (_Base) { case EventTimeBase.BySecond: _Offset = new TimeSpan(0, 0, 0, 0, int.Parse(StrOffset)); break; case EventTimeBase.ByMinute: string[] ArrMinute = StrOffset.Split(','); _Offset = new TimeSpan(0, 0, 0, ArrayAccess(ArrMinute, 0), ArrayAccess(ArrMinute, 1)); break; case EventTimeBase.Hourly: string[] ArrHour = StrOffset.Split(','); _Offset = new TimeSpan(0, 0, ArrayAccess(ArrHour, 0), ArrayAccess(ArrHour, 1), ArrayAccess(ArrHour, 2)); break; case EventTimeBase.Daily: DateTime Daytime = DateTime.Parse(StrOffset); _Offset = new TimeSpan(0, Daytime.Hour, Daytime.Minute, Daytime.Second, Daytime.Millisecond); break; case EventTimeBase.Weekly: string[] ArrWeek = StrOffset.Split(','); if (ArrWeek.Length != 2) throw new Exception("Weekly offset must be in the format n, time where n is the day of the week starting with 0 for sunday"); DateTime WeekTime = DateTime.Parse(ArrWeek[1]); _Offset = new TimeSpan(int.Parse(ArrWeek[0]), WeekTime.Hour, WeekTime.Minute, WeekTime.Second, WeekTime.Millisecond); break; case EventTimeBase.Monthly: string[] ArrMonth = StrOffset.Split(','); if (ArrMonth.Length != 2) throw new Exception("Weekly offset must be in the format n, time where n is the day of the week starting with 0 for sunday"); DateTime MonthTime = DateTime.Parse(ArrMonth[1]); _Offset = new TimeSpan(int.Parse(ArrMonth[0]), MonthTime.Hour, MonthTime.Minute, MonthTime.Second, MonthTime.Millisecond); break; default: throw new Exception("Invalid base specified for timer."); } } private EventTimeBase _Base; private TimeSpan _Offset; } /// <summary> /// The simple interval represents the simple scheduling that .net supports natively. It consists of a start /// absolute time and an interval that is counted off from the start time. /// </summary> [Serializable] public class SimpleInterval : IScheduledItem { public SimpleInterval(DateTime StartTime, TimeSpan Interval) { _Interval = Interval; _StartTime = StartTime; _EndTime = DateTime.MaxValue; } public SimpleInterval(DateTime StartTime, TimeSpan Interval, int count) { _Interval = Interval; _StartTime = StartTime; _EndTime = StartTime + TimeSpan.FromTicks(Interval.Ticks*count); } public SimpleInterval(DateTime StartTime, TimeSpan Interval, DateTime EndTime) { _Interval = Interval; _StartTime = StartTime; _EndTime = EndTime; } public void AddEventsInInterval(DateTime Begin, DateTime End, ArrayList List) { if (End <= _StartTime) return; DateTime Next = NextRunTime(Begin, true); while (Next < End) { List.Add(Next); Next = NextRunTime(Next, false); } } public DateTime NextRunTime(DateTime time, bool AllowExact) { DateTime returnTime = NextRunTimeInt(time, AllowExact); Debug.WriteLine(time); Debug.WriteLine(returnTime); Debug.WriteLine(_EndTime); return (returnTime >= _EndTime) ? DateTime.MaxValue : returnTime; } private DateTime NextRunTimeInt(DateTime time, bool AllowExact) { TimeSpan Span = time-_StartTime; if (Span < TimeSpan.Zero) return _StartTime; if (ExactMatch(time)) return AllowExact ? time : time + _Interval; uint msRemaining = (uint)(_Interval.TotalMilliseconds - ((uint)Span.TotalMilliseconds % (uint)_Interval.TotalMilliseconds)); return time.AddMilliseconds(msRemaining); } private bool ExactMatch(DateTime time) { TimeSpan Span = time-_StartTime; if (Span < TimeSpan.Zero) return false; return (Span.TotalMilliseconds % _Interval.TotalMilliseconds) == 0; } private TimeSpan _Interval; private DateTime _StartTime; private DateTime _EndTime; } /// <summary> /// This class will be used to implement a filter that enables a window of activity. For cases where you want to /// run every 15 minutes between 6:00 AM and 5:00 PM. Or just on weekdays or weekends. /// </summary> public class BlockWrapper : IScheduledItem { public BlockWrapper(IScheduledItem item, string StrBase, string BeginOffset, string EndOffset) { _Item = item; _Begin = new ScheduledTime(StrBase, BeginOffset); _End = new ScheduledTime(StrBase, EndOffset); } public void AddEventsInInterval(DateTime Begin, DateTime End, ArrayList List) { DateTime Next = NextRunTime(Begin, true); while (Next < End) { List.Add(Next); Next = NextRunTime(Next, false); } } public DateTime NextRunTime(DateTime time, bool AllowExact) { return NextRunTime(time, 100, AllowExact); } DateTime NextRunTime(DateTime time, int count, bool AllowExact) { if (count == 0) throw new Exception("Invalid block wrapper combination."); DateTime temp = _Item.NextRunTime(time, AllowExact), begin = _Begin.NextRunTime(time, true), end = _End.NextRunTime(time, true); System.Diagnostics.Debug.WriteLine(string.Format("{0} {1} {2} {3}", time, begin, end, temp)); bool A = temp > end, B = temp < begin, C = end < begin; System.Diagnostics.Debug.WriteLine(string.Format("{0} {1} {2}", A, B, C)); if (C) { if (A && B) return NextRunTime(begin, --count, false); else return temp; } else { if (!A && !B) return temp; if (!A) return NextRunTime(begin, --count, false); else return NextRunTime(end, --count, false); } } private IScheduledItem _Item; private ScheduledTime _Begin, _End; } } --- NEW FILE: EventStorage.cs --- // Original Copyright (c) 2004 Andy Brummer. All Rights Reserved. - http://www.codeproject.com/dotnet/ABTransClockArticle.asp #region Modified Copyright / License Information /* Copyright 2004 - 2005 Adapdev Technologies, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ============================ Author Log ============================ III Full Name SMM Sean McCormack (Adapdev) ============================ Change Log ============================ III MMDDYY Change */ #endregion using System; using System.Xml; using System.Xml.XPath; namespace Adapdev.Scheduling.Timer { /// <summary> /// Local event strorage keeps the last time in memory so that skipped events are not recovered. /// </summary> public class LocalEventStorage : IEventStorage { public LocalEventStorage() { _LastTime = DateTime.MaxValue; } public void RecordLastTime(DateTime Time) { _LastTime = Time; } public DateTime ReadLastTime() { if (_LastTime == DateTime.MaxValue) _LastTime = DateTime.Now; return _LastTime; } DateTime _LastTime; } /// <summary> /// FileEventStorage saves the last time in an XmlDocument so that recovery will include periods that the /// process is shutdown. /// </summary> public class FileEventStorage : IEventStorage { public FileEventStorage(string FileName, string XPath) { _FileName = FileName; _XPath = XPath; } public void RecordLastTime(DateTime Time) { _Doc.SelectSingleNode(_XPath).Value = Time.ToString(); _Doc.Save(_FileName); } public DateTime ReadLastTime() { _Doc.Load(_FileName); string Value = _Doc.SelectSingleNode(_XPath).Value; if (Value == null || Value == string.Empty) return DateTime.Now; return DateTime.Parse(Value); } string _FileName; string _XPath; XmlDocument _Doc = new XmlDocument(); } } --- NEW FILE: MethodCall.cs --- // Original Copyright (c) 2004 Andy Brummer. All Rights Reserved. - http://www.codeproject.com/dotnet/ABTransClockArticle.asp #region Modified Copyright / License Information /* Copyright 2004 - 2005 Adapdev Technologies, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ============================ Author Log ============================ III Full Name SMM Sean McCormack (Adapdev) ============================ Change Log ============================ III MMDDYY Change */ #endregion using System; using System.Collections; using System.Reflection; using System.Text.RegularExpressions; namespace Adapdev.Scheduling.Timer { /// <summary> /// IParameterSetter represents a serialized parameter list. This is used to provide a partial specialized /// method call. This is useful for remote invocation of method calls. For example if you have a method with /// 3 parameters. The first 2 might represent static data such as a report and a storage location. The third /// might be the time that the report is invoked, which is only known when the method is invoked. Using this, /// you just pass the method and the first 2 parameters to a timer object, which supplies the 3rd parameter. /// Without these objects, you would have to generate a custom object type for each method you wished to /// execute in this manner and store the static parameters as instance variables. /// </summary> public interface IParameterSetter { /// <summary> /// This resets the setter to the beginning. It is used for setters that rely on positional state /// information. It is called prior to setting any method values. /// </summary> void reset(); /// <summary> /// This method is used to both query support for setting a parameter and actually set the value. /// True is returned if the parameter passed in is updated. /// </summary> /// <param name="pi">The reflection information about this parameter.</param> /// <param name="ParameterLoc">The location of the prameter in the parameter list.</param> /// <param name="parameter">The parameter object</param> /// <returns>true if the parameter is matched and false otherwise</returns> bool GetParameterValue(ParameterInfo pi, int ParameterLoc, ref object parameter); } /// <summary> /// This setter object takes a simple object array full of parameter data. It applys the objects in order /// to the method parameter list. /// </summary> public class OrderParameterSetter : IParameterSetter { public OrderParameterSetter(params object[] _Params) { _ParamList = _Params; } public void reset() { _counter = 0; } public bool GetParameterValue(ParameterInfo pi, int ParameterLoc, ref object parameter) { if (_counter >= _ParamList.Length) return false; parameter = _ParamList[_counter++]; return true; } object[] _ParamList; int _counter; } /// <summary> /// This setter object stores the parameter data in a Hashtable and uses the hashtable keys to match /// the parameter names of the method to the parameter data. This allows methods to be called like /// stored procedures, with the parameters being passed in independent of order. /// </summary> public class NamedParameterSetter : IParameterSetter { public NamedParameterSetter(Hashtable Params) { _Params = Params; } public void reset() { } public bool GetParameterValue(ParameterInfo pi, int ParameterLoc, ref object parameter) { string ParamName = pi.Name; if (!_Params.ContainsKey(ParamName)) return false; parameter = _Params[ParamName]; return true; } Hashtable _Params; } /// <summary> /// ParameterSetterList maintains a collection of IParameterSetter objects and applies them in order to each /// parameter of the method. Each time a match occurs the next parameter is tried starting with the first /// setter object until it is matched. /// </summary> public class ParameterSetterList { public void Add(IParameterSetter setter) { _List.Add(setter); } public IParameterSetter[] ToArray() { return (IParameterSetter[])_List.ToArray(typeof(IParameterSetter)); } public void reset() { foreach(IParameterSetter Setter in _List) Setter.reset(); } public object[] GetParameters(MethodInfo Method) { ParameterInfo[] Params = Method.GetParameters(); object[] Values = new object[Params.Length]; for(int i=0; i<Params.Length; ++i) SetValue(Params[i], i, ref Values[i]); return Values; } public object[] GetParameters(MethodInfo Method, IParameterSetter LastSetter) { ParameterInfo[] Params = Method.GetParameters(); object[] Values = new object[Params.Length]; for(int i=0; i<Params.Length; ++i) { if (!SetValue(Params[i], i, ref Values[i])) LastSetter.GetParameterValue(Params[i], i, ref Values[i]); } return Values; } bool SetValue(ParameterInfo Info, int i, ref object Value) { foreach(IParameterSetter Setter in _List) { if (Setter.GetParameterValue(Info, i, ref Value)) return true; } return false; } ArrayList _List = new ArrayList(); } /// <summary> /// IMethodCall represents a partially specified parameter data list and a method. This allows methods to be /// dynamically late invoked for things like timers and other event driven frameworks. /// </summary> public interface IMethodCall { ParameterSetterList ParamList { get; } object Execute(); object Execute(IParameterSetter Params); IAsyncResult BeginExecute(AsyncCallback callback, object obj); IAsyncResult BeginExecute(IParameterSetter Params, AsyncCallback callback, object obj); } delegate object Exec(); delegate object Exec2(IParameterSetter Params); /// <summary> /// Method call captures the data required to do a defered method call. /// </summary> public class DelegateMethodCall : MethodCallBase, IMethodCall { public DelegateMethodCall(Delegate f) { _f = f; } public DelegateMethodCall(Delegate f, params object[] Params) { if (f.Method.GetParameters().Length < Params.Length) throw new ArgumentException("Too many parameters specified for delegate", "f"); _f = f; ParamList.Add(new OrderParameterSetter(Params)); } public DelegateMethodCall(Delegate f, IParameterSetter Params) { _f = f; ParamList.Add(Params); } Delegate _f; public Delegate f { get { return _f; } set { _f = value; } } public MethodInfo Method { get { return _f.Method; } } public object Execute() { return f.DynamicInvoke(GetParameterList(Method)); } public object Execute(IParameterSetter Params) { return f.DynamicInvoke(GetParameterList(Method, Params)); } Exec _exec; public IAsyncResult BeginExecute(AsyncCallback callback, object obj) { _exec = new Exec(Execute); return _exec.BeginInvoke(callback, obj); } public IAsyncResult BeginExecute(IParameterSetter Params, AsyncCallback callback, object obj) { Exec2 exec = new Exec2(Execute); return exec.BeginInvoke(Params, callback, obj); } } public class DynamicMethodCall : MethodCallBase, IMethodCall { public DynamicMethodCall(MethodInfo method) { _obj = null; _method = method; } public DynamicMethodCall(object obj, MethodInfo method) { _obj = obj; _method = method; } public DynamicMethodCall(object obj, MethodInfo method, IParameterSetter setter) { _obj = obj; _method = method; ParamList.Add(setter); } object _obj; MethodInfo _method; public MethodInfo Method { get { return _method; } set { _method = value; } } public object Execute() { return _method.Invoke(_obj, GetParameterList(Method)); } public object Execute(IParameterSetter Params) { return _method.Invoke(_obj, GetParameterList(Method, Params)); } Exec _exec; public IAsyncResult BeginExecute(AsyncCallback callback, object obj) { _exec = new Exec(Execute); return _exec.BeginInvoke(callback, null); } public IAsyncResult BeginExecute(IParameterSetter Params, AsyncCallback callback, object obj) { Exec2 exec = new Exec2(Execute); return exec.BeginInvoke(Params, callback, null); } } /// <summary> /// This is a base class that handles the Parameter list management for the 2 dynamic method call methods. /// </summary> public class MethodCallBase { ParameterSetterList _ParamList = new ParameterSetterList(); public ParameterSetterList ParamList { get { return _ParamList; } } protected object[] GetParameterList(MethodInfo Method) { ParamList.reset(); object[] Params = ParamList.GetParameters(Method); return Params; } protected object[] GetParameterList(MethodInfo Method, IParameterSetter Params) { ParamList.reset(); object[] objParams = ParamList.GetParameters(Method, Params); return objParams; } } } --- NEW FILE: TimerJob.cs --- // Original Copyright (c) 2004 Andy Brummer. All Rights Reserved. - http://www.codeproject.com/dotnet/ABTransClockArticle.asp #region Modified Copyright / License Information /* Copyright 2004 - 2005 Adapdev Technologies, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ============================ Author Log ============================ III Full Name SMM Sean McCormack (Adapdev) ============================ Change Log ============================ III MMDDYY Change */ #endregion using System; using System.Collections; using System.Reflection; using System.Timers; namespace Adapdev.Scheduling.Timer { /// <summary> /// Timer job groups a schedule, syncronization data, a result filter, method information and an enabled state so that multiple jobs /// can be managed by the same timer. Each one operating independently of the others with different syncronization and recovery settings. /// </summary> public class TimerJob { public TimerJob(IScheduledItem schedule, IMethodCall method) { Schedule = schedule; Method = method; _ExecuteHandler = new ExecuteHandler(ExecuteInternal); } public IScheduledItem Schedule; public bool SyncronizedEvent = true; public IResultFilter Filter; public IMethodCall Method; // public IJobLog Log; public bool Enabled = true; public DateTime NextRunTime(DateTime time, bool IncludeStartTime) { if (!Enabled) return DateTime.MaxValue; return Schedule.NextRunTime(time, IncludeStartTime); } public void Execute(object sender, DateTime Begin, DateTime End, ExceptionEventHandler Error) { if (!Enabled) return; ArrayList EventList = new ArrayList(); Schedule.AddEventsInInterval(Begin, End, EventList); if (Filter != null) Filter.FilterResultsInInterval(Begin, End, EventList); foreach(DateTime EventTime in EventList) { if (SyncronizedEvent) _ExecuteHandler(sender, EventTime, Error); else _ExecuteHandler.BeginInvoke(sender, EventTime, Error, null, null); } } private void ExecuteInternal(object sender, DateTime EventTime, ExceptionEventHandler Error) { try { TimerParameterSetter Setter = new TimerParameterSetter(EventTime, sender); Method.Execute(Setter); } catch (Exception ex) { if (Error != null) try { Error(this, new ExceptionEventArgs(EventTime, ex)); } catch {} } } private delegate void ExecuteHandler(object sender, DateTime EventTime, ExceptionEventHandler Error); private ExecuteHandler _ExecuteHandler; } /// <summary> /// Timer job manages a group of timer jobs. /// </summary> public class TimerJobList { public TimerJobList() { _List = new ArrayList(); } public void Add(TimerJob Event) { _List.Add(Event); } public void Clear() { _List.Clear(); } /// <summary> /// Gets the next time any of the jobs in the list will run. Allows matching the exact start time. If no matches are found the return /// is DateTime.MaxValue; /// </summary> /// <param name="time">The starting time for the interval being queried. This time is included in the interval</param> /// <returns>The first absolute date one of the jobs will execute on. If none of the jobs needs to run DateTime.MaxValue is returned.</returns> public DateTime NextRunTime(DateTime time) { DateTime next = DateTime.MaxValue; //Get minimum datetime from the list. foreach(TimerJob Job in _List) { DateTime Proposed = Job.NextRunTime(time, true); next = (Proposed < next) ? Proposed : next; } return next; } public TimerJob[] Jobs { get { return (TimerJob[])_List.ToArray(typeof(TimerJob)); } } private ArrayList _List; } /// <summary> /// The timer job allows delegates to be specified with unbound parameters. This ParameterSetter assigns all unbound datetime parameters /// with the specified time and all unbound object parameters with the calling object. /// </summary> public class TimerParameterSetter : IParameterSetter { /// <summary> /// Initalize the ParameterSetter with the time to pass to unbound time parameters and object to pass to unbound object parameters. /// </summary> /// <param name="time">The time to pass to the unbound DateTime parameters</param> /// <param name="sender">The object to pass to the unbound object parameters</param> public TimerParameterSetter(DateTime time, object sender) { _time = time; _sender = sender; } public void reset() { } public bool GetParameterValue(ParameterInfo pi, int ParameterLoc, ref object parameter) { switch(pi.ParameterType.Name.ToLower()) { case "datetime": parameter = _time; return true; case "object": parameter = _sender; return true; case "scheduledeventargs": parameter = new ScheduledEventArgs(_time); return true; case "eventargs": parameter = new ScheduledEventArgs(_time); return true; } return false; } DateTime _time; object _sender; } } --- NEW FILE: ScheduleTimer.cs --- // Original Copyright (c) 2004 Andy Brummer. All Rights Reserved. - http://www.codeproject.com/dotnet/ABTransClockArticle.asp #region Modified Copyright / License Information /* Copyright 2004 - 2005 Adapdev Technologies, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ============================ Author Log ============================ III Full Name SMM Sean McCormack (Adapdev) ============================ Change Log ============================ III MMDDYY Change */ #endregion using System; using System.Collections; using System.Timers; namespace Adapdev.Scheduling.Timer { /// <summary> /// ScheduleTimer represents a timer that fires on a more human friendly schedule. For example it is easy to /// set it to fire every day at 6:00PM. It is useful for batch jobs or alarms that might be difficult to /// schedule with the native .net timers. /// It is similar to the .net timer that it is based on with the start and stop methods functioning similarly. /// The main difference is the event uses a different delegate and arguement since the .net timer argument /// class is not creatable. /// </summary> public class ScheduleTimerBase { public ScheduleTimerBase() { _Timer = new System.Timers.Timer(); _Timer.AutoReset = false; _Timer.Elapsed += new ElapsedEventHandler(Timer_Elapsed); _Jobs = new TimerJobList(); _LastTime = DateTime.MaxValue; } /// <summary> /// Adds a job to the timer. This method passes in a delegate and the parameters similar to the Invoke method of windows forms. /// </summary> /// <param name="Schedule">The schedule that this delegate is to be run on.</param> /// <param name="f">The delegate to run</param> /// <param name="Params">The method parameters to pass if you leave any DateTime parameters unbound, then they will be set with the scheduled run time of the /// method. Any unbound object parameters will get this Job object passed in.</param> public void AddJob(IScheduledItem Schedule, Delegate f, params object[] Params) { _Jobs.Add(new TimerJob(Schedule, new DelegateMethodCall(f, Params))); } /// <summary> /// Adds a job to the timer to operate asyncronously. /// </summary> /// <param name="Schedule">The schedule that this delegate is to be run on.</param> /// <param name="f">The delegate to run</param> /// <param name="Params">The method parameters to pass if you leave any DateTime parameters unbound, then they will be set with the scheduled run time of the /// method. Any unbound object parameters will get this Job object passed in.</param> public void AddAsyncJob(IScheduledItem Schedule, Delegate f, params object[] Params) { TimerJob Event = new TimerJob(Schedule, new DelegateMethodCall(f, Params)); Event.SyncronizedEvent = false; _Jobs.Add(Event); } /// <summary> /// Adds a job to the timer. /// </summary> /// <param name="Event"></param> public void AddJob(TimerJob Event) { _Jobs.Add(Event); } /// <summary> /// Clears out all scheduled jobs. /// </summary> public void ClearJobs() { _Jobs.Clear(); } /// <summary> /// Begins executing all assigned jobs at the scheduled times /// </summary> public void Start() { QueueNextTime(EventStorage.ReadLastTime()); } /// <summary> /// Halts executing all jobs. When the timer is restarted all jobs that would have run while the timer was stopped are re-tried. /// </summary> public void Stop() { _Timer.Stop(); } /// <summary> /// EventStorage determines the method used to store the last event fire time. It defaults to keeping it in memory. /// </summary> public IEventStorage EventStorage = new LocalEventStorage(); public event ExceptionEventHandler Error; private DateTime _LastTime; private System.Timers.Timer _Timer; private TimerJobList _Jobs; /// <summary> /// This is here to provide accuracy. Even if nothing is scheduled the timer sleeps for a maximum of 1 minute. /// </summary> private static TimeSpan MAX_INTERVAL = new TimeSpan(0, 1, 0); private double NextInterval(DateTime thisTime) { TimeSpan interval = _Jobs.NextRunTime(thisTime)-thisTime; if (interval > MAX_INTERVAL) interval = MAX_INTERVAL; //Handles the case of 0 wait time, the interval property requires a duration > 0. return (interval.TotalMilliseconds == 0) ? 1 : interval.TotalMilliseconds; } private void QueueNextTime(DateTime thisTime) { _Timer.Interval = NextInterval(thisTime); System.Diagnostics.Debug.WriteLine(_Timer.Interval); _Timer.Start(); _LastTime = thisTime; EventStorage.RecordLastTime(thisTime); } private void Timer_Elapsed(object sender, ElapsedEventArgs e) { try { foreach(TimerJob Event in _Jobs.Jobs) Event.Execute(this, _LastTime, e.SignalTime, Error); } catch (Exception ex) { OnError(DateTime.Now, ex); } finally { QueueNextTime(e.SignalTime); } } private void OnError(DateTime eventTime, Exception e) { if (Error == null) return; Error(this, new ExceptionEventArgs(eventTime, e)); } } public class ScheduleTimer : ScheduleTimerBase { public void AddEvent(IScheduledItem Schedule) { if (Elapsed == null) throw new ArgumentNullException("Elapsed", "member variable is null."); AddJob(new TimerJob(Schedule, new DelegateMethodCall(Elapsed))); } public event ScheduledEventHandler Elapsed; } /// <summary> /// ExceptionEventArgs allows exceptions to be captured and sent to the OnError event of the timer. /// </summary> public class ExceptionEventArgs : EventArgs { public ExceptionEventArgs(DateTime eventTime, Exception e) { EventTime = eventTime; Error = e; } public DateTime EventTime; public Exception Error; } /// <summary> /// ExceptionEventHandler is the method type used by the OnError event for the timer. /// </summary> public delegate void ExceptionEventHandler(object sender, ExceptionEventArgs Args); public class ScheduledEventArgs : EventArgs { public ScheduledEventArgs(DateTime eventTime) { EventTime = eventTime; } public DateTime EventTime; } public delegate void ScheduledEventHandler(object sender, ScheduledEventArgs e); /// <summary> /// The IResultFilter interface represents filters that either sort the events for an interval or /// remove duplicate events either selecting the first or the last event. /// </summary> public interface IResultFilter { void FilterResultsInInterval(DateTime Start, DateTime End, ArrayList List); } /// <summary> /// IEventStorage is used to provide persistance of schedule during service shutdowns. /// </summary> public interface IEventStorage { void RecordLastTime(DateTime Time); DateTime ReadLastTime(); } } |
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.Data In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv19977/src/Adapdev.Data Added Files: AbstractDAO.cs Adapdev.Data.csproj CommandTextViewer.cs ConnectionStringBuilder.cs DataReaderDebugger.cs DataSetDebugger.cs DbConnectionProvider.cs DbConnectionProviders.cs DbConnectionType.cs DbConnectionTypes.cs DbConstants.cs DbProviderFactory.cs DbProviderType.cs DbProviderTypeConverter.cs DbType.cs DbTypeConverter.cs IDataAccessObject.cs IDataReaderMapper.cs IDataSetAccessObject.cs IDataSetMapper.cs IDbDataAccessObject.cs IDbDataSetAccessObject.cs ITransferObject.cs ProviderInfoManager.cs Log Message: Reposting to the repository after it got hosed --- NEW FILE: DataReaderDebugger.cs --- using System; using System.Data; using System.Text; namespace Adapdev.Data { /// <summary> /// Summary description for DataReaderDebugger. /// </summary> public class DataReaderDebugger { private IDataReader _reader = null; public DataReaderDebugger(IDataReader reader) { this._reader = reader; } public string Text { get { StringBuilder sb = new StringBuilder(); do { int i = _reader.FieldCount; for(int j = 0; j < i; j++) { sb.Append(this._reader.GetName(j) + "|"); } sb.Append(Environment.NewLine); while(this._reader.Read()) { for(int j = 0; j < i; j++) { sb.Append(this._reader.GetValue(j).ToString() + "|"); } sb.Append(Environment.NewLine); } sb.Append(Environment.NewLine); } while(this._reader.NextResult()); return sb.ToString(); } } } } --- NEW FILE: DbProviderFactory.cs --- namespace Adapdev.Data { using System; using System.Data; using System.Data.Common; using System.Data.OleDb; using System.Data.SqlClient; using System.Data.OracleClient; using MySql.Data.MySqlClient; /// <summary> /// Provides database neutral access to ADO.NET classes /// </summary> public class DbProviderFactory { #region IDbCommand /// <summary> /// Creates an IDbCommand implementation for the specified DbProviderType /// </summary> /// <param name="DbProviderType">The DbProviderType to use</param> /// <returns></returns> public static IDbCommand CreateCommand(DbProviderType DbProviderType) { switch (DbProviderType) { case DbProviderType.SQLSERVER: return new SqlCommand(); case DbProviderType.ORACLE: return new OracleCommand(); case DbProviderType.MYSQL: return new MySqlCommand(); default: return new OleDbCommand(); } } #endregion #region IDbConnection /// <summary> /// Creates an IDbConnection implementation for the specified DbProviderType /// </summary> /// <param name="DbProviderType"></param> /// <returns></returns> public static IDbConnection CreateConnection(DbProviderType DbProviderType) { switch (DbProviderType) { case DbProviderType.SQLSERVER: return new SqlConnection(); case DbProviderType.ORACLE: return new OracleConnection(); case DbProviderType.MYSQL: return new MySqlConnection(); default: return new OleDbConnection(); } } #endregion #region DbDataAdapter public static DbDataAdapter CreateDataAdapter(DbProviderType DbProviderType, IDbCommand command, IDbConnection connection) { switch (DbProviderType) { case DbProviderType.SQLSERVER: SqlDataAdapter sqlda = new SqlDataAdapter(); sqlda.SelectCommand = (SqlCommand) command; command.Connection = connection; return sqlda; case DbProviderType.ORACLE: OracleDataAdapter orada = new OracleDataAdapter(); orada.SelectCommand = (OracleCommand) command; command.Connection = connection; return orada; case DbProviderType.MYSQL: MySqlDataAdapter mysqlda = new MySqlDataAdapter(); mysqlda.SelectCommand = (MySqlCommand) command; command.Connection = connection; return mysqlda; default: OleDbDataAdapter oleda = new OleDbDataAdapter(); oleda.SelectCommand = (OleDbCommand) command; command.Connection = connection; return oleda; } } #endregion #region IDataReader public static IDataReader CreateDataReader(string connectionString, IDbCommand command, DbProviderType DbProviderType) { IDbConnection connection = DbProviderFactory.CreateConnection(DbProviderType); connection.ConnectionString = connectionString; return CreateDataReader(connection, command, DbProviderType); } public static IDataReader CreateDataReader(string connectionString, string command, DbProviderType DbProviderType) { IDbConnection connection = DbProviderFactory.CreateConnection(DbProviderType); connection.ConnectionString = connectionString; IDbCommand cmd = DbProviderFactory.CreateCommand(DbProviderType); cmd.CommandText = command; return CreateDataReader(connection, cmd, DbProviderType); } public static IDataReader CreateDataReader(IDbConnection connection, string command, DbProviderType DbProviderType) { IDbCommand cmd = DbProviderFactory.CreateCommand(DbProviderType); cmd.CommandText = command; return CreateDataReader(connection, cmd, DbProviderType); } public static IDataReader CreateDataReader(IDbConnection connection, IDbCommand command, DbProviderType DbProviderType) { return CreateDataReader(connection, command, CommandBehavior.Default, DbProviderType); } public static IDataReader CreateDataReader(IDbConnection connection, IDbCommand command, CommandBehavior behavior, DbProviderType DbProviderType) { IDataReader reader = null; command.Connection = connection; reader = command.ExecuteReader(behavior); return reader; } #endregion #region DataSet public static DataSet CreateDataSet(string connectionString, IDbCommand command, DbProviderType DbProviderType) { IDbConnection connection = DbProviderFactory.CreateConnection(DbProviderType); connection.ConnectionString = connectionString; return CreateDataSet(connection, command, DbProviderType); } public static DataSet CreateDataSet(IDbConnection connection, IDbCommand command, DbProviderType DbProviderType) { DataSet ds = new DataSet(); DbDataAdapter da = DbProviderFactory.CreateDataAdapter(DbProviderType, command, connection); connection.Open(); da.Fill(ds); connection.Close(); return ds; } #endregion #region DataTable public static DataTable CreateDataTable(string connection, IDbCommand command, DbProviderType DbProviderType) { throw new NotImplementedException(); } #endregion } } --- NEW FILE: AbstractDAO.cs --- namespace Adapdev.Data { using System; using System.Collections; using System.Data; using System.Data.Common; using System.Data.OleDb; using System.Data.SqlClient; using Adapdev.Data.Sql; /// <summary> /// AbstractDAO provides the required base functionality to create a full-featured /// Data Access Object. /// </summary> /// public abstract class AbstractDAO : IDbDataAccessObject, IDbDataSetAccessObject, IDataReaderMapper { private DbProviderType provider = DbProviderType.SQLSERVER; private DbType db = DbType.SQLSERVER; private string connectionString = ""; private string table = ""; #region Constructors /// <summary> /// Constructor /// </summary> /// <param name="providerType">The specified provider type</param> /// <param name="databaseType">The specified database type</param> /// <param name="tableName">The table being accessed</param> /// <param name="connectionString">The specified connection string</param> public AbstractDAO(DbProviderType providerType, DbType databaseType, string tableName, string connectionString) { this.provider = providerType; this.db = databaseType; this.table = tableName; this.connectionString = connectionString; } #endregion #region IDataAccessObject Members /// <summary> /// Saves the specified object to the datastore /// </summary> /// <param name="o"></param> /// public void Save(object o) { using(IDbConnection connection = this.CreateConnection()) { connection.Open(); this.ExecuteNonQuery(this.CreateInsertCommand(o), connection); this.CustomSave(o, connection); } } /// <summary> /// Saves the specified object to the datastore, using the specified open connection /// </summary> /// <param name="o">The object to save</param> /// <param name="conn">The open connection to use</param> /// <remarks>The IDbConnection must already be open</remarks> public void Save(object o, IDbConnection conn) { this.ExecuteNonQuery(this.CreateInsertCommand(o), conn); this.CustomSave(o, conn); } /// <summary> /// Saves the specified object to the datastore, using the specified open connection /// </summary> /// <param name="o">The object to save</param> /// <param name="conn">The open connection to use</param> /// <param name="transaction">The transaction to execute under</param> /// <remarks>The IDbConnection must already be open</remarks> public void Save(object o, IDbConnection conn, IDbTransaction transaction) { this.ExecuteNonQuery(this.CreateInsertCommand(o), conn, transaction); this.CustomSave(o, conn, transaction); } /// <summary> /// Deletes the specified object by its id /// </summary> /// <param name="id">The id for the object to delete</param> public void Delete(object id) { this.ExecuteNonQuery(this.CreateDeleteOneCommand(id)); } /// <summary> /// Deletes the specified object by its id /// </summary> /// <param name="id">The id for the object to delete</param> /// <param name="conn">The open connection to use</param> /// <remarks>The IDbConnection must already be open</remarks> public void Delete(object id, IDbConnection conn) { this.ExecuteNonQuery(this.CreateDeleteOneCommand(id), conn); } /// <summary> /// Deletes the specified object by its id /// </summary> /// <param name="id">The id for the object to delete</param> /// <param name="conn">The open connection to use</param> /// <param name="transaction">The transaction to execute under</param> /// <remarks>The IDbConnection must already be open</remarks> public void Delete(object id, IDbConnection conn, IDbTransaction transaction) { this.ExecuteNonQuery(this.CreateDeleteOneCommand(id), conn, transaction); } /// <summary> /// Updates the underlying datastore /// </summary> /// <param name="o">The object to use for the update</param> public void Update(object o) { this.ExecuteNonQuery(this.CreateUpdateCommand(o)); } /// <summary> /// Updates the underlying datastore /// </summary> /// <param name="o">The object to use for the update</param> /// <param name="conn">The open connection to use</param> /// <remarks>The IDbConnection must already be open</remarks> public void Update(object o, IDbConnection conn) { this.ExecuteNonQuery(this.CreateUpdateCommand(o), conn); } /// <summary> /// Updates the underlying datastore /// </summary> /// <param name="o">The object to use for the update</param> /// <param name="conn">The open connection to use</param> /// <param name="transaction">The transaction to execute under</param> /// <remarks>The IDbConnection must already be open</remarks> public void Update(object o, IDbConnection conn, IDbTransaction transaction) { this.ExecuteNonQuery(this.CreateUpdateCommand(o), conn, transaction); } /// <summary> /// Selects all records in the underlying datastore /// </summary> /// <returns></returns> public IList SelectAll() { IList c; using (IDbConnection conn = this.CreateConnection()) { conn.Open(); c = this.SelectAll(conn); } return c; } /// <summary> /// Selects all records in the underlying datastore, using the specified open IDbConnection /// </summary> /// <param name="conn">The open IDbConnection to use</param> /// <returns></returns> public IList SelectAll(IDbConnection conn) { IList c; IDataReader dr = DbProviderFactory.CreateDataReader(conn, this.CreateSelectAllCommand(), this.provider); c = this.MapObjects(dr); dr.Close(); return c; } /// <summary> /// Selects a set number of records in the underlying datastore /// </summary> /// <param name="maxRecords">The number of records to return</param> /// <returns></returns> public IList SelectAllWithLimit(int maxRecords) { return this.SelectAllWithLimit(maxRecords, OrderBy.ASCENDING); } /// <summary> /// Selects a set number of records in the underlying datastore, /// using the specified open IDbConnection /// </summary> /// <param name="maxRecords">The number of records to return</param> /// <param name="connection">The open IDbConnection to use</param> /// <returns></returns> public IList SelectAllWithLimit(int maxRecords, IDbConnection connection) { return this.SelectAllWithLimit(maxRecords, OrderBy.ASCENDING, connection); } /// <summary> /// Selects a set number of records in the underlying datastore /// </summary> /// <param name="maxRecords">The number of records to return</param> /// <param name="order">The order the records should be returned</param> /// <param name="orderColumns">The columns to order by</param> /// <returns></returns> public IList SelectAllWithLimit(int maxRecords, OrderBy order, params string[] orderColumns) { ISelectQuery query = QueryFactory.CreateSelectQuery(this.db); query.SetTable(this.table); query.SetLimit(maxRecords); query.OrderBy = order; query.AddAll(); foreach (string s in orderColumns) { query.AddOrderBy(s); } return this.Select(query); } /// <summary> /// Selects a set number of records in the underlying datastore /// </summary> /// <param name="maxRecords">The number of records to return</param> /// <param name="order">The order the records should be returned</param> /// <param name="connection">The open IDbConnection to use</param> /// <param name="orderColumns">The columns to order by</param> /// <returns></returns> public IList SelectAllWithLimit(int maxRecords, OrderBy order, IDbConnection connection, params string[] orderColumns) { ISelectQuery query = QueryFactory.CreateSelectQuery(this.db); query.SetTable(this.table); query.SetLimit(maxRecords); query.OrderBy = order; query.AddAll(); foreach (string s in orderColumns) { query.AddOrderBy(s); } return this.Select(query, connection); } /// <summary> /// Selects records using the specified query /// </summary> /// <param name="query">The query to use</param> /// <returns></returns> public IList Select(ISelectQuery query) { return this.Select(this.CreateCommand(query.GetText())); } /// <summary> /// Selects records using the specified query /// </summary> /// <param name="query">The query to use</param> /// <param name="connection">The open IDbConnection</param> /// <returns></returns> public IList Select(ISelectQuery query, IDbConnection connection) { return this.Select(this.CreateCommand(query.GetText()), connection); } /// <summary> /// Selects records using the specified command /// </summary> /// <param name="cmd">The command to use</param> /// <returns></returns> public IList Select(IDbCommand cmd) { IList c; using (IDbConnection conn = this.CreateConnection()) { conn.Open(); c = this.Select(cmd, conn); } return c; } /// <summary> /// Selects records using the specified command /// </summary> /// <param name="cmd">The command to use</param> /// <param name="conn">The open IDbConnection to use</param> /// <returns></returns> public IList Select(IDbCommand cmd, IDbConnection conn) { IList c; IDataReader dr = DbProviderFactory.CreateDataReader(conn, cmd, this.provider); c = this.MapObjects(dr); dr.Close(); return c; } /// <summary> /// Selects records using the specified command /// </summary> /// <param name="command">The command to use</param> /// <returns></returns> public IList Select(string command) { return this.Select(this.CreateCommand(command)); } /// <summary> /// Selects records using the specified command /// </summary> /// <param name="command">The command to use</param> /// <param name="conn">The open IDbConnection to use</param> /// <returns></returns> public IList Select(string command, IDbConnection conn) { return this.Select(this.CreateCommand(command), conn); } /// <summary> /// Selects a specific record, using the passed in id /// </summary> /// <param name="id">The id for the record to select</param> /// <returns></returns> public object SelectById(object id) { return this.SelectOne(id); } /// <summary> /// Selects a specific record, using the passed in id /// </summary> /// <param name="id">The id for the record to select</param> /// <param name="connection">The open IDbConnection to use</param> /// <returns></returns> public object SelectById(object id, IDbConnection connection) { return this.SelectOne(id, connection); } /// <summary> /// Selects a specific record, using the passed in id /// </summary> /// <param name="id">The id for the record to select</param> /// <returns></returns> /// [Obsolete("Deprecated. Please use SelectById")] public object SelectOne(object id) { object o; using (IDbConnection conn = this.CreateConnection()) { conn.Open(); o = this.SelectOne(id, conn); } return o; } /// <summary> /// Selects a specific record, using the passed in id /// </summary> /// <param name="id">The id for the record to select</param> /// <param name="conn">The open IDbConnection to use</param> /// <returns></returns> [Obsolete("Deprecated. Please use SelectById")] public object SelectOne(object id, IDbConnection conn) { object o = null; IDataReader dr = DbProviderFactory.CreateDataReader(conn, this.CreateSelectOneCommand(id), this.provider); while (dr.Read()) { o = this.MapObject(dr); break; } dr.Close(); return o; } /// <summary> /// Executes the specified command /// </summary> /// <param name="cmd">The command to use</param> public void ExecuteNonQuery(IDbCommand cmd) { using (IDbConnection conn = this.CreateConnection()) { cmd.Connection = conn; conn.Open(); cmd.ExecuteNonQuery(); } } /// <summary> /// Executes the specified command /// </summary> /// <param name="cmd">The command to use</param> /// <param name="conn">The open IDbConnection to use</param> public void ExecuteNonQuery(IDbCommand cmd, IDbConnection conn) { cmd.Connection = conn; cmd.ExecuteNonQuery(); } /// <summary> /// Executes the specified command /// </summary> /// <param name="cmd">The command to use</param> /// <param name="conn">The open IDbConnection to use</param> /// <param name="transaction">The transaction to execute under</param> public void ExecuteNonQuery(IDbCommand cmd, IDbConnection conn, IDbTransaction transaction) { cmd.Connection = conn; cmd.Transaction = transaction; cmd.ExecuteNonQuery(); } /// <summary> /// Executes the specified query /// </summary> /// <param name="query">The query to use</param> public void ExecuteNonQuery(INonSelectQuery query) { this.ExecuteNonQuery(this.CreateCommand(query.GetText())); } /// <summary> /// Executes the specified query /// </summary> /// <param name="query">The query to use</param> /// <param name="connection">The open IDbConnection to use</param> public void ExecuteNonQuery(INonSelectQuery query, IDbConnection connection) { this.ExecuteNonQuery(this.CreateCommand(query.GetText()), connection); } /// <summary> /// Executse the specified command /// </summary> /// <param name="command">The command to use</param> public void ExecuteNonQuery(string command) { this.ExecuteNonQuery(this.CreateCommand(command)); } /// <summary> /// Executes the specified command /// </summary> /// <param name="command">The command to use</param> /// <param name="connection">The open IDbConnection to use</param> public void ExecuteNonQuery(string command, IDbConnection connection) { this.ExecuteNonQuery(this.CreateCommand(command), connection); } /// <summary> /// Executes the specified command /// </summary> /// <param name="command">The command to use</param> /// <param name="connection">The open IDbConnection to use</param> /// <param name="transaction">The transaction to execute under</param> public void ExecuteNonQuery(string command, IDbConnection connection, IDbTransaction transaction) { this.ExecuteNonQuery(this.CreateCommand(command), connection, transaction); } #endregion #region IDataSetAccessObject Members /// <summary> /// Saves the specified DataSet /// </summary> /// <param name="ds">The DataSet to save</param> /// <returns>Number of modified records</returns> public int SaveDS(DataSet ds) { int i; using (IDbConnection conn = this.CreateConnection()) { conn.Open(); i = this.SaveDS(ds, conn); } return i; } /// <summary> /// Saves the specified DataSet /// </summary> /// <param name="ds">The DataSet to save</param> /// <param name="conn">The open IDbConnection to use</param> /// <returns>Number of modified records</returns> public virtual int SaveDS(DataSet ds, IDbConnection conn) { DbDataAdapter da = DbProviderFactory.CreateDataAdapter(this.Provider, this.CreateSelectAllCommand(), conn); int modified = 0; DataSet modifiedDS = ds.GetChanges(); if (modifiedDS != null) { if (this.Provider == DbProviderType.SQLSERVER) { SqlCommandBuilder cb = new SqlCommandBuilder((SqlDataAdapter) da); foreach (DataTable dt in modifiedDS.Tables) { modified += da.Update(modifiedDS, dt.TableName); } } else { OleDbCommandBuilder cb = new OleDbCommandBuilder((OleDbDataAdapter) da); foreach (DataTable dt in modifiedDS.Tables) { modified += da.Update(modifiedDS, dt.TableName); } } return modified; } else { return 0; } } /// <summary> /// Selects all records /// </summary> /// <returns></returns> public DataSet SelectAllDS() { return this.CreateDataSet(this.CreateSelectAllCommand()); } /// <summary> /// Selects all records /// </summary> /// <param name="conn">The open IDbConnection to use</param> /// <returns></returns> public DataSet SelectAllDS(IDbConnection conn) { return this.GetDataSet(this.CreateSelectAllCommand(), conn); } /// <summary> /// Creates a DataSet using the given command /// </summary> /// <param name="cmd">The command to execute</param> /// <returns></returns> public DataSet SelectDS(IDbCommand cmd) { return this.CreateDataSet(cmd); } /// <summary> /// Creates a DataSet using the given command /// </summary> /// <param name="sql">The sql command to execute</param> /// <returns></returns> public DataSet SelectDS(string sql) { return this.SelectDS(this.CreateCommand(sql)); } /// <summary> /// Creates a DataSet using the given command /// </summary> /// <param name="sql">The sql command to execute</param> /// <param name="conn">The open IDbConnection to use</param> /// <returns></returns> public DataSet SelectDS(string sql, IDbConnection conn) { return this.GetDataSet(this.CreateCommand(sql), conn); } /// <summary> /// Creates a DataSet using the given command /// </summary> /// <param name="cmd">The command to execute</param> /// <param name="conn">The open IDbConnection to use</param> /// <returns></returns> public DataSet SelectDS(IDbCommand cmd, IDbConnection conn) { return this.GetDataSet(cmd, conn); } /// <summary> /// Returns one record wrapped in a DataSet /// </summary> /// <param name="id">The id of the record to select</param> /// <returns></returns> public DataSet SelectDatasetById(object id) { return this.SelectOneDS(id); } /// <summary> /// Returns one record wrapped in a DataSet /// </summary> /// <param name="id">The id of the record to select</param> /// <param name="conn">The open IDbConnection to use</param> /// <returns></returns> public DataSet SelectDatasetById(object id, IDbConnection conn) { return this.SelectOneDS(id, conn); } /// <summary> /// Returns one record wrapped in a DataSet /// </summary> /// <param name="id">The id of the record to select</param> /// <returns></returns> /// [Obsolete("Deprecated. Please use SelectDataSetById")] public DataSet SelectOneDS(object id) { return this.CreateDataSet(this.CreateSelectOneCommand(id)); } /// <summary> /// Returns one record wrapped in a DataSet /// </summary> /// <param name="id">The id of the record to select</param> /// <param name="conn">The open IDbConnection to use</param> /// <returns></returns> [Obsolete("Deprecated. Please use SelectDataSetById")] public DataSet SelectOneDS(object id, IDbConnection conn) { return this.GetDataSet(this.CreateSelectOneCommand(id), conn); } #endregion #region IDataReaderMapper Members /// <summary> /// Maps a collection of objects, using the specified DataReader /// </summary> /// <param name="dr">The DataReader to use for the object mapping</param> /// <returns></returns> public IList MapObjects(IDataReader dr) { ArrayList al = new ArrayList(); while (dr.Read()) { al.Add(this.MapObject(dr)); } return al; } #endregion #region Other Members /// <summary> /// Gets the total count of records /// </summary> /// <returns></returns> public int GetCount() { return this.GetCount(null); } /// <summary> /// Gets the total count of records /// </summary> /// <param name="criteria">The criteria to query with</param> /// <returns></returns> public int GetCount(ICriteria criteria) { int count = 0; ISelectQuery query = QueryFactory.CreateSelectQuery(this.db); query.SetTable(this.table); query.AddCountAll(); if (criteria != null) { query.SetCriteria(criteria); } using (IDbConnection conn = this.CreateConnection()) { conn.Open(); IDataReader dr = DbProviderFactory.CreateDataReader(conn, this.CreateCommand(query.GetText()), this.provider); if (dr.Read()) { count = dr.GetInt32(0); } dr.Close(); } return count; } /// <summary> /// Creates the correct ISelectQuery implementation for the specified database /// </summary> /// <returns></returns> public ISelectQuery CreateSelectQuery() { ISelectQuery query = QueryFactory.CreateSelectQuery(this.db, this.provider); query.SetTable(this.Table); return query; } /// <summary> /// Creates the correct IDeleteQuery implementation for the specified database /// </summary> /// <returns></returns> public IDeleteQuery CreateDeleteQuery() { IDeleteQuery query = QueryFactory.CreateDeleteQuery(this.db, this.provider); query.SetTable(this.Table); return query; } /// <summary> /// Creates the correct IInsertQuery implementation for the specified database /// </summary> /// <returns></returns> public IInsertQuery CreateInsertQuery() { IInsertQuery query = QueryFactory.CreateInsertQuery(this.db, this.provider); query.SetTable(this.Table); return query; } /// <summary> /// Creates the correct IUpdateQuery implementation for the specified database /// </summary> /// <returns></returns> public IUpdateQuery CreateUpdateQuery() { IUpdateQuery query = QueryFactory.CreateUpdateQuery(this.db, this.provider); query.SetTable(this.Table); return query; } #endregion #region Properties /// <summary> /// The connection string /// </summary> public string ConnectionString { get { return this.connectionString; } set { this.connectionString = value; } } /// <summary> /// The database provider type /// </summary> public DbProviderType Provider { get { return this.provider; } set { this.provider = value; } } /// <summary> /// The database type /// </summary> public DbType Db { get { return this.db; } set { this.db = value; } } /// <summary> /// The name of the table /// </summary> public string Table { get { return this.table; } set { this.table = value; } } #endregion #region Helper Methods /// <summary> /// Creates a DataSet, using the given command /// </summary> /// <param name="cmd">The command to execute</param> /// <returns></returns> protected DataSet CreateDataSet(IDbCommand cmd) { return DbProviderFactory.CreateDataSet(this.connectionString, cmd, this.provider); } /// <summary> /// Creates a DataSet, using the given command /// </summary> /// <param name="cmd">The command to execute</param> /// <returns></returns> protected DataSet CreateDataSet(string cmd) { return DbProviderFactory.CreateDataSet(this.connectionString, this.CreateCommand(cmd), this.provider); } /// <summary> /// Creates a DataSet, using the given command /// </summary> /// <param name="cmd">The command to execute</param> /// <param name="conn">The open connection to use</param> /// <returns></returns> protected DataSet GetDataSet(IDbCommand cmd, IDbConnection conn) { return DbProviderFactory.CreateDataSet(conn, cmd, this.provider); } /// <summary> /// Creates a connection with the proper connection string filled in /// </summary> /// <returns></returns> public IDbConnection CreateConnection() { IDbConnection connection = DbProviderFactory.CreateConnection(this.provider); connection.ConnectionString = this.connectionString; return connection; } /// <summary> /// Creates a command for the correct database provider /// and sets the connection /// </summary> /// <param name="command">The command to execute</param> /// <returns></returns> public IDbCommand CreateCommand(string command) { IDbCommand cmd = DbProviderFactory.CreateCommand(this.provider); cmd.CommandText = command; cmd.Connection = this.CreateConnection(); return cmd; } /// <summary> /// Creates a command to select all records /// </summary> /// <returns></returns> protected IDbCommand CreateSelectAllCommand() { IDbCommand command = DbProviderFactory.CreateCommand(this.provider); ISelectQuery s = QueryFactory.CreateSelectQuery(this.db); s.AddAll(); s.SetTable(this.Table); command.CommandText = s.GetText(); return command; } /// <summary> /// Creates a command to delete all records /// </summary> /// <returns></returns> protected IDbCommand CreateDeleteAllCommand() { IDbCommand command = DbProviderFactory.CreateCommand(this.provider); IDeleteQuery s = QueryFactory.CreateDeleteQuery(this.db, this.provider); s.SetTable(this.Table); command.CommandText = s.GetText(); return command; } #endregion #region Custom Items /// <summary> /// Used for custom actions when Save is called. Allows for retrieval /// of autoinsert fields, etc. using the open connection. /// </summary> /// <param name="o"></param> /// <param name="connection"></param> protected virtual void CustomSave(object o, IDbConnection connection){} protected virtual void CustomSave(object o, IDbConnection connection, IDbTransaction transaction){} #endregion #region Abstract Items /// <summary> /// Maps an individual object to a DataReader row /// </summary> /// <param name="dr"></param> /// <returns></returns> protected abstract object MapObject(IDataReader dr); /// <summary> /// Selects one record, using the specified id /// </summary> /// <param name="id">The id of the record to select</param> /// <returns></returns> protected abstract IDbCommand CreateSelectOneCommand(object id); /// <summary> /// Updates a record, using the values from the specified object /// </summary> /// <param name="o"></param> /// <returns></returns> protected abstract IDbCommand CreateUpdateCommand(object o); /// <summary> /// Inserts a record, using the values from the specified object /// </summary> /// <param name="o"></param> /// <returns></returns> protected abstract IDbCommand CreateInsertCommand(object o); /// <summary> /// Deletes one record, using the specified id /// </summary> /// <param name="id"></param> /// <returns></returns> protected abstract IDbCommand CreateDeleteOneCommand(object id); #endregion } } --- NEW FILE: ITransferObject.cs --- namespace Adapdev.Data { /// <summary> /// Represents a Transfer Object (an object that can be passed between /// application layers and between remote applications, and is focused purely /// on holding data). /// </summary> /// <remarks>See Martin Fowler's Patterns of Enterprise Applications, or the J2EE /// Core Patterns for more information</remarks> public interface ITransferObject { } } --- NEW FILE: DbConstants.cs --- namespace Adapdev.Data { /// <summary> /// Provides string representation of database names /// </summary> public class DbConstants { public const string SQLSERVER = "sqlserver"; public const string ORACLE = "oracle"; public const string ACCESS = "access"; public const string MYSQL = "mysql"; public const string DB2 = "db2"; } } --- NEW FILE: DbProviderTypeConverter.cs --- namespace Adapdev.Data { using System; /// <summary> /// Summary description for DbProviderTypeConverter. /// </summary> public class DbProviderTypeConverter { public static DbProviderType Convert(string s) { switch (s.Trim().ToLower()) { case "unknown": return DbProviderType.UNKNOWN; case "db2": return DbProviderType.DB2; case "mysql": return DbProviderType.MYSQL; case "odbc": return DbProviderType.ODBC; case "oledb": return DbProviderType.OLEDB; case "oracle": return DbProviderType.ORACLE; case "sqlserver": case "sqlclient": return DbProviderType.SQLSERVER; default: throw new Exception("DbProviderType " + s + " not found."); } } public static string Convert(DbProviderType t) { switch (t) { case DbProviderType.UNKNOWN: return "UNKNOWN"; case DbProviderType.ODBC: return "ODBC"; case DbProviderType.OLEDB: return "OLEDB"; case DbProviderType.ORACLE: return "ORACLE"; case DbProviderType.SQLSERVER: return "SQLSERVER"; case DbProviderType.MYSQL: return "MYSQL"; case DbProviderType.DB2: return "DB2"; default: throw new Exception("DbProviderType " + t.ToString() + " not found."); } } } } --- NEW FILE: DbTypeConverter.cs --- namespace Adapdev.Data { using System; /// <summary> /// Converts strings to their corresponding DbType /// </summary> public class DbTypeConverter { public static DbType Convert(string s) { switch (s.Trim().ToLower()) { case "unknown": return DbType.UNKNOWN; case "access": return DbType.ACCESS; case "db2": return DbType.DB2; case "mysql": return DbType.MYSQL; case "oracle": return DbType.ORACLE; case "sqlserver": case "sqlclient": return DbType.SQLSERVER; default: throw new Exception("DbType " + s + " not found."); } } public static string Convert(DbType t) { switch (t) { case DbType.UNKNOWN: return "UNKNOWN"; case DbType.ACCESS: return "ACCESS"; case DbType.DB2: return "DB2"; case DbType.MYSQL: return "MYSQL"; case DbType.ORACLE: return "ORACLE"; case DbType.SQLSERVER: return "SQLSERVER"; default: throw new Exception("DbType " + t.ToString() + " not found."); } } } } --- NEW FILE: IDataReaderMapper.cs --- namespace Adapdev.Data { using System.Collections; using System.Data; /// <summary> /// Summary description for IDataReaderMapper. /// </summary> public interface IDataReaderMapper { IList MapObjects(IDataReader dr); } } --- NEW FILE: IDataSetAccessObject.cs --- namespace Adapdev.Data { using System.Data; /// <summary> /// Provides DataSet-centric data access /// </summary> public interface IDataSetAccessObject { /// <summary> /// Persists a DataSet to the underlying datastore /// </summary> /// <param name="ds">The DataSet to persist</param> /// <returns></returns> int SaveDS(DataSet ds); /// <summary> /// Returns a DataSet populated with the record that matches the passed in id /// </summary> /// <param name="id">The id of the record to retrieve</param> /// <returns></returns> DataSet SelectOneDS(object id); /// <summary> /// Returns a DataSet populated with all records from the underlying datastore /// </summary> /// <returns></returns> DataSet SelectAllDS(); } } --- NEW FILE: IDataAccessObject.cs --- namespace Adapdev.Data { using System.Collections; /// <summary> /// Provides access to an underlying datastore /// </summary> public interface IDataAccessObject { /// <summary> /// Saves the specified object to the underlying datastore /// </summary> /// <param name="o">The object to persist</param> void Save(object o); /// <summary> /// Deletes the specified object from the underlying datastore, using /// the passed in id /// </summary> /// <param name="id">The id of the object to delete</param> void Delete(object id); /// <summary> /// Updates the specified object in the underlying datastore /// </summary> /// <param name="o">The object to update</param> void Update(object o); /// <summary> /// Selects an IList of objects that match the specified string criteria /// </summary> /// <param name="s">The criteria to use (for example, an XPath statement, SQL query, etc.)</param> /// <returns></returns> IList Select(string s); /// <summary> /// Retrieves all objects in the underlying datastore /// </summary> /// <returns></returns> IList SelectAll(); /// <summary> /// Retrieves an object with the matching id /// </summary> /// <param name="id">The id of the object to retrieve</param> /// <returns></returns> object SelectOne(object id); /// <summary> /// Gets the number of persisted objects in the underlying datastore /// </summary> /// <returns></returns> int GetCount(); } } --- NEW FILE: ProviderInfoManager.cs --- namespace Adapdev.Data { using System; using System.Collections; using System.Data; using System.IO; using System.Reflection; using Adapdev.Data.Mappings; using Adapdev.Data; using Adapdev.Data.Xml; /// <summary> /// Provides provider specific information related to data types /// and their corresponding object types /// </summary> public class ProviderInfoManager { private static ProviderInfoManager instance; private static readonly Hashtable ht = new Hashtable(); private static readonly ProvidersInfo ds = new ProvidersInfo(); /// <summary> /// Creates a new <see cref="ProviderInfoManager"/> instance. /// </summary> private ProviderInfoManager() { Stream s =Assembly.GetExecutingAssembly().GetManifestResourceStream("Adapdev.Data.Xml.ProviderInfo.xml"); ds.ReadXml(s); this.LoadTypes(); if (ht.Count == 0) { throw new Exception("DatabaseProviders contains no information."); } } /// <summary> /// Gets the instance. /// </summary> /// <returns></returns> public static ProviderInfoManager GetInstance() { if (instance == null) { instance = new ProviderInfoManager(); } return instance; } /// <summary> /// Loads the types. /// </summary> private void LoadTypes() { foreach (ProvidersInfo.ProviderInfoRow dr in ds.ProviderInfo.Rows) { Hashtable tht = new Hashtable(); ht.Add(dr.Name.Trim().ToLower(), tht); } foreach (ProvidersInfo.TypeRow tr in ds.Type.Rows) { Hashtable tht = (Hashtable) ht[tr.ProviderInfoRow.Name.Trim().ToLower()]; tht.Add(tr.Name.ToLower(), tr); } } /// <summary> /// Gets the prefix by name /// </summary> /// <param name="name">Name.</param> /// <param name="typeName">Name of the type.</param> /// <returns></returns> public string GetPrefixByName(string name, string typeName) { return this.GetTypeRowByName(name, typeName).Prefix; } /// <summary> /// Gets the prefix by name /// </summary> /// <param name="ct">Ct.</param> /// <param name="typeName">Name of the type.</param> /// <returns></returns> public string GetPrefixByName(DbProviderType ct, string typeName) { return this.GetPrefixByName(ct.ToString(), typeName); } /// <summary> /// Gets the postfix by name /// </summary> /// <param name="name">Name.</param> /// <param name="typeName">Name of the type.</param> /// <returns></returns> public string GetPostfixByName(string name, string typeName) { return this.GetTypeRowByName(name, typeName).Postfix; } /// <summary> /// Gets the postfix by name /// </summary> /// <param name="ct">Ct.</param> /// <param name="typeName">Name of the type.</param> /// <returns></returns> public string GetPostfixByName(DbProviderType ct, string typeName) { return this.GetPostfixByName(ct.ToString(), typeName); } /// <summary> /// Gets the postfix by name /// </summary> /// <param name="name">Name.</param> /// <param name="typeName">Name of the type.</param> /// <returns></returns> public string GetObjectByName(string name, string typeName) { return this.GetTypeRowByName(name, typeName).Object; } /// <summary> /// Gets the object by name /// </summary> /// <param name="providerType">Provider type</param> /// <param name="typeName">Name of the type.</param> /// <returns></returns> public string GetObjectByName(DbProviderType providerType, string typeName) { return this.GetObjectByName(providerType.ToString(), typeName); } /// <summary> /// Gets the object by id. /// </summary> /// <param name="name">Name.</param> /// <param name="id">Id.</param> /// <returns></returns> public string GetObjectById(string name, int id) { ProviderInfo p = this.GetTypeRowById(name, id); if (p != null) return p.Object; else return ""; } /// <summary> /// Gets the object by id. /// </summary> /// <param name="ct">Ct.</param> /// <param name="id">Id.</param> /// <returns></returns> public string GetObjectById(DbProviderType ct, int id) { return this.GetObjectById(ct.ToString(), id); } /// <summary> /// Gets the name by id. /// </summary> /// <param name="name">Name.</param> /// <param name="id">Id.</param> /// <returns></returns> public string GetNameById(string name, int id) { ProviderInfo p = this.GetTypeRowById(name, id); if (p != null) return p.Name; else return ""; } /// <summary> /// Gets the name by id. /// </summary> /// <param name="providerType">Provider type.</param> /// <param name="id">Id.</param> /// <returns></returns> public string GetNameById(DbProviderType providerType, int id) { return this.GetNameById(providerType.ToString(), id); } /// <summary> /// Gets the default by id. /// </summary> /// <param name="name">Name.</param> /// <param name="id">Id.</param> /// <returns></returns> public string GetDefaultById(string name, int id) { ProviderInfo p = this.GetTypeRowById(name, id); if (p != null) return p.Default; else return ""; } /// <summary> /// Gets the default by id. /// </summary> /// <param name="providerType">Provider type.</param> /// <param name="id">Id.</param> /// <returns></returns> public string GetDefaultById(DbProviderType providerType, int id) { return this.GetDefaultById(providerType.ToString(), id); } /// <summary> /// Gets the test default by id. /// </summary> /// <param name="name">Name.</param> /// <param name="id">Id.</param> /// <returns></returns> public string GetTestDefaultById(string name, int id) { ProviderInfo p = this.GetTypeRowById(name, id); if (p != null) return p.TestDefault; else return ""; } /// <summary> /// Gets the test default by id. /// </summary> /// <param name="providerType">Provider type.</param> /// <param name="id">Id.</param> /// <returns></returns> public string GetTestDefaultById(DbProviderType providerType, int id) { return this.GetTestDefaultById(providerType.ToString(), id); } /// <summary> /// Gets the name of the id by. /// </summary> /// <param name="name">Name.</param> /// <param name="typeName">Name of the type.</param> /// <returns></returns> public int GetIdByName(string name, string typeName) { return Convert.ToInt32(this.GetTypeRowByName(name, typeName).Id); } /// <summary> /// Gets the name of the id by. /// </summary> /// <param name="providerType">Provider type.</param> /// <param name="typeName">Name of the type.</param> /// <returns></returns> public int GetIdByName(DbProviderType providerType, string typeName) { return this.GetIdByName(providerType.ToString(), typeName); } /// <summary> /// Gets the name of the type row by. /// </summary> /// <param name="name">Name.</param> /// <param name="typeName">Name of the type.</param> /// <returns></returns> protected ProviderInfo GetTypeRowByName(string name, string typeName) { string _name = name.Trim().ToLower(); string _typeName = typeName.Trim().ToLower(); if (ht.Contains(_name)) { Hashtable tht = (Hashtable) ht[_name]; if (tht.Contains(_typeName)) { ProvidersInfo.TypeRow tr = (ProvidersInfo.TypeRow) tht[_typeName]; return this.BuildProviderInfo(tr); } } else { throw new Exception(String.Format("TypeRow not found. name: {0}, typeName: {1}", name, typeName)); } return null; } /// <summary> /// Gets the type row by id. /// </summary> /// <param name="name">Name.</param> /// <param name="id">Id.</param> /// <returns></returns> protected ProviderInfo GetTypeRowById(string name, int id) { string _name = name.Trim().ToLower(); if (ht.Contains(_name)) { Hashtable tht = (Hashtable) ht[_name]; foreach (DictionaryEntry d in tht) { ProvidersInfo.TypeRow tr = (ProvidersInfo.TypeRow) d.Value; if (tr.Id.Equals(id.ToString())) return this.BuildProviderInfo(tr); } } else { throw new Exception(String.Format("TypeRow not found. name: {0}, id: {1}", name, id)); } return null; } /// <summary> /// Builds the provider info. /// </summary> /// <param name="r">Row.</param> /// <returns></returns> protected ProviderInfo BuildProviderInfo(ProvidersInfo.TypeRow r) { ProviderInfo pr = new ProviderInfo(); pr.Default = r.Default; pr.Id = r.Id; pr.Name = r.Name; pr.Object = r.Object; pr.Postfix = r.Postfix; pr.Prefix = r.Prefix; pr.TestDefault = r.TestDefault; return pr; } } } --- NEW FILE: IDbDataSetAccessObject.cs --- namespace Adapdev.Data { using System.Data; /// <summary> /// Provides DataSet-centric operations /// </summary> public interface IDbDataSetAccessObject : IDataSetAccessObject { /// <summary> /// Saves a DataSet to the underlying datastore /// </summary> /// <param name="ds">The dataset to save</param> /// <param name="conn">The connection to use</param> /// <returns>Number of records affected</returns> int SaveDS(DataSet ds, IDbConnection conn); /// <summary> /// Returns a DataSet, most likely with one DataTable DataRow. It fills /// the DataSet by grabbing a record with a matching id /// </summary> /// <param name="id">The id of the record to retrieve</param> /// <param name="conn">The connection to use</param> /// <returns></returns> DataSet SelectOneDS(object id, IDbConnection conn); /// <summary> /// Returns a DataSet populated with all records /// </summary> /// <param name="conn">The connection to use</param> /// <returns></returns> DataSet SelectAllDS(IDbConnection conn); /// <summary> /// Returns a DataSet with records that match the command /// </summary> /// <param name="cmd">The command to use</param> /// <returns></returns> DataSet SelectDS(IDbCommand cmd); /// <summary> /// Returns a DataSet with records that match the command /// </summary> /// <param name="cmd">The command to use</param> /// <param name="conn">The connection to use</param> /// <returns></returns> DataSet SelectDS(IDbCommand cmd, IDbConnection conn); /// <summary> /// Executes the specified command /// </summary> /// <param name="cmd">The command to use</param> void ExecuteNonQuery(IDbCommand cmd); /// <summary> /// Executes the specified command /// </summary> /// <param name="cmd">The command to use</param> /// <param name="conn">The connection to use</param> void ExecuteNonQuery(IDbCommand cmd, IDbConnection conn); } } --- NEW FILE: DbType.cs --- namespace Adapdev.Data { /// <summary> /// Summary description for DbType. /// </summary> public enum DbType { UNKNOWN, ACCESS, SQLSERVER, MYSQL, ORACLE, DB2 } } --- NEW FILE: CommandTextViewer.cs --- namespace Adapdev.Data { using System; using System.Data; using System.Text; /// <summary> /// CommandStringBuilder takes an IDbCommand and creates a fully filled in sql text, replacing /// parameter designations with their actual values /// </summary> public class CommandTextViewer { private static readonly ProviderInfoManager dp = ProviderInfoManager.GetInstance(); /// <summary> /// Returns the fully filled-in sql text for a specified IDbCommand /// </summary> /// <param name="cmd"></param> /// <param name="providerType"></param> /// <returns></returns> public static string Parse(IDbCommand cmd, DbProviderType providerType) { if (providerType == DbProviderType.OLEDB) { return ParseOleDbCommand(cmd); } else if (providerType == DbProviderType.SQLSERVER) { return ParseSqlCommand(cmd); } else if (providerType == DbProviderType.ORACLE) { return ParseOracleCommand(cmd); } else throw new NotImplementedException(providerType.ToString() + " is not currently supported."); } /// <summary> /// This is a worker method, which takes an OleDbCommand and builds the sql text, with the parameter values added into it. /// </summary> /// <param name="cmd">The command.</param> /// <returns>A sql string with all of the parameter values filled in.</returns> public static string ParseOleDbCommand(IDbCommand cmd) { string cmds = cmd.CommandText.ToString().Trim(); StringBuilder scmds = new StringBuilder(cmds); if (cmd.CommandType == CommandType.Text) { for (int i = cmd.Parameters.Count - 1; i >= 0; i--) { string pvalue = ""; string pname = ((IDataParameter) cmd.Parameters[i]).ParameterName; if (((IDataParameter) cmd.Parameters[i]).Value == null) { pvalue = DBNull.Value.ToString(); } else { pvalue = ((IDataParameter) cmd.Parameters[i]).Value.ToString(); } string ptype = ((IDataParameter) cmd.Parameters[i]).DbType.ToString(); string prefix = dp.GetPrefixByName("dbtype_oledb", ptype); string newValue = prefix + pvalue + prefix; // Console.WriteLine(newValue); int qindex = scmds.ToString().LastIndexOf("?"); //Console.WriteLine(qindex + " : " + scmds.ToString().Length); //if(qindex == scmds.ToString().Length - 1) qindex = qindex - 1; if (qindex > 0) scmds.Replace("?", newValue, qindex, 1); } cmds = scmds.ToString(); } else if (cmd.CommandType == CommandType.StoredProcedure) { StringBuilder sb = new StringBuilder(); sb.Append("{call "); sb.Append(cmds + "("); for (int i = 0; i < cmd.Parameters.Count; i++) { string pvalue = ""; string pname = ((IDataParameter) cmd.Parameters[i]).ParameterName; if (((IDataParameter) cmd.Parameters[i]).Value == null) { pvalue = DBNull.Value.ToString(); } else { pvalue = ((IDataParameter) cmd.Parameters[i]).Value.ToString(); } string ptype = ((IDataParameter) cmd.Parameters[i]).DbType.ToString(); string prefix = dp.GetPrefixByName("dbtype_oledb", ptype); string newValue = prefix + pvalue + prefix; string comma = ","; if (i >= cmd.Parameters.Count - 1) { comma = ""; } sb.Append(" " + newValue + comma); } sb.Append(" )}"); cmds = sb.ToString(); } return cmds; } /// <summary> /// This is a worker method, which takes an SqlCommand and builds the sql text, with the parameter values added into it. /// </summary> /// <param name="cmd">The command.</param> /// <returns>A sql string with all of the parameter values filled in.</returns> public static string ParseSqlCommand(IDbCommand cmd) { string cmds = cmd.CommandText.ToString().Trim(); if (cmd.CommandType == CommandType.Text) { for (int i = 0; i < cmd.Parameters.Count; i++) { string pvalue = ""; string pname = ((IDataParameter) cmd.Parameters[i]).ParameterName; if (((IDataParameter) cmd.Parameters[i]).Value == null) { pvalue = DBNull.Value.ToString(); } else { pvalue = ((IDataParameter) cmd.Parameters[i]).Value.ToString(); } string ptype = ((IDataParameter) cmd.Parameters[i]).DbType.ToString(); string prefix = dp.GetPrefixByName("dbtype_sqlclient", ptype); string newValue = prefix + pvalue + prefix; cmds = cmds.Replace(pname, newValue); } } else if (cmd.CommandType == CommandType.StoredProcedure) { StringBuilder sb = new StringBuilder(); sb.Append("EXEC "); sb.Append(cmds); for (int i = 0; i < cmd.Parameters.Count; i++) { string pvalue = ""; string pname = ((IDataParameter) cmd.Parameters[i]).ParameterName; if (((IDataParameter) cmd.Parameters[i]).Value == null) { pvalue = DBNull.Value.ToString(); } else { pvalue = ((IDataParameter) cmd.Parameters[i]).Value.ToString(); } string ptype = ((IDataParameter) cmd.Parameters[i]).DbType.ToString(); string prefix = dp.GetPrefixByName("dbtype_sqlclient", ptype); string newValue = prefix + pvalue + prefix; string comma = ","; if (i >= cmd.Parameters.Count - 1) { comma = ""; } sb.Append(" " + newValue + comma); } cmds = sb.ToString(); } return cmds; } /// <summary> /// This is a worker method, which takes an OracleCommand and builds the sql text, /// with the parameter values added into it. /// </summary> /// <param name="cmd">The command.</param> /// <returns>A sql string with all of the parameter values filled in.</returns> public static string ParseOracleCommand(IDbCommand cmd) { string cmds = cmd.CommandText.ToString().Trim(); if (cmd.CommandType == CommandType.Text) { for (int i = 0; i < cmd.Parameters.Count; i++) { string pvalue = ""; string pname = ((IDataParameter) cmd.Parameters[i]).ParameterName; if (((IDataParameter) cmd.Parameters[i]).Value == null) { pvalue = DBNull.Value.ToString(); } else { pvalue = ((IDataParameter) cmd.Parameters[i]).Value.ToString(); } string ptype = ((IDataParameter) cmd.Parameters[i]).DbType.ToString(); string prefix = dp.GetPrefixByName("oracle", ptype); string newValue = prefix + pvalue + prefix; cmds = cmds.Replace(pname, newValue); } } else if (cmd.CommandType == CommandType.StoredProcedure) { StringBuilder sb = new StringBuilder(); sb.Append("CREATE OR REPLACE"); sb.Append(cmds); for (int i = 0; i < cmd.Parameters.Count; i++) { string pvalue = ""; string pname = ((IDataParameter) cmd.Parameters[i]).ParameterName; if (((IDataParameter) cmd.Parameters[i]).Value == null) { pvalue = DBNull.Value.ToString(); } else { pvalue = ((IDataParameter) cmd.Parameters[i]).Value.ToString(); } string ptype = ((IDataParameter) cmd.Parameters[i]).DbType.ToString(); string prefix = dp.GetPrefixByName("oracle", ptype); string newValue = prefix + pvalue + prefix; string comma = ","; if (i >= cmd.Parameters.Count - 1) { comma = ""; } sb.Append(" " + newValue + comma); } cmds = sb.ToString(); } return cmds; } } } --- NEW FILE: Adapdev.Data.csproj --- <VisualStudioProject> <CSHARP ProjectType = "Local" ProductVersion = "7.10.3077" SchemaVersion = "2.0" ProjectGuid = "{08C5794D-44ED-4E75-A1C1-48A28C3D0044}" > <Build> <Settings ApplicationIcon = "" AssemblyKeyContainerName = "" AssemblyName = "Adapdev.Data" AssemblyOriginatorKeyFile = "" DefaultClientScript = "JScript" DefaultHTMLPageLayout = "Grid" DefaultTargetSchema = "IE50" DelaySign = "false" OutputType = "Library" PreBuildEvent = "" PostBuildEvent = "" RootNamespace = "Adapdev.Data" RunPostBuildEvent = "OnBuildSuccess" StartupObject = "" > <Config Name = "Debug" AllowUnsafeBlocks = "false" BaseAddress = "285212672" CheckForOverflowUnderflow = "false" ConfigurationOverrideFile = "" DefineConstants = "DEBUG;TRACE" DocumentationFile = "" DebugSymbols = "true" FileAlignment = "4096" IncrementalBuild = "false" NoStdLib = "false" NoWarn = "" Optimize = "false" OutputPath = "bin\Debug\" RegisterForComInterop = "false" RemoveIntegerChecks = "false" TreatWarningsAsErrors = "false" WarningLevel = "4" /> <Config Name = "Release" AllowUnsafeBlocks = "false" BaseAddress = "285212672" CheckForOverflowUnderflow = "false" ConfigurationOverrideFile = "" DefineConstants = "TRACE" DocumentationFile = "" DebugSymbols = "false" FileAlignment = "4096" IncrementalBuild = "false" NoStdLib = "false" NoWarn = "" Optimize = "true" OutputPath = "bin\Release\" RegisterForComInterop = "false" RemoveIntegerChecks = "false" TreatWarningsAsErrors = "false" WarningLevel = "4" /> </Settings> <References> <Reference Name = "System" AssemblyName = "System" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.dll" /> <Reference Name = "System.Data" AssemblyName = "System.Data" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.Data.dll" /> <Reference Name = "System.XML" AssemblyName = "System.Xml" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.XML.dll" /> <Reference Name = "Adapdev" Project = "{CC30A321-2569-4B1F-8E1A-781B5509B56D}" Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" /> <Reference Name = "System.Data.OracleClient" AssemblyName = "System.Data.OracleClient" HintPath = "..\..\..\..\..\WINDOWS\Microsoft.NET\Framework\v1.1.4322\Syste... [truncated message content] |
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.CodeGen In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv19977/src/Adapdev.CodeGen Added Files: AbstractCodeDomTemplate.cs AbstractCodeTemplate.cs AbstractConfig.cs AbstractSchemaConfig.cs Adapdev.CodeGen.csproj CodeGenerator.cs CodeType.cs CompilerFactory.cs DataSetHelper.cs ICodeDomTemplate.cs ICodeDomTemplateEventArgs.cs ICodeTemplate.cs ICodeTemplateEventArgs.cs INVelocityTemplate.cs LanguageType.cs NVelocityCodeTemplate.cs NVelocityTableCodeTemplate.cs TableCodeDomTemplate.cs TableCodeTemplate.cs UnitTestType.cs Log Message: Reposting to the repository after it got hosed --- NEW FILE: DataSetHelper.cs --- using System; using System.Data; using Adapdev.Data; using Adapdev.Data.Schema; namespace Adapdev.CodeGen { public class DataHelper { private DatabaseSchema schema = null; public DataHelper(DatabaseSchema schema) { this.schema = schema; } public DataTable GetDataTable(DataSet dataset, string dataTableName) { return dataset.Tables[dataTableName]; } public DataColumn GetDataColumn(DataTable table, string dataColumnName) { return table.Columns[dataColumnName]; } public object GetColumnValue(DataRow row, string columnName) { return row[columnName]; } public DataSet GetDataSet(string query) { try { IDbCommand command = DbProviderFactory.CreateCommand(schema.DatabaseProviderType); command.CommandText = query; return DbProviderFactory.CreateDataSet(schema.ConnectionString, command, schema.DatabaseProviderType); } catch(Exception e) { Console.WriteLine(e.Message); } return null; } } } --- NEW FILE: AbstractCodeDomTemplate.cs --- namespace Adapdev.CodeGen { using System; using System.CodeDom; /// <summary> /// Summary description for AbstractTemplate. /// </summary> public abstract class AbstractCodeDomTemplate : ICodeDomTemplate { protected string fileName = String.Empty; protected string className = String.Empty; protected string outputDir = String.Empty; protected string nameSpace = String.Empty; protected bool overwrite = true; /// <summary> /// Creates a new <see cref="AbstractCodeDomTemplate"/> instance. /// </summary> /// <param name="fileName">Name of the file.</param> /// <param name="className">Name of the class.</param> /// <param name="nameSpace">Namespace.</param> public AbstractCodeDomTemplate(string fileName, string className, string nameSpace) { this.fileName = fileName; this.className = className; this.nameSpace = nameSpace; } /// <summary> /// Gets or sets the name of the file. /// </summary> /// <value></value> public string FileName { get { return this.fileName; } set { this.fileName = value; } } /// <summary> /// Gets or sets the name of the class. /// </summary> /// <value></value> public string ClassName { get { return this.className; } set { this.className = value; } } /// <summary> /// Gets or sets the output directory. /// </summary> /// <value></value> public virtual string OutputDirectory { get { return this.outputDir; } set { this.outputDir = value; } } /// <summary> /// Gets or sets the namespace. /// </summary> /// <value></value> public virtual string Namespace { get { return this.nameSpace; } set { this.nameSpace = value; } } /// <summary> /// Gets or sets a value indicating whether generated file can be overwritten /// </summary> /// <value> /// <c>true</c> if it can be overwritten; otherwise, <c>false</c>. /// </value> public virtual bool Overwrite { get { return this.overwrite; } set { this.overwrite = value; } } /// <summary> /// Processes the custom code. /// </summary> public virtual void ProcessCustomCode() { } /// <summary> /// Gets the code compile unit. /// </summary> /// <returns></returns> public abstract CodeCompileUnit GetCodeCompileUnit(); } } --- NEW FILE: INVelocityTemplate.cs --- using System; using NVelocity; namespace Adapdev.CodeGen { /// <summary> /// Summary description for INVelocityTemplate. /// </summary> public interface INVelocityTemplate { /// <summary> /// Gets the context. /// </summary> /// <value></value> VelocityContext Context{get;} } } --- NEW FILE: ICodeTemplate.cs --- namespace Adapdev.CodeGen { /// <summary> /// Summary description for ICodeTemplate. /// </summary> public interface ICodeTemplate { /// <summary> /// Gets the code. /// </summary> /// <returns></returns> string GetCode(); /// <summary> /// Gets or sets the name of the file. /// </summary> /// <value></value> string FileName { get; set; } /// <summary> /// Gets or sets the name of the class. /// </summary> /// <value></value> string ClassName { get; set; } /// <summary> /// Gets or sets the namespace. /// </summary> /// <value></value> string Namespace { get; set; } /// <summary> /// Gets or sets the file extension. /// </summary> /// <value></value> string FileExtension { get; set; } /// <summary> /// Gets or sets the output directory. /// </summary> /// <value></value> string OutputDirectory { get; set; } /// <summary> /// Gets or sets a value indicating whether the generated file can be overwritten /// </summary> /// <value> /// <c>true</c> if overwrite; otherwise, <c>false</c>. /// </value> bool Overwrite { get; set; } /// <summary> /// Processes the custom code. /// </summary> void ProcessCustomCode(); } } --- NEW FILE: AbstractCodeTemplate.cs --- namespace Adapdev.CodeGen { using System; /// <summary> /// Summary description for AbstractTemplate. /// </summary> public abstract class AbstractCodeTemplate : ICodeTemplate { protected string fileName = String.Empty; protected string className = String.Empty; protected string fileExtension = String.Empty; protected string outputDir = String.Empty; protected string nameSpace = String.Empty; protected bool overwrite = true; /// <summary> /// Creates a new <see cref="AbstractCodeTemplate"/> instance. /// </summary> /// <param name="fileName">Name of the file.</param> /// <param name="fileExtension">File extension.</param> /// <param name="className">Name of the class.</param> /// <param name="nameSpace">Namespace.</param> public AbstractCodeTemplate(string fileName, string fileExtension, string className, string nameSpace) { this.fileName = fileName; this.fileExtension = fileExtension; this.className = className; this.nameSpace = nameSpace; } /// <summary> /// Gets or sets the name of the file. /// </summary> /// <value></value> public string FileName { get { return this.fileName; } set { this.fileName = value; } } /// <summary> /// Gets or sets the file extension. /// </summary> /// <value></value> public string FileExtension { get { return this.fileExtension; } set { this.fileExtension = value; } } /// <summary> /// Gets or sets the name of the class. /// </summary> /// <value></value> public string ClassName { get { return this.className; } set { this.className = value; } } /// <summary> /// Gets or sets the output directory. /// </summary> /// <value></value> public virtual string OutputDirectory { get { return this.outputDir; } set { this.outputDir = value; } } /// <summary> /// Gets or sets the namespace. /// </summary> /// <value></value> public virtual string Namespace { get { return this.nameSpace; } set { this.nameSpace = value; } } /// <summary> /// Gets or sets a value indicating whether the generated file can be overwritten /// </summary> /// <value> /// <c>true</c> if it can be overwritten; otherwise, <c>false</c>. /// </value> public virtual bool Overwrite { get { return this.overwrite; } set { this.overwrite = value; } } /// <summary> /// Processes the custom code. /// </summary> public virtual void ProcessCustomCode() { } /// <summary> /// Gets the code. /// </summary> /// <returns></returns> public abstract string GetCode(); } } --- NEW FILE: CodeGenerator.cs --- namespace Adapdev.CodeGen { using System; using System.CodeDom; using System.CodeDom.Compiler; using System.Collections; using System.IO; public delegate void ICodeTemplateProcessedEventHandler(object sender, ICodeTemplateEventArgs e); public delegate void ICodeDomTemplateProcessedEventHandler(object sender, ICodeDomTemplateEventArgs e); /// <summary> /// Summary description for CodeGenerator. /// </summary> public class CodeGenerator { public event ICodeTemplateProcessedEventHandler ICodeTemplateProcessed; public event ICodeDomTemplateProcessedEventHandler ICodeDomTemplateProcessed; protected string outputDir = String.Empty; /// <summary> /// Creates a new <see cref="CodeGenerator"/> instance. /// </summary> /// <param name="outputDir">Output dir.</param> public CodeGenerator(string outputDir) { this.outputDir = outputDir; } /// <summary> /// Gets or sets the output dir. /// </summary> /// <value></value> public string OutputDir { get { return this.outputDir; } set { this.outputDir = value; } } /// <summary> /// Processes the <see cref="ICodeDomTemplate"/> to file. /// </summary> /// <param name="template">Template.</param> /// <param name="codeType">Code type.</param> /// <param name="refAssemblies">Reference assemblies.</param> public void ProcessICodeDomTemplateToFile(ICodeDomTemplate template, LanguageType codeType, params string[] refAssemblies) { string location = Path.Combine(this.outputDir, template.OutputDirectory); location = Path.Combine(location, codeType.ToString()); CodeCompileUnit ccu = template.GetCodeCompileUnit(); foreach(string s in refAssemblies) { ccu.ReferencedAssemblies.Add(s); } if (ccu != null) { // Obtains an ICodeGenerator from a CodeDomProvider class. CodeDomProvider provider = CodeProviderFactory.GetCodeProvider(codeType); ICodeGenerator gen = provider.CreateGenerator(); // If the directory doesn't exist, create it if (!Directory.Exists(location)) { Directory.CreateDirectory(location); } // Build path and filename string filePath = Path.Combine(location, template.FileName + "." + provider.FileExtension); if (File.Exists(filePath) && template.Overwrite) // If the filepath exists and it can be overwritten { // Creates a StreamWriter to an output file. StreamWriter sw = new StreamWriter(filePath, false); // Generates source code using the code generator. gen.GenerateCodeFromCompileUnit(ccu, sw, new CodeGeneratorOptions()); // Closes the output files. sw.Close(); } else if (!File.Exists(filePath)) // If the file path doesn't exist { // Creates a StreamWriter to an output file. StreamWriter sw = new StreamWriter(filePath, false); // Generates source code using the code generator. gen.GenerateCodeFromCompileUnit(ccu, sw, new CodeGeneratorOptions()); // Closes the output files. sw.Close(); } // Process any custom code template.ProcessCustomCode(); } this.OnICodeDomTemplateProcessed(new ICodeDomTemplateEventArgs(template)); } /// <summary> /// Processes the <see cref="ICodeTemplate"/> to a file. /// </summary> /// <param name="template">Template.</param> public void ProcessICodeTemplateToFile(ICodeTemplate template) { // Get the code string code = template.GetCode(); // Make sure it's not null or empty if (template != null && !code.Equals(String.Empty)) { // Build the output path, and create it if it doesn't exist string output = Path.Combine(this.outputDir, template.OutputDirectory); if (!Directory.Exists(output)) { Directory.CreateDirectory(output); } // Build the file path string filePath = Path.Combine(output, template.FileName + "." + template.FileExtension); if (File.Exists(filePath) && template.Overwrite) // If it exists and can be overwritten { // Creates a StreamWriter to an output file. StreamWriter sw = new StreamWriter(filePath, false); // Generates source code using the code generator. sw.Write(code); // Closes the output files. sw.Close(); } else if (!File.Exists(filePath)) // The file doesn't exist { // Creates a StreamWriter to an output file. StreamWriter sw = new StreamWriter(filePath, false); // Generates source code using the code generator. sw.Write(code); // Closes the output files. sw.Close(); } template.ProcessCustomCode(); } this.OnICodeTemplateProcessed(new ICodeTemplateEventArgs(template)); } /// <summary> /// Processes the <see cref="ICodeDomTemplate"/>s to files. /// </summary> /// <param name="templates">Templates.</param> /// <param name="codeType">Code type.</param> public void ProcessICodeDomTemplatesToFiles(ICollection templates, LanguageType codeType) { foreach (ICodeDomTemplate template in templates) { try { this.ProcessICodeDomTemplateToFile(template, codeType); } catch(Exception ex) { throw ex; } } } /// <summary> /// Processes the <see cref="ICodeTemplate"/>s to files. /// </summary> /// <param name="templates">Templates.</param> public void ProcessICodeDomTemplatesToFiles(ICollection templates) { foreach (ICodeDomTemplate template in templates) { this.ProcessICodeDomTemplateToFile(template, LanguageType.CPP); this.ProcessICodeDomTemplateToFile(template, LanguageType.CSHARP); this.ProcessICodeDomTemplateToFile(template, LanguageType.JSCRIPT); this.ProcessICodeDomTemplateToFile(template, LanguageType.JSHARP); this.ProcessICodeDomTemplateToFile(template, LanguageType.VBNET); } } public void ProcessICodeTemplatesToFiles(ICollection templates) { foreach (ICodeTemplate template in templates) { this.ProcessICodeTemplateToFile(template); } } /// <summary> /// Processes the templates to an assembly. /// </summary> /// <param name="templates">Templates.</param> /// <param name="codeType">Code type.</param> /// <param name="assembly">Assembly.</param> /// <param name="cparams">Cparams.</param> public void ProcessTemplatesToAssembly(ICollection templates, LanguageType codeType, string assembly, CompilerParameters cparams) { // Create compiler for the specified CodeDom CodeDomProvider provider = CodeProviderFactory.GetCodeProvider(codeType); ICodeCompiler gen = provider.CreateCompiler(); ArrayList files = new ArrayList(); // Generate the code foreach (ICodeDomTemplate template in templates) { this.ProcessICodeDomTemplateToFile(template, codeType); files.Add(template.FileName + "." + provider.FileExtension); } // Compile the code gen.CompileAssemblyFromFileBatch(cparams, (string[]) files.ToArray(typeof (string))); } /// <summary> /// Fires when the <see cref="ICodeTemplate"/> is processed /// </summary> /// <param name="e">E.</param> public void OnICodeTemplateProcessed(ICodeTemplateEventArgs e) { if (ICodeTemplateProcessed != null) { //Invokes the delegates. ICodeTemplateProcessed(this, e); } } /// <summary> /// Fires when the <see cref="ICodeDomTemplate"/> is processed /// </summary> /// <param name="e">E.</param> public void OnICodeDomTemplateProcessed(ICodeDomTemplateEventArgs e) { if (ICodeDomTemplateProcessed != null) { //Invokes the delegates. ICodeDomTemplateProcessed(this, e); } } // public void ProcessTemplateAssemblyToFiles(Assembly a, LanguageType codeType){} // public void ProcessTemplateAssemblyToAssembly(string assemblyToRead, string assemblyToWrite, LanguageType codeType, CompilerParameters cparams){} // // public void ProcessCodeCompileUnitToFile(CodeCompileUnit ccu, string fileName, LanguageType codeType){} // public void ProcessCodeCompileUnitsToFiles(ICollection ccus, string[] fileNames, LanguageType codeType){} // public void ProcessCodeCompileUnitsToAssembly(ICollection ccus, LanguageType codeType, string assembly, CompilerParameters cparams){} // public void ProcessCodeCompileUnitAssemblyToFiles(Assembly a, LanguageType codeType){} // public void ProcessCodeCompileUnitAssemblyToAssembly(string assemblyToRead, string assemblyToWrite, LanguageType codeType, CompilerParameters cparams){} } } --- NEW FILE: ICodeDomTemplateEventArgs.cs --- namespace Adapdev.CodeGen { using System; /// <summary> /// Summary description for ICodeDomTemplateEventArgs. /// </summary> public class ICodeDomTemplateEventArgs : EventArgs { private ICodeDomTemplate _template = null; /// <summary> /// Creates a new <see cref="ICodeDomTemplateEventArgs"/> instance. /// </summary> /// <param name="template">Template.</param> public ICodeDomTemplateEventArgs(ICodeDomTemplate template) { this._template = template; } /// <summary> /// Gets the <see cref="ICodeDomTemplate"/> /// </summary> /// <value></value> public ICodeDomTemplate ICodeDomTemplate { get { return this._template; } } } } --- NEW FILE: ICodeDomTemplate.cs --- namespace Adapdev.CodeGen { using System.CodeDom; /// <summary> /// Summary description for ICodeDomTemplate. /// </summary> public interface ICodeDomTemplate { /// <summary> /// Gets the code compile unit. /// </summary> /// <returns></returns> CodeCompileUnit GetCodeCompileUnit(); /// <summary> /// Gets or sets the name of the file. /// </summary> /// <value></value> string FileName { get; set; } /// <summary> /// Gets or sets the name of the class. /// </summary> /// <value></value> string ClassName { get; set; } /// <summary> /// Gets or sets the namespace. /// </summary> /// <value></value> string Namespace { get; set; } /// <summary> /// Gets or sets the output directory. /// </summary> /// <value></value> string OutputDirectory { get; set; } /// <summary> /// Gets or sets a value indicating whether the generated file can be overwritten /// </summary> /// <value> /// <c>true</c> if overwrite; otherwise, <c>false</c>. /// </value> bool Overwrite { get; set; } /// <summary> /// Processes the custom code. /// </summary> void ProcessCustomCode(); } } --- NEW FILE: NVelocityCodeTemplate.cs --- namespace Adapdev.CodeGen { using System; using System.IO; using NVelocity; using NVelocity.App; /// <summary> /// Summary description for NVelocityCodeTemplate. /// </summary> public class NVelocityCodeTemplate : AbstractCodeTemplate, INVelocityTemplate { protected string templateFile = String.Empty; protected VelocityContext context = null; /// <summary> /// Creates a new <see cref="NVelocityCodeTemplate"/> instance. /// </summary> /// <param name="fileName">Name of the file.</param> /// <param name="fileExtension">File extension.</param> /// <param name="overWrite">Over write.</param> /// <param name="templateFile">Template file.</param> /// <param name="outputDirectory">Output directory.</param> /// <param name="className">Name of the class.</param> /// <param name="nameSpace">Namespace.</param> public NVelocityCodeTemplate(string fileName, string fileExtension, bool overWrite, string templateFile, string outputDirectory, string className, string nameSpace) : base(fileName, fileExtension, className, nameSpace) { this.templateFile = templateFile; this.outputDir = outputDirectory; this.overwrite = overWrite; if (!File.Exists("nvelocity.properties")) File.Copy(Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "nvelocity.properties"), Path.Combine(".", "nvelocity.properties"), true); if (!File.Exists("directive.properties")) File.Copy(Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "directive.properties"), Path.Combine(".", "directive.properties"), true); Velocity.Init("nvelocity.properties"); context = new VelocityContext(); } /// <summary> /// Creates a new <see cref="NVelocityCodeTemplate"/> instance. /// </summary> /// <param name="fileName">Name of the file.</param> /// <param name="fileExtension">File extension.</param> /// <param name="templateFile">Template file.</param> /// <param name="outputDirectory">Output directory.</param> public NVelocityCodeTemplate(string fileName, string fileExtension, string templateFile, string outputDirectory) : this(fileName, fileExtension, true, templateFile, outputDirectory, String.Empty, String.Empty) { } /// <summary> /// Gets the code. /// </summary> /// <returns></returns> public override string GetCode() { if(!context.ContainsKey("namespace")) context.Put("namespace", this.nameSpace); if(!context.ContainsKey("classname")) context.Put("classname", this.className); if(!context.ContainsKey("filename")) context.Put("filename", this.fileName); context.Put("datetimenow", DateTime.Now); context.Put("template", this); StringWriter writer = new StringWriter(); Velocity.MergeTemplate(this.templateFile, context, writer); return writer.GetStringBuilder().ToString(); } /// <summary> /// Gets or sets the template file. /// </summary> /// <value></value> public string TemplateFile { get { return this.templateFile; } set { this.templateFile = value; } } public override bool Overwrite { get { return this.overwrite; } set { base.Overwrite = value; } } /// <summary> /// Gets the context. /// </summary> /// <value></value> public VelocityContext Context { get { return this.context; } } public string GetConversionExpression(string objectType) { string subt = objectType.Substring(objectType.IndexOf(".") + 1); return "Convert.To"+subt; } } } --- NEW FILE: ICodeTemplateEventArgs.cs --- namespace Adapdev.CodeGen { using System; /// <summary> /// Summary description for ICodeTemplateEventArgs. /// </summary> public class ICodeTemplateEventArgs : EventArgs { private ICodeTemplate _template = null; /// <summary> /// Creates a new <see cref="ICodeTemplateEventArgs"/> instance. /// </summary> /// <param name="template">Template.</param> public ICodeTemplateEventArgs(ICodeTemplate template) { this._template = template; } /// <summary> /// Gets the I code template. /// </summary> /// <value></value> public ICodeTemplate ICodeTemplate { get { return this._template; } } } } --- NEW FILE: LanguageType.cs --- namespace Adapdev.CodeGen { using System; /// <summary> /// Summary description for LanguageType. /// </summary> /// [Flags] public enum LanguageType { CSHARP = 1, JSHARP = 2, JSCRIPT = 4, VBNET = 8, CPP = 16, SQL = 32, OTHER = 64, JAVA = 128 } } --- NEW FILE: TableCodeDomTemplate.cs --- namespace Adapdev.CodeGen { using Adapdev.Data.Schema; public abstract class TableCodeDomTemplate : AbstractCodeDomTemplate { protected TableSchema ti; /// <summary> /// Creates a new <see cref="TableCodeDomTemplate"/> instance. /// </summary> /// <param name="ti">TableSchema.</param> /// <param name="nameSpace">Namespace.</param> /// <param name="fileName">Name of the file.</param> /// <param name="className">Name of the class.</param> public TableCodeDomTemplate(TableSchema ti, string nameSpace, string fileName, string className) : base(fileName, className, nameSpace) { this.ti = ti; } } } --- NEW FILE: Adapdev.CodeGen.csproj --- <VisualStudioProject> <CSHARP ProjectType = "Local" ProductVersion = "7.10.3077" SchemaVersion = "2.0" ProjectGuid = "{2D8FC662-0244-49F1-8017-DFE73B191017}" > <Build> <Settings ApplicationIcon = "" AssemblyKeyContainerName = "" AssemblyName = "Adapdev.CodeGen" AssemblyOriginatorKeyFile = "" DefaultClientScript = "JScript" DefaultHTMLPageLayout = "Grid" DefaultTargetSchema = "IE50" DelaySign = "false" OutputType = "Library" PreBuildEvent = "" PostBuildEvent = "" RootNamespace = "Adapdev.CodeGen" RunPostBuildEvent = "OnBuildSuccess" StartupObject = "" > <Config Name = "Debug" AllowUnsafeBlocks = "false" BaseAddress = "285212672" CheckForOverflowUnderflow = "false" ConfigurationOverrideFile = "" DefineConstants = "DEBUG;TRACE" DocumentationFile = "" DebugSymbols = "true" FileAlignment = "4096" IncrementalBuild = "false" NoStdLib = "false" NoWarn = "" Optimize = "false" OutputPath = "bin\Debug\" RegisterForComInterop = "false" RemoveIntegerChecks = "false" TreatWarningsAsErrors = "false" WarningLevel = "4" /> <Config Name = "Release" AllowUnsafeBlocks = "false" BaseAddress = "285212672" CheckForOverflowUnderflow = "false" ConfigurationOverrideFile = "" DefineConstants = "TRACE" DocumentationFile = "" DebugSymbols = "false" FileAlignment = "4096" IncrementalBuild = "false" NoStdLib = "false" NoWarn = "" Optimize = "true" OutputPath = "bin\Release\" RegisterForComInterop = "false" RemoveIntegerChecks = "false" TreatWarningsAsErrors = "false" WarningLevel = "4" /> </Settings> <References> <Reference Name = "System" AssemblyName = "System" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.dll" /> <Reference Name = "System.Data" AssemblyName = "System.Data" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.Data.dll" /> <Reference Name = "System.XML" AssemblyName = "System.Xml" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.XML.dll" /> <Reference Name = "Adapdev" Project = "{CC30A321-2569-4B1F-8E1A-781B5509B56D}" Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" /> <Reference Name = "Adapdev.Data" Project = "{08C5794D-44ED-4E75-A1C1-48A28C3D0044}" Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" /> <Reference Name = "Adapdev.NVelocity" Project = "{75D57D5C-250A-447C-80BC-2FF9DC8A14D2}" Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" /> <Reference Name = "MCppCodeDomProvider" AssemblyName = "MCppCodeDomProvider" HintPath = "C:\Program Files\Microsoft Visual Studio .NET 2003\Common7\IDE\PublicAssemblies\MCppCodeDomProvider.dll" AssemblyFolderKey = "hklm\publicassemblies" /> <Reference Name = "Microsoft.JScript" AssemblyName = "Microsoft.JScript" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\Microsoft.JScript.dll" /> <Reference Name = "Microsoft.VisualBasic" AssemblyName = "Microsoft.VisualBasic" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\Microsoft.VisualBasic.dll" /> <Reference Name = "VJSharpCodeProvider" AssemblyName = "VJSharpCodeProvider" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\VJSharpCodeProvider.DLL" /> <Reference Name = "log4net" AssemblyName = "log4net" HintPath = "..\..\lib\log4net.dll" /> </References> </Build> <Files> <Include> <File RelPath = "AbstractCodeDomTemplate.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "AbstractCodeTemplate.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "AbstractConfig.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "AbstractSchemaConfig.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "AdapdevAssemblyInfo.cs" Link = "..\AdapdevAssemblyInfo.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "CodeGenerator.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "CodeType.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "CompilerFactory.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "DataSetHelper.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "ICodeDomTemplate.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "ICodeDomTemplateEventArgs.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "ICodeTemplate.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "ICodeTemplateEventArgs.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "INVelocityTemplate.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "LanguageType.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "NVelocityCodeTemplate.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "NVelocityTableCodeTemplate.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "TableCodeDomTemplate.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "TableCodeTemplate.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "UnitTestType.cs" SubType = "Code" BuildAction = "Compile" /> </Include> </Files> </CSHARP> </VisualStudioProject> --- NEW FILE: CodeType.cs --- using System; namespace Adapdev.Data.CodeGen { /// <summary> /// Summary description for CodeType. /// </summary> /// [FlagsAttribute] public enum CodeType { CSHARP, JSHARP, JSCRIPT, VBNET, CPP } } --- NEW FILE: AbstractConfig.cs --- namespace Adapdev.CodeGen { using System; using System.Collections; using System.IO; public delegate void ProcessCustomCodeHandler(string info); /// <summary> /// Summary description for AbstractConfig. /// </summary> public abstract class AbstractConfig { protected Hashtable properties = null; protected string nameSpace = String.Empty; protected ArrayList languages = new ArrayList(); protected string appdir = AppDomain.CurrentDomain.SetupInformation.ApplicationBase; protected string shareddir = String.Empty; protected string outputdir = String.Empty; /// <summary> /// Creates a new <see cref="AbstractConfig"/> instance. /// </summary> /// <param name="nameSpace">Namespace.</param> public AbstractConfig(string nameSpace) { this.nameSpace = nameSpace; shareddir = Path.Combine(this.appdir, "shared"); } /// <summary> /// Gets the base output directory for this template library /// </summary> /// <value></value> public virtual string PackageDirectory { get { return this.PackageName; } } /// <summary> /// Gets or sets the output directory. /// </summary> /// <value></value> public virtual string OutputDirectory { get { return this.outputdir; } set { this.outputdir = value; } } /// <summary> /// Gets the application directory. /// </summary> /// <value></value> public string ApplicationDirectory { get { return this.appdir; } } /// <summary> /// Gets or sets the shared directory. /// </summary> /// <value></value> public string SharedDirectory { get { return this.shareddir; } set { this.shareddir = value; } } /// <summary> /// Gets or sets the base namespace for this template library /// </summary> /// <value></value> public string NameSpace { get { return this.nameSpace; } set { this.nameSpace = value; } } /// <summary> /// Gets or sets the custom properties. /// </summary> /// <value></value> public virtual Hashtable CustomProperties { get { return this.properties; } set { this.properties = value; } } /// <summary> /// Processes the custom code. /// </summary> public virtual void ProcessCustomCode() { } public event ProcessCustomCodeHandler Processing; public void OnProcessing(string info) { if(Processing != null) { Processing(info); } } /// <summary> /// Gets the code DOM templates. /// </summary> /// <returns>A list of ICodeDomTemplates to process</returns> public abstract ArrayList GetCodeDomTemplates(); /// <summary> /// Gets the code templates. /// </summary> /// <returns>A list of ICodeTemplates to process</returns> public abstract ArrayList GetCodeTemplates(); // The name of the package. /// <summary> /// Gets the name of the package. /// </summary> /// <value></value> public abstract string PackageName { get; } /// <summary> /// Gets the package description. /// </summary> /// <value></value> public abstract string PackageDescription { get; } /// <summary> /// Gets the author. /// </summary> /// <value></value> public abstract string Author { get; } /// <summary> /// Gets the version. /// </summary> /// <value></value> public abstract string Version { get; } /// <summary> /// Gets the copyright. /// </summary> /// <value></value> public abstract string Copyright { get; } } } --- NEW FILE: AbstractSchemaConfig.cs --- namespace Adapdev.CodeGen { using System; using Adapdev.Data.Schema; /// <summary> /// Summary description for AbstractConfig. /// </summary> public abstract class AbstractSchemaConfig : AbstractConfig { protected string connectionString = String.Empty; protected DatabaseSchema databaseSchema = new DatabaseSchema(); /// <summary> /// Creates a new <see cref="AbstractSchemaConfig"/> instance. /// </summary> /// <param name="connectionString">Connection string.</param> /// <param name="nameSpace">Namespace.</param> /// <param name="databaseSchema">Database schema.</param> public AbstractSchemaConfig(string connectionString, string nameSpace, DatabaseSchema databaseSchema) : base(nameSpace) { this.connectionString = connectionString; this.databaseSchema = databaseSchema; } /// <summary> /// Gets or sets the connection string. /// </summary> /// <value></value> public string ConnectionString { get { return this.connectionString; } set { this.connectionString = value; } } /// <summary> /// Gets or sets the <see cref="DatabaseSchema"/> /// </summary> /// <value></value> public DatabaseSchema DatabaseSchema { get { return this.databaseSchema; } set { this.databaseSchema = value; } } } } --- NEW FILE: NVelocityTableCodeTemplate.cs --- namespace Adapdev.CodeGen { using System; using System.Collections; using System.IO; using System.Text; using Adapdev.Data; using Adapdev.Data.Schema; using Adapdev.Data.Sql; using NVelocity; using NVelocity.App; /// <summary> /// Summary description for NVelocityTableCodeTemplate. /// </summary> public class NVelocityTableCodeTemplate : TableCodeTemplate, INVelocityTemplate { protected DatabaseSchema di = null; protected string templateFile = String.Empty; protected VelocityContext context = null; /// <summary> /// Creates a new <see cref="NVelocityTableCodeTemplate"/> instance. /// </summary> /// <param name="di">Database Schema.</param> /// <param name="ti">Table Schema.</param> /// <param name="outputDirectory">Output directory.</param> /// <param name="templateFile">Template file.</param> /// <param name="nameSpace">Namespace.</param> /// <param name="fileName">Name of the file.</param> /// <param name="fileExtension">File extension.</param> /// <param name="className">Name of the class.</param> /// <param name="overWrite">Over write.</param> public NVelocityTableCodeTemplate(DatabaseSchema di, TableSchema ti, string outputDirectory, string templateFile, string nameSpace, string fileName, string fileExtension, string className, bool overWrite) : base(ti, nameSpace, fileName, fileExtension, className) { this.di = di; this.templateFile = templateFile; this.outputDir = outputDirectory; this.overwrite = overWrite; if (!File.Exists("nvelocity.properties")) File.Copy(Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "nvelocity.properties"), Path.Combine(".", "nvelocity.properties"), true); if (!File.Exists("directive.properties")) File.Copy(Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "directive.properties"), Path.Combine(".", "directive.properties"), true); Velocity.Init("nvelocity.properties"); context = new VelocityContext(); } /// <summary> /// Creates a new <see cref="NVelocityTableCodeTemplate"/> instance. /// </summary> /// <param name="di">Database Schema.</param> /// <param name="ti">Table Schema.</param> /// <param name="outputDirectory">Output directory.</param> /// <param name="templateFile">Template file.</param> /// <param name="fileName">Name of the file.</param> /// <param name="fileExtension">File extension.</param> public NVelocityTableCodeTemplate(DatabaseSchema di, TableSchema ti, string outputDirectory, string templateFile, string fileName, string fileExtension) : this(di, ti, outputDirectory, templateFile, String.Empty, fileName, fileExtension, String.Empty, true) { } /// <summary> /// Gets the code. /// </summary> /// <returns></returns> public override string GetCode() { context.Put("databaseschema", this.di); context.Put("tableschema", this.ti); if(!context.ContainsKey("namespace")) context.Put("namespace", this.nameSpace); if(!context.ContainsKey("classname")) context.Put("classname", this.className); if(!context.ContainsKey("filename")) context.Put("filename", this.fileName); context.Put("datetimenow", DateTime.Now); context.Put("datahelper", new DataHelper(di)); context.Put("providerinfo", ProviderInfoManager.GetInstance()); context.Put("template", this); context.Put("queryhelper", new QueryHelper()); context.Put("mysqlprovidertype", Adapdev.Data.DbProviderType.MYSQL); StringWriter writer = new StringWriter(); Velocity.MergeTemplate(this.templateFile, context, writer); return writer.GetStringBuilder().ToString(); } /// <summary> /// Gets the Sql to select one record by the primary key /// </summary> /// <returns></returns> public string GetSelectOneSql() { return this.GetSelectOneSql(this.ti); } /// <summary> /// Gets the Sql to select one record by the primary key /// </summary> /// <param name="ts">Ts.</param> /// <returns></returns> public string GetSelectOneSql(TableSchema ts) { if(ts.HasPrimaryKeys) { ISelectQuery query = QueryFactory.CreateSelectQuery(di.DatabaseType, di.DatabaseProviderType); query.SetTable(ts.Name); foreach (ColumnSchema ci in ts.OrdinalColumns.Values) { if(ci.IsActive)query.Add(ci.Name); } ArrayList pks = new ArrayList(ts.PrimaryKeys.Values); ColumnSchema pk = (ColumnSchema) pks[0]; ICriteria criteria = query.CreateCriteria(); criteria.DbProviderType = this.di.DatabaseProviderType; criteria.AddEqualTo(pk.Name); query.SetCriteria(criteria); return query.GetText(); } return ""; } /// <summary> /// Gets the insert SQL. /// </summary> /// <returns></returns> public string GetInsertSql() { return this.GetInsertSql(this.ti); } /// <summary> /// Gets the insert SQL. /// </summary> /// <param name="ts">Ts.</param> /// <returns></returns> public string GetInsertSql(TableSchema ts) { IInsertQuery query = QueryFactory.CreateInsertQuery(di.DatabaseType, di.DatabaseProviderType); query.SetTable(ts.Name); foreach (ColumnSchema ci in ts.SortedColumns.Values) { if (!ci.IsAutoIncrement && ci.IsActive) query.Add(ci.Name); } return query.GetText(); } /// <summary> /// Gets the update SQL. /// </summary> /// <returns></returns> public string GetUpdateSql() { return this.GetUpdateSql(this.ti); } /// <summary> /// Gets the update SQL. /// </summary> /// <returns></returns> public string GetUpdateSql(TableSchema ts) { IUpdateQuery query = QueryFactory.CreateUpdateQuery(di.DatabaseType, di.DatabaseProviderType); query.SetTable(ts.Name); foreach (ColumnSchema ci in ts.SortedColumns.Values) { if (!ci.IsAutoIncrement && ci.IsActive) query.Add(ci.Name); } ArrayList pks = new ArrayList(ts.PrimaryKeys.Values); ICriteria criteria = query.CreateCriteria(); criteria.DbProviderType = this.di.DatabaseProviderType; int i = 1; foreach(ColumnSchema pk in pks) { criteria.AddEqualTo(pk.Name); if(i < pks.Count) criteria.AddAnd(); i++; } query.SetCriteria(criteria); return query.GetText(); } /// <summary> /// Gets the delete one SQL. /// </summary> /// <returns></returns> public string GetDeleteOneSql() { return this.GetDeleteOneSql(this.ti); } /// <summary> /// Gets the sql to delete one record by primary key /// </summary> /// <returns></returns> public string GetDeleteOneSql(TableSchema ts) { if(ts.HasPrimaryKeys) { IDeleteQuery query = QueryFactory.CreateDeleteQuery(di.DatabaseType, di.DatabaseProviderType); query.SetTable(ts.Name); ArrayList pks = new ArrayList(ts.PrimaryKeys.Values); ColumnSchema pk = (ColumnSchema) pks[0]; ICriteria criteria = query.CreateCriteria(); criteria.DbProviderType = this.di.DatabaseProviderType; criteria.AddEqualTo(pk.Name); query.SetCriteria(criteria); return query.GetText(); } return ""; } /// <summary> /// Gets the foreign key SQL. /// </summary> /// <param name="ci">Ci.</param> /// <returns></returns> public string GetForeignKeySql(ColumnSchema ci) { return this.GetForeignKeySql(this.ti, ci); } /// <summary> /// Gets the foreign key SQL. /// </summary> /// <param name="ts">Ts.</param> /// <param name="columnSchema">Column schema.</param> /// <returns></returns> public string GetForeignKeySql(TableSchema ts, ColumnSchema columnSchema) { ISelectQuery query = QueryFactory.CreateSelectQuery(di.DatabaseType); query.SetTable(ts.Name); foreach (ColumnSchema ci2 in ts.OrdinalColumns.Values) { if(ci2.IsActive)query.Add(ci2.Name); } ICriteria criteria = query.CreateCriteria(); criteria.DbProviderType = this.di.DatabaseProviderType; criteria.AddEqualTo(columnSchema.Name); query.SetCriteria(criteria); return query.GetText(); } /// <summary> /// Gets the name of the parameter. /// </summary> /// <param name="name">Name.</param> /// <returns></returns> public string GetParameterName(string name) { return QueryHelper.GetParameterName(name, this.di.DatabaseProviderType); } /// <summary> /// Gets the parameter value. /// </summary> /// <param name="c">C.</param> /// <returns></returns> public string GetParameterValue(DatabaseSchema d, ColumnSchema c) { if (c.NetType.Equals("System.DateTime")) { if(d.DatabaseType == Adapdev.Data.DbType.SQLSERVER) return c.Alias + ".Subtract(new TimeSpan(2,0,0,0)).ToOADate()"; else if(d.DatabaseType == Adapdev.Data.DbType.ORACLE) return c.Alias; else if (d.DatabaseType == Adapdev.Data.DbType.MYSQL) return c.Alias; else return c.Alias + ".ToOADate()"; } else return c.Alias; } public string GetParameterLength(ColumnSchema c) { switch(c.DataType.ToLower()) { case "binary": case "char": case "nchar": case "nvarchar": case "varbinary": case "varchar": return "(" + c.Length + ")"; } return String.Empty; } public string GetParameterText(ColumnSchema cs) { return this.GetParameterName(cs.Name) + " " + cs.DataType.ToLower() + this.GetParameterLength(cs); } /// <summary> /// Gets or sets the template file. /// </summary> /// <value></value> public string TemplateFile { get { return this.templateFile; } set { this.templateFile = value; } } public override bool Overwrite { get { return this.overwrite; } set { base.Overwrite = value; } } /// <summary> /// Gets the context. /// </summary> /// <value></value> public VelocityContext Context { get { return this.context; } } public string GetConversionExpression(string objectType) { string subt = objectType.Substring(objectType.IndexOf(".") + 1); return "Convert.To"+subt; } public string GetSqlServerSPInsertParams(TableSchema ts) { StringBuilder sb = new StringBuilder(); ArrayList al = new ArrayList(); // Get all columns that aren't autoincrement foreach(ColumnSchema cs in ts.SortedColumns.Values) { if(!cs.IsAutoIncrement && cs.IsActive)al.Add(cs); } // Build the list of parameters int i = 1; foreach(ColumnSchema cs in al) { if(cs.IsActive) { if(i < al.Count) { sb.Append(this.GetParameterText(cs) + "," + Environment.NewLine); } else { sb.Append(this.GetParameterText(cs) + Environment.NewLine); } i++; } } return sb.ToString(); } public string GetSqlServerSPUpdateParams(TableSchema ts) { int i = 1; StringBuilder sb = new StringBuilder(); foreach (ColumnSchema columnSchema in ts.SortedColumns.Values) { if(columnSchema.IsActive) { if(i < ts.SortedColumns.Count) { sb.Append(this.GetParameterText(columnSchema) + "," + Environment.NewLine); } else { sb.Append(this.GetParameterText(columnSchema) + Environment.NewLine); } } i++; } return sb.ToString(); } } } --- NEW FILE: CompilerFactory.cs --- namespace Adapdev.CodeGen { using System.CodeDom.Compiler; using Microsoft.CSharp; using Microsoft.JScript; using Microsoft.MCpp; using Microsoft.VisualBasic; using Microsoft.VJSharp; /// <summary> /// Summary description for CompilerFactory. /// </summary> public class CodeProviderFactory { /// <summary> /// Gets the code provider. /// </summary> /// <param name="codeType">Code type.</param> /// <returns></returns> public static CodeDomProvider GetCodeProvider(LanguageType codeType) { switch (codeType) { case LanguageType.CPP: return new MCppCodeProvider(); case LanguageType.CSHARP: return new CSharpCodeProvider(); case LanguageType.JSCRIPT: return new JScriptCodeProvider(); case LanguageType.JSHARP: return new VJSharpCodeProvider(); case LanguageType.VBNET: return new VBCodeProvider(); default: return new CSharpCodeProvider(); } } } } --- NEW FILE: UnitTestType.cs --- using System; namespace Adapdev.Data.CodeGen { /// <summary> /// Summary description for UnitTestType. /// </summary> public enum UnitTestType { CSUNIT, NUNIT, ZANEBUG, MBUNIT } } --- NEW FILE: TableCodeTemplate.cs --- namespace Adapdev.CodeGen { using System; using Adapdev.Data.Schema; public abstract class TableCodeTemplate : AbstractCodeTemplate { protected TableSchema ti; /// <summary> /// Creates a new <see cref="TableCodeTemplate"/> instance. /// </summary> /// <param name="ti">TableSchema.</param> /// <param name="nameSpace">Namespace.</param> /// <param name="fileName">Name of the file.</param> /// <param name="fileExtension">File extension.</param> /// <param name="className">Name of the class.</param> public TableCodeTemplate(TableSchema ti, string nameSpace, string fileName, string fileExtension, string className) : base(fileName, fileExtension, className, nameSpace) { this.ti = ti; } /// <summary> /// Creates a new <see cref="TableCodeTemplate"/> instance. /// </summary> /// <param name="ti">TableSchema.</param> /// <param name="fileName">Name of the file.</param> /// <param name="fileExtension">File extension.</param> public TableCodeTemplate(TableSchema ti, string fileName, string fileExtension) : base(fileName, fileExtension, String.Empty, String.Empty) { this.ti = ti; } } } |
From: Sean M. <int...@us...> - 2005-11-16 05:33:39
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev/Diagnostics In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv19977/src/Adapdev/Diagnostics Added Files: CPUMeter.cs HiPerfTimer.cs IPerfTimer.cs MillisecondsPerfTimer.cs MinutesPerfTimer.cs PerfTimerFactory.cs SecondsPerfTimer.cs TicksPerfTimer.cs Log Message: Reposting to the repository after it got hosed --- NEW FILE: SecondsPerfTimer.cs --- #region Copyright / License Information /* Copyright 2004 - 2005 Adapdev Technologies, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ============================ Author Log ============================ III Full Name SMM Sean McCormack (Adapdev) ============================ Change Log ============================ III MMDDYY Change */ #endregion namespace Adapdev.Diagnostics { using System; /// <summary> /// Summary description for DateTimePerfTimer. /// </summary> public class SecondsPerfTimer : IPerfTimer { private DateTime start; private TimeSpan stop; public SecondsPerfTimer() { } #region IPerfTimer Members public void Start() { start = DateTime.Now; } public void Stop() { stop = DateTime.Now.Subtract(start); } public double Duration { get { return stop.TotalSeconds; } } #endregion } } --- NEW FILE: IPerfTimer.cs --- #region Copyright / License Information /* Copyright 2004 - 2005 Adapdev Technologies, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ============================ Author Log ============================ III Full Name SMM Sean McCormack (Adapdev) ============================ Change Log ============================ III MMDDYY Change */ #endregion namespace Adapdev.Diagnostics { /// <summary> /// Summary description for PerfTimer. /// </summary> public interface IPerfTimer { void Start(); void Stop(); double Duration { get; } } } --- NEW FILE: MillisecondsPerfTimer.cs --- #region Copyright / License Information /* Copyright 2004 - 2005 Adapdev Technologies, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ============================ Author Log ============================ III Full Name SMM Sean McCormack (Adapdev) ============================ Change Log ============================ III MMDDYY Change */ #endregion namespace Adapdev.Diagnostics { using System; /// <summary> /// Summary description for DateTimePerfTimer. /// </summary> public class MillisecondsPerfTimer : IPerfTimer { private DateTime start; private TimeSpan stop; public MillisecondsPerfTimer() { } #region IPerfTimer Members public void Start() { start = DateTime.Now; } public void Stop() { stop = DateTime.Now.Subtract(start); } public double Duration { get { return stop.TotalMilliseconds; } } #endregion } } --- NEW FILE: MinutesPerfTimer.cs --- #region Copyright / License Information /* Copyright 2004 - 2005 Adapdev Technologies, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ============================ Author Log ============================ III Full Name SMM Sean McCormack (Adapdev) ============================ Change Log ============================ III MMDDYY Change */ #endregion namespace Adapdev.Diagnostics { using System; /// <summary> /// Summary description for DateTimePerfTimer. /// </summary> public class MinutesPerfTimer : IPerfTimer { private DateTime start; private TimeSpan stop; public MinutesPerfTimer() { } #region IPerfTimer Members public void Start() { start = DateTime.Now; } public void Stop() { stop = DateTime.Now.Subtract(start); } public double Duration { get { return stop.TotalMinutes; } } #endregion } } --- NEW FILE: TicksPerfTimer.cs --- #region Copyright / License Information /* Copyright 2004 - 2005 Adapdev Technologies, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ============================ Author Log ============================ III Full Name SMM Sean McCormack (Adapdev) ============================ Change Log ============================ III MMDDYY Change */ #endregion namespace Adapdev.Diagnostics { using System; /// <summary> /// Summary description for TicksPerfTimer. /// </summary> public class TicksPerfTimer : IPerfTimer { private int start; private int stop; public TicksPerfTimer() { // // TODO: Add constructor logic here // } #region IPerfTimer Members public void Start() { start = Environment.TickCount; } public void Stop() { stop = Environment.TickCount - start; } public double Duration { get { return stop; } } #endregion } } --- NEW FILE: PerfTimerFactory.cs --- #region Copyright / License Information /* Copyright 2004 - 2005 Adapdev Technologies, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ============================ Author Log ============================ III Full Name SMM Sean McCormack (Adapdev) ============================ Change Log ============================ III MMDDYY Change */ #endregion namespace Adapdev.Diagnostics { /// <summary> /// Summary description for PerfTimerFactory. /// </summary> public class PerfTimerFactory { public PerfTimerFactory() { // // TODO: Add constructor logic here // } public static IPerfTimer GetPerfTimer(PerfTimerType type) { switch (type) { case PerfTimerType.MILLISECONDS: return new MillisecondsPerfTimer(); case PerfTimerType.HIRESSECONDS: return new HiPerfTimer(); case PerfTimerType.SECONDS: return new SecondsPerfTimer(); case PerfTimerType.MINUTES: return new MinutesPerfTimer(); case PerfTimerType.TICKS: return new TicksPerfTimer(); default: return new MillisecondsPerfTimer(); } } } public enum PerfTimerType { TICKS, MILLISECONDS, HIRESSECONDS, SECONDS, MINUTES } } --- NEW FILE: HiPerfTimer.cs --- // Original Copyright 2002 Daniel Strigl. http://www.codeproject.com/csharp/highperformancetimercshar.asp?target=timer #region Modified Copyright / License Information /* Copyright 2004 - 2005 Adapdev Technologies, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ============================ Author Log ============================ III Full Name SMM Sean McCormack (Adapdev) ============================ Change Log ============================ III MMDDYY Change */ #endregion namespace Adapdev.Diagnostics { using System.ComponentModel; using System.Runtime.InteropServices; using System.Threading; internal class HiPerfTimer : IPerfTimer { [DllImport("Kernel32.dll")] private static extern bool QueryPerformanceCounter( out long lpPerformanceCount); [DllImport("Kernel32.dll")] private static extern bool QueryPerformanceFrequency( out long lpFrequency); private long startTime, stopTime; private long freq; // Constructor public HiPerfTimer() { startTime = 0; stopTime = 0; if (QueryPerformanceFrequency(out freq) == false) { // high-performance counter not supported throw new Win32Exception(); } } // Start the timer public void Start() { // lets do the waiting threads there work Thread.Sleep(0); QueryPerformanceCounter(out startTime); } // Stop the timer public void Stop() { QueryPerformanceCounter(out stopTime); } // Returns the duration of the timer (in seconds) public double Duration { get { double d = (stopTime - startTime); return d/freq; } } } } --- NEW FILE: CPUMeter.cs --- // Original Copyright (c) 2004, Ingo Rammer http://www.thinktecture.com/staff/ingo/weblog/archives/001403.html /** * Usage: * * static void Main(string[] args) * { * CPUMeter mtr = new CPUMeter(); * // do some heavy stuff * double result = 0; * for (int i = 0;i<100000000; i++) * { * result = result+Math.Sin(i); * } * double usage = mtr.GetCpuUtilization(); * Console.WriteLine("Done. CPU Usage {0:#00.00} %", usage); * Console.ReadLine(); * } * */ #region Modified Copyright / License Information /* Copyright 2004 - 2005 Adapdev Technologies, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ============================ Author Log ============================ III Full Name SMM Sean McCormack (Adapdev) ============================ Change Log ============================ III MMDDYY Change */ #endregion namespace Adapdev.Diagnostics { using System; using System.Diagnostics; public class CPUMeter : IDisposable { private CounterSample _startSample; private PerformanceCounter _cnt; /// Creates a per-process CPU meter instance tied to the current process. public CPUMeter() { String instancename = GetCurrentProcessInstanceName(); _cnt = new PerformanceCounter("Process", "% Processor Time", instancename, true); ResetCounter(); } /// Creates a per-process CPU meter instance tied to a specific process. public CPUMeter(int pid) { String instancename = GetProcessInstanceName(pid); _cnt = new PerformanceCounter("Process", "% Processor Time", instancename, true); ResetCounter(); } /// Resets the internal counter. All subsequent calls to GetCpuUtilization() will /// be relative to the point in time when you called ResetCounter(). This /// method can be call as often as necessary to get a new baseline for /// CPU utilization measurements. public void ResetCounter() { _startSample = _cnt.NextSample(); } /// Returns this process's CPU utilization since the last call to ResetCounter(). public double GetCpuUtilization() { CounterSample curr = _cnt.NextSample(); double diffValue = curr.RawValue - _startSample.RawValue; double diffTimestamp = curr.TimeStamp100nSec - _startSample.TimeStamp100nSec; double usage = (diffValue/diffTimestamp)*100; return usage; } private static string GetCurrentProcessInstanceName() { Process proc = Process.GetCurrentProcess(); int pid = proc.Id; return GetProcessInstanceName(pid); } private static string GetProcessInstanceName(int pid) { PerformanceCounterCategory cat = new PerformanceCounterCategory("Process"); string[] instances = cat.GetInstanceNames(); foreach (string instance in instances) { using (PerformanceCounter cnt = new PerformanceCounter("Process", "ID Process", instance, true)) { int val = (int) cnt.RawValue; if (val == pid) { return instance; } } } throw new Exception("Could not find performance counter " + "instance name for current process. This is truly strange ..."); } public void Dispose() { if (_cnt != null) _cnt.Dispose(); } } } |
From: Sean M. <int...@us...> - 2005-11-16 05:33:39
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev/Reflection In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv19977/src/Adapdev/Reflection Added Files: ClassAccessor.cs ClassAccessorCache.cs FieldAccessor.cs FieldAccessorException.cs IValueAccessor.cs PropertyAccessor.cs PropertyAccessorException.cs ReflectionCache.cs Log Message: Reposting to the repository after it got hosed --- NEW FILE: ClassAccessorCache.cs --- using System; using System.Collections; using System.Text; namespace Adapdev.Reflection { /// <summary> /// Summary description for ClassAccessorCache. /// </summary> public class ClassAccessorCache { private static Hashtable _classes = new Hashtable(); private ClassAccessorCache() { } public static ClassAccessor Get(Type t) { ClassAccessor c = null; if(!_classes.ContainsKey(t.FullName)) { c = new ClassAccessor(t); Add(c); c.LoadAllProperties(); } else { c = _classes[t.FullName] as ClassAccessor; } return c; } public static ClassAccessor Get(object o) { return Get(o.GetType()); } public static void Add(ClassAccessor c) { _classes[c.Type.FullName] = c; } public static void Remove(Type t) { _classes.Remove(t.FullName); } public static void Clear() { _classes.Clear(); } public static int Count { get{return _classes.Count;} } public static string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("Properties for ClassAccessorCache: " + Environment.NewLine); foreach(ClassAccessor c in _classes.Values) { sb.Append(c + Environment.NewLine); } return sb.ToString(); } } } --- NEW FILE: PropertyAccessor.cs --- // // Author: James Nies // Date: 3/22/2005 // Description: The PropertyAccessor class provides fast dynamic access // to a property of a specified target class. // // *** This code was written by James Nies and has been provided to you, *** // *** free of charge, for your use. I assume no responsibility for any *** // *** undesired events resulting from the use of this code or the *** // *** information that has been provided with it . *** // using System; using System.Reflection; using System.Reflection.Emit; using System.Threading; using System.Collections; namespace Adapdev.Reflection { /// <summary> /// The PropertyAccessor class provides fast dynamic access /// to a property of a specified target class. /// </summary> public class PropertyAccessor : IValueAccessor { /// <summary> /// Creates a new property accessor. /// </summary> /// <param name="targetType">Target object type.</param> /// <param name="property">Property name.</param> public PropertyAccessor(Type targetType, string property) { this.mTargetType = targetType; this.mProperty = property; PropertyInfo propertyInfo = targetType.GetProperty(property); // // Make sure the property exists // if(propertyInfo == null) { throw new PropertyAccessorException( string.Format("Property \"{0}\" does not exist for type " + "{1}.", property, targetType)); } else { this.mCanRead = propertyInfo.CanRead; this.mCanWrite = propertyInfo.CanWrite; this.mPropertyType = propertyInfo.PropertyType; } } /// <summary> /// Gets the property value from the specified target. /// </summary> /// <param name="target">Target object.</param> /// <returns>Property value.</returns> public object Get(object target) { if(mCanRead) { if(this.mEmittedValueAccessor == null) { this.Init(); } return this.mEmittedValueAccessor.Get(target); } else { throw new PropertyAccessorException( string.Format("Property \"{0}\" does not have a get method.", mProperty)); } } /// <summary> /// Sets the property for the specified target. /// </summary> /// <param name="target">Target object.</param> /// <param name="value">Value to set.</param> public void Set(object target, object value) { if(mCanWrite) { if(this.mEmittedValueAccessor == null) { this.Init(); } // // Set the property value // this.mEmittedValueAccessor.Set(target, value); } else { throw new PropertyAccessorException( string.Format("Property \"{0}\" does not have a set method.", mProperty)); } } /// <summary> /// Whether or not the Property supports read access. /// </summary> public bool CanRead { get { return this.mCanRead; } } /// <summary> /// Whether or not the Property supports write access. /// </summary> public bool CanWrite { get { return this.mCanWrite; } } /// <summary> /// The Type of object this property accessor was /// created for. /// </summary> public Type TargetType { get { return this.mTargetType; } } /// <summary> /// The Type of the Property being accessed. /// </summary> public Type PropertyType { get { return this.mPropertyType; } } private Type mTargetType; private string mProperty; private Type mPropertyType; private IValueAccessor mEmittedValueAccessor; private Hashtable mTypeHash; private bool mCanRead; private bool mCanWrite; /// <summary> /// This method generates creates a new assembly containing /// the Type that will provide dynamic access. /// </summary> private void Init() { this.InitTypes(); // Create the assembly and an instance of the // property accessor class. Assembly assembly = EmitAssembly(); mEmittedValueAccessor = assembly.CreateInstance("Property") as IValueAccessor; if(mEmittedValueAccessor == null) { throw new Exception("Unable to create property accessor."); } } /// <summary> /// Thanks to Ben Ratzlaff for this snippet of code /// http://www.codeproject.com/cs/miscctrl/CustomPropGrid.asp /// /// "Initialize a private hashtable with type-opCode pairs /// so i dont have to write a long if/else statement when outputting msil" /// </summary> private void InitTypes() { mTypeHash=new Hashtable(); mTypeHash[typeof(sbyte)]=OpCodes.Ldind_I1; mTypeHash[typeof(byte)]=OpCodes.Ldind_U1; mTypeHash[typeof(char)]=OpCodes.Ldind_U2; mTypeHash[typeof(short)]=OpCodes.Ldind_I2; mTypeHash[typeof(ushort)]=OpCodes.Ldind_U2; mTypeHash[typeof(int)]=OpCodes.Ldind_I4; mTypeHash[typeof(uint)]=OpCodes.Ldind_U4; mTypeHash[typeof(long)]=OpCodes.Ldind_I8; mTypeHash[typeof(ulong)]=OpCodes.Ldind_I8; mTypeHash[typeof(bool)]=OpCodes.Ldind_I1; mTypeHash[typeof(double)]=OpCodes.Ldind_R8; mTypeHash[typeof(float)]=OpCodes.Ldind_R4; } /// <summary> /// Create an assembly that will provide the get and set methods. /// </summary> private Assembly EmitAssembly() { // // Create an assembly name // AssemblyName assemblyName = new AssemblyName(); assemblyName.Name = "PropertyAccessorAssembly"; // // Create a new assembly with one module // AssemblyBuilder newAssembly = Thread.GetDomain().DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); ModuleBuilder newModule = newAssembly.DefineDynamicModule("Module"); // // Define a public class named "Property" in the assembly. // TypeBuilder myType = newModule.DefineType("Property", TypeAttributes.Public); // // Mark the class as implementing IPropertyAccessor. // myType.AddInterfaceImplementation(typeof(IValueAccessor)); // Add a constructor ConstructorBuilder constructor = myType.DefineDefaultConstructor(MethodAttributes.Public); // // Define a method for the get operation. // Type[] getParamTypes = new Type[] {typeof(object)}; Type getReturnType = typeof(object); MethodBuilder getMethod = myType.DefineMethod("Get", MethodAttributes.Public | MethodAttributes.Virtual, getReturnType, getParamTypes); // // From the method, get an ILGenerator. This is used to // emit the IL that we want. // ILGenerator getIL = getMethod.GetILGenerator(); // // Emit the IL. // MethodInfo targetGetMethod = this.mTargetType.GetMethod("get_" + this.mProperty); if(targetGetMethod != null) { getIL.DeclareLocal(typeof(object)); getIL.Emit(OpCodes.Ldarg_1); //Load the first argument //(target object) getIL.Emit(OpCodes.Castclass, this.mTargetType); //Cast to the source type getIL.EmitCall(OpCodes.Call, targetGetMethod, null); //Get the property value if(targetGetMethod.ReturnType.IsValueType) { getIL.Emit(OpCodes.Box, targetGetMethod.ReturnType); //Box if necessary } getIL.Emit(OpCodes.Stloc_0); //Store it getIL.Emit(OpCodes.Ldloc_0); } else { getIL.ThrowException(typeof(MissingMethodException)); } getIL.Emit(OpCodes.Ret); // // Define a method for the set operation. // Type[] setParamTypes = new Type[] {typeof(object), typeof(object)}; Type setReturnType = null; MethodBuilder setMethod = myType.DefineMethod("Set", MethodAttributes.Public | MethodAttributes.Virtual, setReturnType, setParamTypes); // // From the method, get an ILGenerator. This is used to // emit the IL that we want. // ILGenerator setIL = setMethod.GetILGenerator(); // // Emit the IL. // MethodInfo targetSetMethod = this.mTargetType.GetMethod("set_" + this.mProperty); if(targetSetMethod != null) { Type paramType = targetSetMethod.GetParameters()[0].ParameterType; setIL.DeclareLocal(paramType); setIL.Emit(OpCodes.Ldarg_1); //Load the first argument //(target object) setIL.Emit(OpCodes.Castclass, this.mTargetType); //Cast to the source type setIL.Emit(OpCodes.Ldarg_2); //Load the second argument //(value object) if(paramType.IsValueType) { setIL.Emit(OpCodes.Unbox, paramType); //Unbox it if(mTypeHash[paramType]!=null) //and load { OpCode load = (OpCode)mTypeHash[paramType]; setIL.Emit(load); } else { setIL.Emit(OpCodes.Ldobj,paramType); } } else { setIL.Emit(OpCodes.Castclass, paramType); //Cast class } setIL.EmitCall(OpCodes.Callvirt, targetSetMethod, null); //Set the property value } else { setIL.ThrowException(typeof(MissingMethodException)); } setIL.Emit(OpCodes.Ret); // // Load the type // myType.CreateType(); return newAssembly; } } } --- NEW FILE: IValueAccessor.cs --- // // Author: James Nies // Date: 3/22/2005 // Description: The PropertyAccessor class uses this interface // for creating a type at runtime for accessing an individual // property on a target object. // // *** This code was written by James Nies and has been provided to you, *** // *** free of charge, for your use. I assume no responsibility for any *** // *** undesired events resulting from the use of this code or the *** // *** information that has been provided with it . *** // using System; namespace Adapdev.Reflection { /// <summary> /// The IPropertyAccessor interface defines a property /// accessor. /// </summary> public interface IValueAccessor { /// <summary> /// Gets the value stored in the property for /// the specified target. /// </summary> /// <param name="target">Object to retrieve /// the property from.</param> /// <returns>Property value.</returns> object Get(object target); /// <summary> /// Sets the value for the property of /// the specified target. /// </summary> /// <param name="target">Object to set the /// property on.</param> /// <param name="value">Property value.</param> void Set(object target, object value); } } --- NEW FILE: FieldAccessor.cs --- // // Author: James Nies // Date: 3/22/2005 // Description: The PropertyAccessor class provides fast dynamic access // to a property of a specified target class. // // *** This code was written by James Nies and has been provided to you, *** // *** free of charge, for your use. I assume no responsibility for any *** // *** undesired events resulting from the use of this code or the *** // *** information that has been provided with it . *** // using System; using System.Reflection; using System.Reflection.Emit; using System.Threading; using System.Collections; namespace Adapdev.Reflection { /// <summary> /// The PropertyAccessor class provides fast dynamic access /// to a property of a specified target class. /// </summary> public class FieldAccessor : IValueAccessor { /// <summary> /// Creates a new property accessor. /// </summary> /// <param name="targetType">Target object type.</param> /// <param name="field">Property name.</param> public FieldAccessor(Type targetType, string field) { this.mTargetType = targetType; this.mField = field; FieldInfo fieldInfo = targetType.GetField(field, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public); // // Make sure the property exists // if(fieldInfo == null) { throw new FieldAccessorException( string.Format("Field \"{0}\" does not exist for type " + "{1}.", field, targetType)); } else { this.mCanRead = true; this.mCanWrite = true; //!fieldInfo.IsInitOnly; this.mFieldType = fieldInfo.FieldType; this.fi = fieldInfo; } } /// <summary> /// Gets the property value from the specified target. /// </summary> /// <param name="target">Target object.</param> /// <returns>Property value.</returns> public object Get(object target) { if(mCanRead) { if(this.mEmittedValueAccessor == null) { this.Init(); } return this.mEmittedValueAccessor.Get(target); } else { throw new FieldAccessorException( string.Format("Field \"{0}\" does not have a get method.", mField)); } } /// <summary> /// Sets the property for the specified target. /// </summary> /// <param name="target">Target object.</param> /// <param name="value">Value to set.</param> public void Set(object target, object value) { if(mCanWrite) { if(this.mEmittedValueAccessor == null) { this.Init(); } // // Set the property value // this.mEmittedValueAccessor.Set(target, value); } else { throw new FieldAccessorException( string.Format("Field \"{0}\" does not have a set method.", mField)); } } /// <summary> /// Whether or not the Property supports read access. /// </summary> public bool CanRead { get { return this.mCanRead; } } /// <summary> /// Whether or not the Property supports write access. /// </summary> public bool CanWrite { get { return this.mCanWrite; } } /// <summary> /// The Type of object this property accessor was /// created for. /// </summary> public Type TargetType { get { return this.mTargetType; } } /// <summary> /// The Type of the Property being accessed. /// </summary> public Type FieldType { get { return this.mFieldType; } } private Type mTargetType; private string mField; private Type mFieldType; private IValueAccessor mEmittedValueAccessor; private Hashtable mTypeHash; private bool mCanRead; private bool mCanWrite; private FieldInfo fi; /// <summary> /// This method generates creates a new assembly containing /// the Type that will provide dynamic access. /// </summary> private void Init() { this.InitTypes(); // Create the assembly and an instance of the // property accessor class. Assembly assembly = EmitAssembly(); mEmittedValueAccessor = assembly.CreateInstance("Field") as IValueAccessor; if(mEmittedValueAccessor == null) { throw new Exception("Unable to create property accessor."); } } /// <summary> /// Thanks to Ben Ratzlaff for this snippet of code /// http://www.codeproject.com/cs/miscctrl/CustomPropGrid.asp /// /// "Initialize a private hashtable with type-opCode pairs /// so i dont have to write a long if/else statement when outputting msil" /// </summary> private void InitTypes() { mTypeHash=new Hashtable(); mTypeHash[typeof(sbyte)]=OpCodes.Ldind_I1; mTypeHash[typeof(byte)]=OpCodes.Ldind_U1; mTypeHash[typeof(char)]=OpCodes.Ldind_U2; mTypeHash[typeof(short)]=OpCodes.Ldind_I2; mTypeHash[typeof(ushort)]=OpCodes.Ldind_U2; mTypeHash[typeof(int)]=OpCodes.Ldind_I4; mTypeHash[typeof(uint)]=OpCodes.Ldind_U4; mTypeHash[typeof(long)]=OpCodes.Ldind_I8; mTypeHash[typeof(ulong)]=OpCodes.Ldind_I8; mTypeHash[typeof(bool)]=OpCodes.Ldind_I1; mTypeHash[typeof(double)]=OpCodes.Ldind_R8; mTypeHash[typeof(float)]=OpCodes.Ldind_R4; } /// <summary> /// Create an assembly that will provide the get and set methods. /// </summary> private Assembly EmitAssembly() { // // Create an assembly name // AssemblyName assemblyName = new AssemblyName(); assemblyName.Name = "FieldAccessorAssembly"; // // Create a new assembly with one module // AssemblyBuilder newAssembly = Thread.GetDomain().DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); ModuleBuilder newModule = newAssembly.DefineDynamicModule("Module"); // // Define a public class named "Property" in the assembly. // TypeBuilder myType = newModule.DefineType("Field", TypeAttributes.Public); // // Mark the class as implementing IPropertyAccessor. // myType.AddInterfaceImplementation(typeof(IValueAccessor)); // Add a constructor ConstructorBuilder constructor = myType.DefineDefaultConstructor(MethodAttributes.Public); // // Define a method for the get operation. // Type[] getParamTypes = new Type[] {typeof(object)}; Type getReturnType = typeof(object); MethodBuilder getMethod = myType.DefineMethod("Get", MethodAttributes.Public | MethodAttributes.Virtual, getReturnType, getParamTypes); // // From the method, get an ILGenerator. This is used to // emit the IL that we want. // ILGenerator getIL = getMethod.GetILGenerator(); // // Emit the IL. // // MethodInfo targetGetMethod = this.mTargetType.GetMethod("get_" + this.mField); // // if(targetGetMethod != null) // { // TODO: Fix this piece getIL.DeclareLocal(typeof(object)); getIL.Emit(OpCodes.Ldarg_1); //Load the first argument //(target object) getIL.Emit(OpCodes.Castclass, this.mTargetType); //Cast to the source type getIL.Emit(OpCodes.Stfld, this.mField); //getIL.EmitCall(OpCodes.Call, targetGetMethod, null); //Get the property value // if(targetGetMethod.ReturnType.IsValueType) // { // getIL.Emit(OpCodes.Box, targetGetMethod.ReturnType); //Box if necessary // } getIL.Emit(OpCodes.Stloc_0); //Store it getIL.Emit(OpCodes.Ldloc_0); // } // else // { // getIL.ThrowException(typeof(MissingMethodException)); // } getIL.Emit(OpCodes.Ret); // // Define a method for the set operation. // Type[] setParamTypes = new Type[] {typeof(object), typeof(object)}; Type setReturnType = null; MethodBuilder setMethod = myType.DefineMethod("Set", MethodAttributes.Public | MethodAttributes.Virtual, setReturnType, setParamTypes); // // From the method, get an ILGenerator. This is used to // emit the IL that we want. // ILGenerator setIL = setMethod.GetILGenerator(); // // Emit the IL. // MethodInfo targetSetMethod = this.mTargetType.GetMethod("set_" + this.mField); if(targetSetMethod != null) { Type paramType = targetSetMethod.GetParameters()[0].ParameterType; setIL.DeclareLocal(paramType); setIL.Emit(OpCodes.Ldarg_1); //Load the first argument //(target object) setIL.Emit(OpCodes.Castclass, this.mTargetType); //Cast to the source type setIL.Emit(OpCodes.Ldarg_2); //Load the second argument //(value object) if(paramType.IsValueType) { setIL.Emit(OpCodes.Unbox, paramType); //Unbox it if(mTypeHash[paramType]!=null) //and load { OpCode load = (OpCode)mTypeHash[paramType]; setIL.Emit(load); } else { setIL.Emit(OpCodes.Ldobj,paramType); } } else { setIL.Emit(OpCodes.Castclass, paramType); //Cast class } setIL.EmitCall(OpCodes.Callvirt, targetSetMethod, null); //Set the property value } else { setIL.ThrowException(typeof(MissingMethodException)); } setIL.Emit(OpCodes.Ret); // // Load the type // myType.CreateType(); return newAssembly; } } } --- NEW FILE: PropertyAccessorException.cs --- // // Author: James Nies // Date: 3/22/2005 // Description: Exception that can be thrown from the PropertyAccessor // class. // // *** This code was written by James Nies and has been provided to you, *** // *** free of charge, for your use. I assume no responsibility for any *** // *** undesired events resulting from the use of this code or the *** // *** information that has been provided with it . *** // using System; namespace Adapdev.Reflection { /// <summary> /// PropertyAccessorException class. /// </summary> public class PropertyAccessorException : Exception { public PropertyAccessorException(string message) : base(message) { } } } --- NEW FILE: ClassAccessor.cs --- using System; using System.Collections; using System.Reflection; using System.Text; namespace Adapdev.Reflection { /// <summary> /// Summary description for ClassAccessor. /// </summary> public class ClassAccessor { private Type _type = null; private Hashtable _properties = new Hashtable(); private DateTime _created; public ClassAccessor(Type t) { this._type = t; this._created = DateTime.Now; } public ClassAccessor(object o) : this(o.GetType()){} public void AddProperty(string name) { PropertyAccessor accessor = new PropertyAccessor(this._type, name); this._properties[name] = accessor; } public object GetPropertyValue(object o, string propertyName) { this.CheckForAccessor(propertyName); PropertyAccessor accessor = this._properties[propertyName] as PropertyAccessor; return accessor.Get(o); } public PropertyAccessor GetPropertyAccessor(string propertyName) { return this._properties[propertyName] as PropertyAccessor; } public Hashtable GetPropertyAccessors() { return this._properties; } public Type PropertyType(string propertyName) { this.CheckForAccessor(propertyName); PropertyAccessor accessor = this._properties[propertyName] as PropertyAccessor; return accessor.PropertyType; } public Type Type { get { return this._type; } } public void SetPropertyValue(object o, string propertyName, object val) { this.CheckForAccessor(propertyName); PropertyAccessor accessor = this._properties[propertyName] as PropertyAccessor; accessor.Set(o, val); } private void CheckForAccessor(string propertyName) { if(!this.IsPropertyDefined(propertyName)) this.AddProperty(propertyName); } private bool IsPropertyDefined(string propertyName) { return this._properties.ContainsKey(propertyName); } public void LoadAllProperties() { PropertyInfo[] infoArray = this._type.GetProperties(); foreach(PropertyInfo p in infoArray) { this.AddProperty(p.Name); } } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("[" + this._type.FullName + "] Properties loaded: " + Environment.NewLine); foreach(string key in this._properties.Keys) { sb.Append(key + Environment.NewLine); } return sb.ToString(); } public int PropertyCount { get{return this._properties.Count;} } } } --- NEW FILE: FieldAccessorException.cs --- using System; namespace Adapdev.Reflection { /// <summary> /// PropertyAccessorException class. /// </summary> public class FieldAccessorException : Exception { public FieldAccessorException(string message) : base(message) { } } } --- NEW FILE: ReflectionCache.cs --- #region Copyright / License Information /* Copyright 2004 - 2005 Adapdev Technologies, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ============================ Author Log ============================ III Full Name SMM Sean McCormack (Adapdev) ============================ Change Log ============================ III MMDDYY Change */ #endregion namespace Adapdev.Reflection { using System; using System.Collections; using System.Collections.Specialized; using System.Reflection; /// <summary> /// Summary description for ReflectionCache. /// </summary> public class ReflectionCache { private static ReflectionCache instance; private HybridDictionary assemblies = new HybridDictionary(); private Hashtable types = new Hashtable(); public static ReflectionCache GetInstance() { if (instance == null) { instance = new ReflectionCache(); } return instance; } public Assembly GetAssembly(string assembly) { if (assemblies.Contains(assembly)) { return (Assembly) assemblies[assembly]; } else { Assembly a = Assembly.LoadFrom(assembly); assemblies[assembly] = a; return a; } } public Type GetType(string assembly, string type) { string id = assembly + "|" + type; if (types.Contains(id)) { return (Type) types[id]; } else { Assembly a = this.GetAssembly(assembly); Type t = a.GetType(type, true, true); types[id] = t; return t; } } } } |
From: Sean M. <int...@us...> - 2005-11-16 05:33:39
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev/XPath/Internal In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv19977/src/Adapdev/XPath/Internal Added Files: ObjectNavigationContext.cs ObjectNavigatorState.cs ObjectNavigatorStateDictionary.cs ObjectNavigatorStateItem.cs ObjectNavigatorStateList.cs ObjectNavigatorStateRoot.cs Log Message: Reposting to the repository after it got hosed --- NEW FILE: ObjectNavigationContext.cs --- #region license // Bamboo.Prevalence - a .NET object prevalence engine // Copyright (C) 2004 Rodrigo B. de Oliveira // // Based on the original concept and implementation of Prevayler (TM) // by Klaus Wuestefeld. Visit http://www.prevayler.org for details. // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, // and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE // OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // Contact Information // // http://bbooprevalence.sourceforge.net // mailto:rod...@us... #endregion using System; using System.Xml; namespace Adapdev.XPath.Internal { internal class ObjectNavigationContext { public NameTable NameTable; public TypeInfoCache TypeInfoCache; public ObjectNavigationContext() { NameTable = new NameTable(); TypeInfoCache = new TypeInfoCache(); } } } --- NEW FILE: ObjectNavigatorStateList.cs --- #region license // Bamboo.Prevalence - a .NET object prevalence engine // Copyright (C) 2004 Rodrigo B. de Oliveira // // Based on the original concept and implementation of Prevayler (TM) // by Klaus Wuestefeld. Visit http://www.prevayler.org for details. // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, // and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE // OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // Contact Information // // http://bbooprevalence.sourceforge.net // mailto:rod...@us... #endregion using System; using System.Collections; using System.Xml; using System.Xml.XPath; namespace Adapdev.XPath.Internal { internal class ObjectNavigatorStateList : ObjectNavigatorState { IList _children; internal ObjectNavigatorStateList(ObjectNavigationContext context, ObjectNavigatorState parent, object node, string name) : base(context, parent, node, name) { _children = (IList)node; } internal override XPathNodeType NodeType { get { return XPathNodeType.Element; } } internal override ObjectNavigatorState MoveToFirstChild() { return MoveToChild(0); } internal override ObjectNavigatorState MoveToNext() { return _parent.MoveToChild(_index + 1); } internal override ObjectNavigatorState MoveToChild(int index) { while (index < _children.Count) { object child = _children[index]; if (null != child) { ObjectNavigatorState state = CreateElementState(_context, this, child, child.GetType().Name); state.Index = index; return state; } ++index; } return null; } } } --- NEW FILE: ObjectNavigatorStateRoot.cs --- #region license // Bamboo.Prevalence - a .NET object prevalence engine // Copyright (C) 2004 Rodrigo B. de Oliveira // // Based on the original concept and implementation of Prevayler (TM) // by Klaus Wuestefeld. Visit http://www.prevayler.org for details. // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, // and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE // OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // Contact Information // // http://bbooprevalence.sourceforge.net // mailto:rod...@us... #endregion using System; using System.Xml; using System.Xml.XPath; namespace Adapdev.XPath.Internal { internal class ObjectNavigatorStateRoot : ObjectNavigatorState { ObjectNavigatorState _child; internal ObjectNavigatorStateRoot(ObjectNavigationContext context, object node, string nodeName) : base(context, null, node, "#document") { if (null == nodeName) { nodeName = _node.GetType().Name; } _child = CreateElementState(context, this, node, nodeName); } internal override ObjectNavigatorState MoveToFirstChild() { return _child; } internal override XPathNodeType NodeType { get { return XPathNodeType.Root; } } } } --- NEW FILE: ObjectNavigatorState.cs --- #region license // Bamboo.Prevalence - a .NET object prevalence engine // Copyright (C) 2004 Rodrigo B. de Oliveira // // Based on the original concept and implementation of Prevayler (TM) // by Klaus Wuestefeld. Visit http://www.prevayler.org for details. // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, // and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE // OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // Contact Information // // http://bbooprevalence.sourceforge.net // mailto:rod...@us... #endregion using System; using System.Collections; using System.Xml; using System.Xml.XPath; namespace Adapdev.XPath.Internal { internal abstract class ObjectNavigatorState { protected int _index; protected string _name; protected ObjectNavigatorState _parent; protected object _node; protected ObjectNavigationContext _context; public ObjectNavigatorState(ObjectNavigationContext context, ObjectNavigatorState parent, object node, string name) { _parent = parent; _context = context; _node = node; _name = _context.NameTable.Add(name); _index = 0; } internal int Index { get { return _index; } set { _index = value; } } internal virtual bool IsSamePosition(ObjectNavigatorState other) { return other._node == _node && other._index == _index && other._name == _name && other._parent == _parent; } internal virtual string Name { get { return _name; } } internal virtual string Value { get { return _node.ToString(); } } internal ObjectNavigatorState Parent { get { return _parent; } } internal object Node { get { return _node; } } internal abstract XPathNodeType NodeType { get; } internal virtual ObjectNavigatorState MoveToFirstChild() { return null; } internal virtual ObjectNavigatorState MoveToNext() { return null; } internal virtual ObjectNavigatorState MoveToChild(int index) { return null; } internal static ObjectNavigatorState CreateElementState(ObjectNavigationContext context, ObjectNavigatorState parent, object node, string name) { if (node is IDictionary) { return new ObjectNavigatorStateDictionary(context, parent, node, name); } else if (node is IList) { return new ObjectNavigatorStateList(context, parent, node, name); } else { return new ObjectNavigatorStateItem(context, parent, node, name); } } } } --- NEW FILE: ObjectNavigatorStateDictionary.cs --- #region license // Bamboo.Prevalence - a .NET object prevalence engine // Copyright (C) 2004 Rodrigo B. de Oliveira // // Based on the original concept and implementation of Prevayler (TM) // by Klaus Wuestefeld. Visit http://www.prevayler.org for details. // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, // and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE // OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // Contact Information // // http://bbooprevalence.sourceforge.net // mailto:rod...@us... #endregion using System; using System.Collections; using System.Xml; using System.Xml.XPath; namespace Adapdev.XPath.Internal { internal class ObjectNavigatorStateDictionary : ObjectNavigatorState { IDictionary _dictionary; IList _children; internal ObjectNavigatorStateDictionary(ObjectNavigationContext context, ObjectNavigatorState parent, object node, string name) : base(context, parent, node, name) { _dictionary = (IDictionary)node; _children = new ArrayList(_dictionary.Keys); } internal override XPathNodeType NodeType { get { return XPathNodeType.Element; } } internal override ObjectNavigatorState MoveToFirstChild() { return MoveToChild(0); } internal override ObjectNavigatorState MoveToNext() { return _parent.MoveToChild(_index + 1); } internal override ObjectNavigatorState MoveToChild(int index) { while (index < _children.Count) { object key = _children[index]; object child = _dictionary[key]; if (null != child) { ObjectNavigatorState state = CreateElementState(_context, this, child, key.ToString()); state.Index = index; return state; } ++index; } return null; } } } --- NEW FILE: ObjectNavigatorStateItem.cs --- #region license // Bamboo.Prevalence - a .NET object prevalence engine // Copyright (C) 2004 Rodrigo B. de Oliveira // // Based on the original concept and implementation of Prevayler (TM) // by Klaus Wuestefeld. Visit http://www.prevayler.org for details. // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, // and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE // OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // Contact Information // // http://bbooprevalence.sourceforge.net // mailto:rod...@us... #endregion using System; using System.Xml; using System.Xml.XPath; using System.Reflection; namespace Adapdev.XPath.Internal { internal class ObjectNavigatorStateItem : ObjectNavigatorState { IValueProvider[] _children; internal ObjectNavigatorStateItem(ObjectNavigationContext context, ObjectNavigatorState parent, object node, string name) : base(context, parent, node, name) { } internal override XPathNodeType NodeType { get { return XPathNodeType.Element; } } internal override ObjectNavigatorState MoveToFirstChild() { return MoveToChild(0); } internal override ObjectNavigatorState MoveToNext() { return _parent.MoveToChild(_index + 1); } internal override ObjectNavigatorState MoveToChild(int index) { CheckChildren(); while (index < _children.Length) { object child = _children[index].GetValue(_node); if (null != child) { ObjectNavigatorState state = CreateElementState(_context, this, child, _children[index].Name); state.Index = index; return state; } ++index; } return null; } void CheckChildren() { if (null != _children) { return; } _children = _context.TypeInfoCache.GetNavigableProperties(_node); } } } |
From: Sean M. <int...@us...> - 2005-11-16 05:33:39
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev/Text/Indexing/FullText/Tokenizers In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv19977/src/Adapdev/Text/Indexing/FullText/Tokenizers Added Files: NullTokenizer.cs StringTokenizer.cs Log Message: Reposting to the repository after it got hosed --- NEW FILE: StringTokenizer.cs --- #region license // Bamboo.Prevalence - a .NET object prevalence engine // Copyright (C) 2004 Rodrigo B. de Oliveira // // Based on the original concept and implementation of Prevayler (TM) // by Klaus Wuestefeld. Visit http://www.prevayler.org for details. // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, // and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE // OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // Contact Information // // http://bbooprevalence.sourceforge.net // mailto:rod...@us... #endregion using System; using Adapdev.Text.Indexing.FullText; namespace Adapdev.Text.Indexing.FullText.Tokenizers { /// <summary> /// Splits a string into tokens by considering any /// whitespace and punctuation characters as separators. /// </summary> /// <remarks> /// This tokenizer must always be the last in a /// tokenizer chain. /// </remarks> [Serializable] public class StringTokenizer : ITokenizer { string _text; int _current; /// <summary> /// Creates a new tokenizer for the string /// in the text argument. /// </summary> /// <param name="text">token source</param> public StringTokenizer(string text) : this(text, 0) { } /// <summary> /// Creates a new tokenizer for the string /// in the text argument starting from /// the position indicated by the current /// argument. /// </summary> /// <param name="text">token source</param> /// <param name="current">starting position</param> protected StringTokenizer(string text, int current) { if (null == text) { throw new ArgumentNullException("text", "text can't be null"); } _text = text; _current = current; } #region Implementation of ITokenizer /// <summary> /// Always returns null since this tokenizer /// must be the last in the chain. /// </summary> public ITokenizer Previous { get { return null; } set { throw new NotSupportedException("ITokenizer chaining not supported by StringTokenizer!"); } } /// <summary> /// See <see cref="Adapdev.Text.Indexing.FullText.ITokenizer.NextToken"/> for /// details. /// </summary> /// <returns></returns> public Adapdev.Text.Indexing.FullText.Token NextToken() { SkipSeparators(); int begin = _current; for (; _current<_text.Length; ++_current) { if (IsSeparator(_text, _current)) { break; } } if (_current > begin) { return new Token(_text.Substring(begin, _current-begin), begin); } return null; } /// <summary> /// Returns a clone. /// </summary> /// <param name="tail">must always be null</param> /// <returns>a clone</returns> public ITokenizer Clone(ITokenizer tail) { if (null != tail) { throw new NotSupportedException("ITokenizer chaining not supported by StringTokenizer!"); } return new StringTokenizer(_text, _current); } #endregion void SkipSeparators() { for (; _current<_text.Length; ++_current) { if (!IsSeparator(_text, _current)) { break; } } } bool IsSeparator(string text, int index) { char current = text[index]; return Char.IsWhiteSpace(current) || Char.IsPunctuation(current); } } } --- NEW FILE: NullTokenizer.cs --- #region license // Bamboo.Prevalence - a .NET object prevalence engine // Copyright (C) 2004 Rodrigo B. de Oliveira // // Based on the original concept and implementation of Prevayler (TM) // by Klaus Wuestefeld. Visit http://www.prevayler.org for details. // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, // and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE // OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // Contact Information // // http://bbooprevalence.sourceforge.net // mailto:rod...@us... #endregion using System; using Adapdev.Text.Indexing.FullText; namespace Adapdev.Text.Indexing.FullText.Tokenizers { /// <summary> /// Summary description for NullTokenizer. /// </summary> public class NullTokenizer : ITokenizer { /// <summary> /// The one and only NullTokenizer instance. /// </summary> public static ITokenizer Instance = new NullTokenizer(); private NullTokenizer() { } #region Implementation of ITokenizer /// <summary> /// Always returns null since this tokenizer /// must be the last in the chain. /// </summary> public ITokenizer Previous { get { return null; } set { throw new NotSupportedException("ITokenizer chaining not supported by NullTokenizer!"); } } /// <summary> /// See <see cref="Adapdev.Text.Indexing.FullText.ITokenizer.NextToken"/> for /// details. /// </summary> /// <returns></returns> public Adapdev.Text.Indexing.FullText.Token NextToken() { return null; } /// <summary> /// Returns this. /// </summary> /// <param name="tail">must always be null</param> /// <returns>a clone</returns> public ITokenizer Clone(ITokenizer tail) { return this; } #endregion } } |
From: Sean M. <int...@us...> - 2005-11-16 05:33:39
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev/XPath In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv19977/src/Adapdev/XPath Added Files: TypeInfoCache.cs XPathObjectNavigator.cs Log Message: Reposting to the repository after it got hosed --- NEW FILE: XPathObjectNavigator.cs --- #region license // Bamboo.Prevalence - a .NET object prevalence engine // Copyright (C) 2004 Rodrigo B. de Oliveira // // Based on the original concept and implementation of Prevayler (TM) // by Klaus Wuestefeld. Visit http://www.prevayler.org for details. // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, // and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE // OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // Contact Information // // http://bbooprevalence.sourceforge.net // mailto:rod...@us... #endregion using System; using System.Xml; using System.Xml.XPath; using Adapdev.XPath.Internal; namespace Adapdev.XPath { /// <summary> /// XPathNavigator implementation over an arbitrary /// object graph. /// </summary> /// <example> /// <code> /// Address address = new Address("Al. Calder�o Branco", 784); /// Customer customer = new Customer("Rodrigo", "Oliveira", address); /// /// XPathObjectNavigator context = new XPathObjectNavigator(customer); /// XPathNodeIterator i = context.Select("/Customer/Address/Street"); /// AssertEquals(1, i.Count); /// AssertEquals(true, i.MoveNext()); /// AssertEquals(customer.Address.Street, i.Current.Value); /// AssertEquals(customer.Address.Street, ((XPathObjectNavigator)i.Current).Node); /// </code> /// </example> public class XPathObjectNavigator : XPathNavigator { ObjectNavigatorState _state; ObjectNavigatorState _root; ObjectNavigationContext _context; string _lang; /// <summary> /// Create a new navigator for the object graph /// starting at node. The node's name is nodeName. /// </summary> /// <param name="node">root</param> /// <param name="nodeName">root's name</param> public XPathObjectNavigator(object node, string nodeName) { _context = new ObjectNavigationContext(); _context.NameTable.Add(string.Empty); _root = new ObjectNavigatorStateRoot(_context, node, nodeName); _state = _root.MoveToFirstChild(); _lang = _context.NameTable.Add("en-US"); } /// <summary> /// Create a new navigator for the object graph /// starting at node. The node name will be /// node.GetType().Name. /// </summary> /// <param name="node">root</param> public XPathObjectNavigator(object node) : this(node, null) { } /// <summary> /// copy constructor. /// </summary> /// <param name="other">navigator to be copied</param> public XPathObjectNavigator(XPathObjectNavigator other) { _context = other._context; _state = other._state; _root = other._root; _lang = other._lang; } /// <summary> /// Selects a single object from the current node. /// </summary> /// <param name="xpath">selection expression</param> /// <returns>the first object returned by the /// expression or null</returns> public object SelectObject(string xpath) { XPathNodeIterator i = Select(xpath); if (i.MoveNext()) { return ((XPathObjectNavigator)i.Current).Node; } return null; } /// <summary> /// Selects a group of objects from the current node. /// </summary> /// <param name="xpath">selection expression</param> /// <param name="returnItemType">array element type to be returned</param> /// <returns>an array with all the objects returned /// by the expression</returns> public System.Array SelectObjects(string xpath, Type returnItemType) { if (null == returnItemType) { throw new ArgumentNullException("returnItemType"); } System.Collections.ArrayList result = new System.Collections.ArrayList(); XPathNodeIterator i = Select(xpath); while (i.MoveNext()) { result.Add(((XPathObjectNavigator)i.Current).Node); } return result.ToArray(returnItemType); } /// <summary> /// Same as <see cref="SelectObjects(System.String, System.Type)"/> with /// returnItemType iguals to typeof(object). /// </summary> /// <param name="xpath"></param> /// <returns></returns> public object[] SelectObjects(string xpath) { return (object[])SelectObjects(xpath, typeof(object)); } /// <summary> /// See <see cref="System.Xml.XPath.XPathNavigator.BaseURI" /> for details. /// </summary> public override string BaseURI { get { Trace("get_BaseURI"); return _context.NameTable.Get(string.Empty); } } /// <summary> /// See <see cref="System.Xml.XPath.XPathNavigator.Clone" /> for details. /// </summary> public override System.Xml.XPath.XPathNavigator Clone() { Trace("Clone"); return new XPathObjectNavigator(this); } /// <summary> /// See <see cref="System.Xml.XPath.XPathNavigator.GetAttribute(string, string)" /> for details. /// </summary> /// <remarks>No attributes are returned.</remarks> public override string GetAttribute(string localName, string namespaceURI) { Trace("GetAttribute"); return string.Empty; } /// <summary> /// See <see cref="System.Xml.XPath.XPathNavigator.GetNamespace(string)" /> for details. /// </summary> /// <remarks>Namespace is always empty</remarks> public override string GetNamespace(string name) { Trace("GetNamespace"); return _context.NameTable.Get(string.Empty); } /// <summary> /// See <see cref="System.Xml.XPath.XPathNavigator.HasAttributes" /> for details. /// </summary> /// <remarks>false</remarks> public override bool HasAttributes { get { Trace("HasAttributes"); return false; } } /// <summary> /// See <see cref="System.Xml.XPath.XPathNavigator.HasChildren" /> for details. /// </summary> public override bool HasChildren { get { Trace("HasChildren"); return false; } } /// <summary> /// See <see cref="System.Xml.XPath.XPathNavigator.IsEmptyElement" /> for details. /// </summary> public override bool IsEmptyElement { get { Trace("IsEmptyElement"); return true; } } /// <summary> /// See <see cref="System.Xml.XPath.XPathNavigator.IsSamePosition" /> for details. /// </summary> public override bool IsSamePosition(System.Xml.XPath.XPathNavigator other) { Trace("IsSamePosition"); XPathObjectNavigator x = other as XPathObjectNavigator; if (null == x) { return false; } return _state.IsSamePosition(x._state); } /// <summary> /// See <see cref="System.Xml.XPath.XPathNavigator.LocalName" /> for details. /// </summary> public override string LocalName { get { Trace("get_LocalName"); return _state.Name; } } /// <summary> /// See <see cref="System.Xml.XPath.XPathNavigator.Name" /> for details. /// </summary> /// <remarks>Same as LocalName</remarks> public override string Name { get { Trace("get_Name"); return _state.Name; } } /// <summary> /// See <see cref="System.Xml.XPath.XPathNavigator.NamespaceURI" /> for details. /// </summary> /// <remarks>Always empty</remarks> public override string NamespaceURI { get { Trace("get_NamespaceURI"); return _context.NameTable.Get(string.Empty); } } /// <summary> /// See <see cref="System.Xml.XPath.XPathNavigator.NameTable" /> for details. /// </summary> public override System.Xml.XmlNameTable NameTable { get { Trace("get_NameTable"); return _context.NameTable; } } /// <summary> /// See <see cref="System.Xml.XPath.XPathNavigator.MoveTo" /> for details. /// </summary> public override bool MoveTo(System.Xml.XPath.XPathNavigator other) { Trace("MoveTo"); XPathObjectNavigator navigator = other as XPathObjectNavigator; if (null == other) { return false; } _state = navigator._state; _root = navigator._root; _context = navigator._context; return true; } /// <summary> /// See <see cref="System.Xml.XPath.XPathNavigator.MoveToAttribute" /> for details. /// </summary> public override bool MoveToAttribute(string localName, string namespaceURI) { Trace("MoveToAttribute"); return false; } /// <summary> /// See <see cref="System.Xml.XPath.XPathNavigator.MoveToFirst" /> for details. /// </summary> /// <remarks>Not supported.</remarks> public override bool MoveToFirst() { Trace("MoveToFirst"); return false; } /// <summary> /// See <see cref="System.Xml.XPath.XPathNavigator.MoveToFirstAttribute" /> for details. /// </summary> public override bool MoveToFirstAttribute() { Trace("MoveToFirstAttribute"); return false; } /// <summary> /// See <see cref="System.Xml.XPath.XPathNavigator.MoveToFirstChild" /> for details. /// </summary> public override bool MoveToFirstChild() { Trace("MoveToFirstChild"); ObjectNavigatorState newstate = _state.MoveToFirstChild(); if (null == newstate) { return false; } _state = newstate; return true; } /// <summary> /// See <see cref="System.Xml.XPath.XPathNavigator.MoveToFirstNamespace" /> for details. /// </summary> public override bool MoveToFirstNamespace(System.Xml.XPath.XPathNamespaceScope namespaceScope) { Trace("MoveToFirstNamespace"); return false; } /// <summary> /// See <see cref="System.Xml.XPath.XPathNavigator.MoveToId" /> for details. /// </summary> /// <remarks>Not supported.</remarks> public override bool MoveToId(string id) { Trace("MoveToId"); return false; } /// <summary> /// See <see cref="System.Xml.XPath.XPathNavigator.MoveToNamespace(string)" /> for details. /// </summary> public override bool MoveToNamespace(string name) { Trace("MoveToNamespace"); return false; } /// <summary> /// See <see cref="System.Xml.XPath.XPathNavigator.MoveToNext" /> for details. /// </summary> public override bool MoveToNext() { Trace("MoveToNext"); ObjectNavigatorState newstate = _state.MoveToNext(); if (null != newstate) { _state = newstate; return true; } return false; } /// <summary> /// See <see cref="System.Xml.XPath.XPathNavigator.MoveToNextAttribute" /> for details. /// </summary> public override bool MoveToNextAttribute() { Trace("MoveToNextAttribute"); return false; } /// <summary> /// See <see cref="System.Xml.XPath.XPathNavigator.MoveToNextNamespace" /> for details. /// </summary> public override bool MoveToNextNamespace(System.Xml.XPath.XPathNamespaceScope namespaceScope) { Trace("MoveToNextNamespace"); return false; } /// <summary> /// See <see cref="System.Xml.XPath.XPathNavigator.MoveToParent" /> for details. /// </summary> public override bool MoveToParent() { Trace("MoveToParent"); if (null != _state.Parent) { _state = _state.Parent; return true; } return false; } /// <summary> /// See <see cref="System.Xml.XPath.XPathNavigator.MoveToPrevious" /> for details. /// </summary> /// <remarks>Not supported.</remarks> public override bool MoveToPrevious() { Trace("MoveToPrevious"); return false; } /// <summary> /// See <see cref="System.Xml.XPath.XPathNavigator.MoveToRoot" /> for details. /// </summary> public override void MoveToRoot() { Trace("MoveToRoot"); _state = _root; } /// <summary> /// See <see cref="System.Xml.XPath.XPathNavigator.NodeType" /> for details. /// </summary> public override System.Xml.XPath.XPathNodeType NodeType { get { Trace("get_NodeType"); return _state.NodeType; } } /// <summary> /// See <see cref="System.Xml.XPath.XPathNavigator.Value" /> for details. /// </summary> public override string Value { get { Trace("get_Value"); return _state.Value; } } /// <summary> /// The current object. /// </summary> public object Node { get { return _state.Node; } } /// <summary> /// See <see cref="System.Xml.XPath.XPathNavigator.XmlLang" /> for details. /// </summary> public override string XmlLang { get { return _lang; } } /// <summary> /// See <see cref="System.Xml.XPath.XPathNavigator.Prefix" /> for details. /// </summary> /// <remarks>Always empty.</remarks> public override string Prefix { get { Trace("get_Prefix"); return _context.NameTable.Get(string.Empty); } } private void Trace(string format, params object[] args) { System.Diagnostics.Trace.WriteLine(string.Format(format, args)); } } } --- NEW FILE: TypeInfoCache.cs --- #region license // Bamboo.Prevalence - a .NET object prevalence engine // Copyright (C) 2004 Rodrigo B. de Oliveira // // Based on the original concept and implementation of Prevayler (TM) // by Klaus Wuestefeld. Visit http://www.prevayler.org for details. // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, // and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE // OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // Contact Information // // http://bbooprevalence.sourceforge.net // mailto:rod...@us... #endregion using System; using System.Collections; using System.Reflection; namespace Adapdev.XPath { public interface IValueProvider { string Name { get; } object GetValue(object instance); } public class PropertyInfoValueProvider : IValueProvider { PropertyInfo _pi; public PropertyInfoValueProvider(PropertyInfo pi) { _pi = pi; } public string Name { get { return _pi.Name; } } public object GetValue(object instance) { return _pi.GetValue(instance, (object[])null); } } public class FieldInfoValueProvider : IValueProvider { FieldInfo _fi; public FieldInfoValueProvider(FieldInfo fi) { _fi = fi; } public string Name { get { return _fi.Name; } } public object GetValue(object instance) { return _fi.GetValue(instance); } } /// <summary> /// A cache for the navigable properties of a type. /// </summary> public class TypeInfoCache { /// <summary> /// For types with no navigable properties (like primitives). /// </summary> public static IValueProvider[] EmptyValueProviderArray = new IValueProvider[0]; System.Collections.Hashtable _cache; /// <summary> /// Constructs an empty TypeInfoCache. /// </summary> public TypeInfoCache() { _cache = new System.Collections.Hashtable(); } /// <summary> /// Return the navigable properties for the object passed /// as argument. Any readable public property is considered /// navigable. /// </summary> /// <param name="o">object</param> /// <returns>array of navigable properties</returns> public IValueProvider[] GetNavigableProperties(object o) { IValueProvider[] properties = (IValueProvider[])_cache[o]; if (null == properties) { properties = FindNavigableProperties(o); _cache[o] = properties; } return properties; } private IValueProvider[] FindNavigableProperties(object o) { if (o.GetType().IsPrimitive) { return EmptyValueProviderArray; } ArrayList children = new ArrayList(); BindingFlags flags = BindingFlags.Instance | BindingFlags.Public; foreach (MemberInfo mi in o.GetType().FindMembers(MemberTypes.Property | MemberTypes.Field, flags, null, null)) { PropertyInfo pi = mi as PropertyInfo; if (null != pi) { if (pi.CanRead && 0 == pi.GetGetMethod().GetParameters().Length) { children.Add(new PropertyInfoValueProvider(pi)); } } else { children.Add(new FieldInfoValueProvider((FieldInfo)mi)); } } return (IValueProvider[])children.ToArray(typeof(IValueProvider)); } } } |
From: Sean M. <int...@us...> - 2005-11-16 05:33:39
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev/Commands In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv19977/src/Adapdev/Commands Added Files: ICommand.cs Log Message: Reposting to the repository after it got hosed --- NEW FILE: ICommand.cs --- using System; namespace Adapdev.Commands { /// <summary> /// Summary description for ICommand. /// </summary> public interface ICommand { void Execute(); } } |
From: Sean M. <int...@us...> - 2005-11-16 05:33:39
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev/UID In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv19977/src/Adapdev/UID Added Files: GuidUIDGenerator.cs TimeSpanUIDGenerator.cs UIDFactory.cs UIDGenerator.cs Log Message: Reposting to the repository after it got hosed --- NEW FILE: UIDFactory.cs --- #region Copyright / License Information /* Copyright 2004 - 2005 Adapdev Technologies, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ============================ Author Log ============================ III Full Name SMM Sean McCormack (Adapdev) ============================ Change Log ============================ III MMDDYY Change */ #endregion namespace Adapdev.UID { /// <summary> /// Summary description for UIDFactory. /// </summary> public class UIDFactory { private static UIDType t = UIDType.TimeSpan; private static string domain = "ABC"; private static bool showDomain = true; private UIDFactory() { } public static object GetNextId() { return GetNextId(t, showDomain); } public static object GetNextId(UIDType uidType) { return GetNextId(t, false); } public static object GetNextId(UIDType uidType, bool appendDomain) { object id; switch (uidType) { case UIDType.TimeSpan: id = TimeSpanUIDGenerator.GetInstance().GetNextId(); break; case UIDType.Guid: id = GuidUIDGenerator.GetInstance().GetNextId(); break; default: id = TimeSpanUIDGenerator.GetInstance().GetNextId(); break; } if (appendDomain) { id = domain + id; } return id; } public static UIDType Type { get { return UIDFactory.t; } set { UIDFactory.t = value; } } public static string Domain { get { return domain; } set { domain = value; } } public static bool AppendDomain { get { return showDomain; } set { showDomain = value; } } } public enum UIDType { TimeSpan, Guid } } --- NEW FILE: UIDGenerator.cs --- #region Copyright / License Information /* Copyright 2004 - 2005 Adapdev Technologies, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ============================ Author Log ============================ III Full Name SMM Sean McCormack (Adapdev) ============================ Change Log ============================ III MMDDYY Change */ #endregion namespace Adapdev.UID { /// <summary> /// Summary description for OIDGenerator. /// </summary> public abstract class UIDGenerator { protected UIDGenerator() { } public abstract object GetNextId(); } } --- NEW FILE: GuidUIDGenerator.cs --- #region Copyright / License Information /* Copyright 2004 - 2005 Adapdev Technologies, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ============================ Author Log ============================ III Full Name SMM Sean McCormack (Adapdev) ============================ Change Log ============================ III MMDDYY Change */ #endregion namespace Adapdev.UID { using System; /// <summary> /// Summary description for GuidUIDGenerator. /// </summary> public class GuidUIDGenerator : UIDGenerator { private static GuidUIDGenerator instance; private GuidUIDGenerator() : base() { } public static GuidUIDGenerator GetInstance() { if (instance == null) { instance = new GuidUIDGenerator(); } return instance; } public override object GetNextId() { return Guid.NewGuid(); } } } --- NEW FILE: TimeSpanUIDGenerator.cs --- #region Copyright / License Information /* Copyright 2004 - 2005 Adapdev Technologies, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ============================ Author Log ============================ III Full Name SMM Sean McCormack (Adapdev) ============================ Change Log ============================ III MMDDYY Change */ #endregion namespace Adapdev.UID { using System; /// <summary> /// Summary description for TimeSpanOIDGenerator. /// </summary> public class TimeSpanUIDGenerator : UIDGenerator { private static TimeSpanUIDGenerator instance; private long id = 0; private TimeSpanUIDGenerator() : base() { id = DateTime.Now.Ticks; } public static TimeSpanUIDGenerator GetInstance() { if (instance == null) { instance = new TimeSpanUIDGenerator(); } return instance; } public override object GetNextId() { return id++; } } } |
From: Sean M. <int...@us...> - 2005-11-16 05:33:38
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev/Threading In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv19977/src/Adapdev/Threading Added Files: CallerThreadContext.cs DelegateAdapter.cs Exceptions.cs STPStartInfo.cs SmartThreadPool.cs ThreadPoolWait.cs WorkItem.cs WorkItemsQueue.cs Log Message: Reposting to the repository after it got hosed --- NEW FILE: WorkItem.cs --- // Ami Bar // am...@gm... using System; using System.Threading; using System.Diagnostics; namespace Adapdev.Threading { #region WorkItem Delegate /// <summary> /// A delegate that represents the method to run as the work item /// </summary> /// <param name="state">A state object for the method to run</param> public delegate object WorkItemCallback(object state); /// <summary> /// A delegate to call after the WorkItemCallback completed /// </summary> /// <param name="wir">The work item result object</param> public delegate void PostExecuteWorkItemCallback(IWorkItemResult wir); #endregion #region IWorkItemResult interface /// <summary> /// IWorkItemResult interface /// </summary> public interface IWorkItemResult { /// <summary> /// Get the result of the work item. /// If the work item didn't run yet then the caller waits. /// </summary> /// <returns>The result of the work item</returns> object GetResult(); /// <summary> /// Get the result of the work item. /// If the work item didn't run yet then the caller waits until timeout. /// </summary> /// <returns>The result of the work item</returns> /// On timeout throws WorkItemTimeoutException object GetResult( int millisecondsTimeout, bool exitContext); /// <summary> /// Get the result of the work item. /// If the work item didn't run yet then the caller waits until timeout. /// </summary> /// <returns>The result of the work item</returns> /// On timeout throws WorkItemTimeoutException object GetResult( TimeSpan timeout, bool exitContext); /// <summary> /// Get the result of the work item. /// If the work item didn't run yet then the caller waits until timeout or until the cancelWaitHandle is signaled. /// </summary> /// <param name="millisecondsTimeout">Timeout in milliseconds, or -1 for infinite</param> /// <param name="exitContext"> /// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false. /// </param> /// <param name="cancelWaitHandle">A cancel wait handle to interrupt the blocking if needed</param> /// <returns>The result of the work item</returns> /// On timeout throws WorkItemTimeoutException /// On cancel throws WorkItemCancelException object GetResult( int millisecondsTimeout, bool exitContext, WaitHandle cancelWaitHandle); /// <summary> /// Get the result of the work item. /// If the work item didn't run yet then the caller waits until timeout or until the cancelWaitHandle is signaled. /// </summary> /// <returns>The result of the work item</returns> /// On timeout throws WorkItemTimeoutException /// On cancel throws WorkItemCancelException object GetResult( TimeSpan timeout, bool exitContext, WaitHandle cancelWaitHandle); /// <summary> /// Get the result of the work item. /// If the work item didn't run yet then the caller waits. /// </summary> /// <param name="e">Filled with the exception if one was thrown</param> /// <returns>The result of the work item</returns> object GetResult(out Exception e); /// <summary> /// Get the result of the work item. /// If the work item didn't run yet then the caller waits until timeout. /// </summary> /// <param name="e">Filled with the exception if one was thrown</param> /// <returns>The result of the work item</returns> /// On timeout throws WorkItemTimeoutException object GetResult( int millisecondsTimeout, bool exitContext, out Exception e); /// <summary> /// Get the result of the work item. /// If the work item didn't run yet then the caller waits until timeout. /// </summary> /// <param name="e">Filled with the exception if one was thrown</param> /// <returns>The result of the work item</returns> /// On timeout throws WorkItemTimeoutException object GetResult( TimeSpan timeout, bool exitContext, out Exception e); /// <summary> /// Get the result of the work item. /// If the work item didn't run yet then the caller waits until timeout or until the cancelWaitHandle is signaled. /// </summary> /// <param name="millisecondsTimeout">Timeout in milliseconds, or -1 for infinite</param> /// <param name="exitContext"> /// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false. /// </param> /// <param name="cancelWaitHandle">A cancel wait handle to interrupt the blocking if needed</param> /// <param name="e">Filled with the exception if one was thrown</param> /// <returns>The result of the work item</returns> /// On timeout throws WorkItemTimeoutException /// On cancel throws WorkItemCancelException object GetResult( int millisecondsTimeout, bool exitContext, WaitHandle cancelWaitHandle, out Exception e); /// <summary> /// Get the result of the work item. /// If the work item didn't run yet then the caller waits until timeout or until the cancelWaitHandle is signaled. /// </summary> /// <returns>The result of the work item</returns> /// <param name="e">Filled with the exception if one was thrown</param> /// On timeout throws WorkItemTimeoutException /// On cancel throws WorkItemCancelException object GetResult( TimeSpan timeout, bool exitContext, WaitHandle cancelWaitHandle, out Exception e); /// <summary> /// Gets an indication whether the asynchronous operation has completed. /// </summary> bool IsCompleted { get; } /// <summary> /// Gets an indication whether the asynchronous operation has been canceled. /// </summary> bool IsCanceled { get; } /// <summary> /// Gets a user-defined object that qualifies or contains information about an asynchronous operation. /// </summary> object State { get; } /// <summary> /// Cancel the work item if it didn't start running yet. /// </summary> /// <returns>Returns true on success or false if the work item is in progress or already completed</returns> bool Cancel(); } #endregion #region WorkItem class /// <summary> /// Holds a callback delegate and the state for that delegate. /// </summary> internal class WorkItem : IDisposable { #region WorkItemState enum /// <summary> /// Indicates the state of the work item in the thread pool /// </summary> private enum WorkItemState { InQueue, InProgress, Completed, Canceled, } #endregion #region Member Variables /// <summary> /// Callback delegate for the callback. /// </summary> private WorkItemCallback _callback; /// <summary> /// Callback delegate for the the post execute. /// </summary> private PostExecuteWorkItemCallback _postExecuteWorkItemCallback; /// <summary> /// State with which to call the callback delegate. /// </summary> private object _state; /// <summary> /// Stores the caller's context /// </summary> private CallerThreadContext _callerContext; /// <summary> /// Holds the result of the mehtod /// </summary> private object _result; /// <summary> /// Hold the exception if the method threw it /// </summary> private Exception _exception; /// <summary> /// Hold the state of the work item /// </summary> private WorkItemState _workItemState; /// <summary> /// A ManualResetEvent to indicate that the result is ready /// </summary> private ManualResetEvent _workItemCompleted; /// <summary> /// A reference count to the _workItemCompleted. /// When it reaches to zero _workItemCompleted is Closed /// </summary> private int _workItemCompletedRefCount; /// <summary> /// Represents the result state of the work item /// </summary> private WorkItemResult _workItemResult; /// <summary> /// Indicates when to call to the post execute /// </summary> private CallToPostExecute _callToPostExecute; #endregion #region Construction /// <summary> /// Initialize the callback holding object. /// </summary> /// <param name="callback">Callback delegate for the callback.</param> /// <param name="state">State with which to call the callback delegate.</param> /// /// We assume that the WorkItem object is created within the thread /// that meant to run the callback public WorkItem( WorkItemCallback callback, object state, bool useCallerContext, PostExecuteWorkItemCallback postExecuteWorkItemCallback, CallToPostExecute callToPostExecute) { if (useCallerContext) { _callerContext = CallerThreadContext.Capture(); } _postExecuteWorkItemCallback = postExecuteWorkItemCallback; _callToPostExecute = callToPostExecute; _callback = callback; _state = state; _workItemState = WorkItemState.InQueue; _workItemCompleted = null; _workItemCompletedRefCount = 0; _workItemResult = new WorkItemResult(this); } #endregion #region Methods /// <summary> /// Change the state of the work item to in progress if it wasn't canceled. /// </summary> /// <returns> /// Return true on success or false in case the work item was canceled. /// If the work item needs to run a post execute then the method will return true. /// </returns> public bool StartingWorkItem() { lock(this) { if (WorkItemState.Canceled == _workItemState) { bool result = false; if ((_postExecuteWorkItemCallback != null) && ((_callToPostExecute & CallToPostExecute.WhenWorkItemCanceled) == CallToPostExecute.WhenWorkItemCanceled)) { result = true; } return result; } Debug.Assert(WorkItemState.InQueue == _workItemState); SetWorkItemState(WorkItemState.InProgress); } return true; } /// <summary> /// Execute the work item and the post execute /// </summary> public void Execute() { CallToPostExecute currentCallToPostExecute = 0; // Execute the work item if we are in the correct state switch(_workItemState) { case WorkItemState.InProgress: currentCallToPostExecute |= CallToPostExecute.WhenWorkItemNotCanceled; ExecuteWorkItem(); break; case WorkItemState.Canceled: currentCallToPostExecute |= CallToPostExecute.WhenWorkItemCanceled; break; default: Debug.Assert(false); throw new NotSupportedException(); } // Run the post execute as needed if ((currentCallToPostExecute & _callToPostExecute) != 0) { PostExecute(); } } /// <summary> /// Execute the work item /// </summary> private void ExecuteWorkItem() { CallerThreadContext ctc = null; if (null != _callerContext) { ctc = CallerThreadContext.Capture(); CallerThreadContext.Apply(_callerContext); } Exception exception = null; object result = null; try { result = _callback(_state); } catch (Exception e) { // Save the exception so we can rethrow it later exception = e; } if (null != _callerContext) { CallerThreadContext.Apply(ctc); } SetResult(result, exception); } /// <summary> /// Runs the post execute callback /// </summary> private void PostExecute() { if (null != _postExecuteWorkItemCallback) { try { _postExecuteWorkItemCallback(this._workItemResult); } catch (Exception e) { Debug.Assert(null != e); } } } /// <summary> /// Set the result of the work item to return /// </summary> /// <param name="result">The result of the work item</param> internal void SetResult(object result, Exception exception) { _result = result; _exception = exception; SignalComplete(false); } /// <summary> /// Returns the work item result /// </summary> /// <returns>The work item result</returns> internal IWorkItemResult GetWorkItemResult() { return _workItemResult; } /// <summary> /// Wait for all work items to complete /// </summary> /// <param name="workItemResults">Array of work item result objects</param> /// <param name="millisecondsTimeout">The number of milliseconds to wait, or Timeout.Infinite (-1) to wait indefinitely.</param> /// <param name="exitContext"> /// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false. /// </param> /// <param name="cancelWaitHandle">A cancel wait handle to interrupt the wait if needed</param> /// <returns> /// true when every work item in workItemResults has completed; otherwise false. /// </returns> internal static bool WaitAll( IWorkItemResult [] workItemResults, int millisecondsTimeout, bool exitContext, WaitHandle cancelWaitHandle) { bool success; WaitHandle [] waitHandles = new WaitHandle[workItemResults.Length];; GetWaitHandles(workItemResults, waitHandles); if ((null == cancelWaitHandle) && (waitHandles.Length <= 64)) { success = WaitHandle.WaitAll(waitHandles, millisecondsTimeout, exitContext); } else { success = true; int millisecondsLeft = millisecondsTimeout; DateTime start = DateTime.Now; WaitHandle [] whs; if (null != cancelWaitHandle) { whs = new WaitHandle [] { null, cancelWaitHandle }; } else { whs = new WaitHandle [] { null }; } bool waitInfinitely = (Timeout.Infinite == millisecondsTimeout); // Iterate over the wait handles and wait for each one to complete. // We cannot use WaitHandle.WaitAll directly, because the cancelWaitHandle // won't affect it. // Each iteration we update the time left for the timeout. for(int i = 0; i < workItemResults.Length; ++i) { // WaitAny don't work with negative numbers if (!waitInfinitely && (millisecondsLeft < 0)) { success = false; break; } whs[0] = waitHandles[i]; int result = WaitHandle.WaitAny(whs, millisecondsLeft, exitContext); if((result > 0) || (WaitHandle.WaitTimeout == result)) { success = false; break; } if(!waitInfinitely) { // Update the time left to wait TimeSpan ts = DateTime.Now - start; millisecondsLeft = millisecondsTimeout - (int)ts.TotalMilliseconds; } } } // Release the wait handles ReleaseWaitHandles(workItemResults); return success; } /// <summary> /// Waits for any of the work items in the specified array to complete, cancel, or timeout /// </summary> /// <param name="workItemResults">Array of work item result objects</param> /// <param name="millisecondsTimeout">The number of milliseconds to wait, or Timeout.Infinite (-1) to wait indefinitely.</param> /// <param name="exitContext"> /// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false. /// </param> /// <param name="cancelWaitHandle">A cancel wait handle to interrupt the wait if needed</param> /// <returns> /// The array index of the work item result that satisfied the wait, or WaitTimeout if no work item result satisfied the wait and a time interval equivalent to millisecondsTimeout has passed or the work item has been canceled. /// </returns> internal static int WaitAny( IWorkItemResult [] workItemResults, int millisecondsTimeout, bool exitContext, WaitHandle cancelWaitHandle) { WaitHandle [] waitHandles = null; if (null != cancelWaitHandle) { waitHandles = new WaitHandle[workItemResults.Length+1]; GetWaitHandles(workItemResults, waitHandles); waitHandles[workItemResults.Length] = cancelWaitHandle; } else { waitHandles = new WaitHandle[workItemResults.Length]; GetWaitHandles(workItemResults, waitHandles); } int result = WaitHandle.WaitAny(waitHandles, millisecondsTimeout, exitContext); // Treat cancel as timeout if (null != cancelWaitHandle) { if (result == workItemResults.Length) { result = WaitHandle.WaitTimeout; } } ReleaseWaitHandles(workItemResults); return result; } /// <summary> /// Fill an array of wait handles with the work items wait handles. /// </summary> /// <param name="workItemResults">An array of work item results</param> /// <param name="waitHandles">An array of wait handles to fill</param> private static void GetWaitHandles( IWorkItemResult [] workItemResults, WaitHandle [] waitHandles) { for(int i = 0; i < workItemResults.Length; ++i) { WorkItemResult wir = workItemResults[i] as WorkItemResult; Debug.Assert(null != wir, "All workItemResults must be WorkItemResult objects"); waitHandles[i] = wir.GetWorkItem().GetWaitHandle(); } } /// <summary> /// Release the work items' wait handles /// </summary> /// <param name="workItemResults">An array of work item results</param> private static void ReleaseWaitHandles(IWorkItemResult [] workItemResults) { for(int i = 0; i < workItemResults.Length; ++i) { WorkItemResult wir = workItemResults[i] as WorkItemResult; wir.GetWorkItem().ReleaseWaitHandle(); } } #endregion #region Private Members /// <summary> /// Sets the work item's state /// </summary> /// <param name="workItemState">The state to set the work item to</param> private void SetWorkItemState(WorkItemState workItemState) { lock(this) { _workItemState = workItemState; } } /// <summary> /// Signals that work item has been completed or canceled /// </summary> /// <param name="canceled">Indicates that the work item has been canceled</param> private void SignalComplete(bool canceled) { SetWorkItemState(canceled ? WorkItemState.Canceled : WorkItemState.Completed); lock(this) { // If someone is waiting then signal. if (null != _workItemCompleted) { _workItemCompleted.Set(); } } } #endregion #region Members exposed by WorkItemResult /// <summary> /// Cancel the work item if it didn't start running yet. /// </summary> /// <returns>Returns true on success or false if the work item is in progress or already completed</returns> private bool Cancel() { lock(this) { switch(_workItemState) { case WorkItemState.Canceled: //Debug.WriteLine("Work item already canceled"); return true; case WorkItemState.Completed: case WorkItemState.InProgress: //Debug.WriteLine("Work item cannot be canceled"); return false; case WorkItemState.InQueue: // Signal to the wait for completion that the work // item has been completed (canceled). There is no // reason to wait for it to get out of the queue SignalComplete(true); //Debug.WriteLine("Work item canceled"); return true; } } return false; } /// <summary> /// Get the result of the work item. /// If the work item didn't run yet then the caller waits for the result, timeout, or cancel. /// In case of error the method throws and exception /// </summary> /// <returns>The result of the work item</returns> private object GetResult( int millisecondsTimeout, bool exitContext, WaitHandle cancelWaitHandle) { Exception e = null; object result = GetResult(millisecondsTimeout, exitContext, cancelWaitHandle, out e); if (null != e) { throw e; } return result; } /// <summary> /// Get the result of the work item. /// If the work item didn't run yet then the caller waits for the result, timeout, or cancel. /// In case of error the e argument is filled with the exception /// </summary> /// <returns>The result of the work item</returns> private object GetResult( int millisecondsTimeout, bool exitContext, WaitHandle cancelWaitHandle, out Exception e) { e = null; // Check for cancel if (WorkItemState.Canceled == _workItemState) { throw new WorkItemCancelException("Work item canceled"); } // Check for completion if (IsCompleted) { e = _exception; return _result; } // If no cancelWaitHandle is provided if (null == cancelWaitHandle) { WaitHandle wh = GetWaitHandle(); bool timeout = !wh.WaitOne(millisecondsTimeout, exitContext); ReleaseWaitHandle(); if (timeout) { throw new WorkItemTimeoutException("Work item timeout"); } } else { WaitHandle wh = GetWaitHandle(); int result = WaitHandle.WaitAny(new WaitHandle[] { wh, cancelWaitHandle }); ReleaseWaitHandle(); switch(result) { case 0: // The work item signaled // Note that the signal could be also as a result of canceling the // work item (not the get result) break; case 1: case WaitHandle.WaitTimeout: throw new WorkItemTimeoutException("Work item timeout"); default: Debug.Assert(false); break; } } // Check for cancel if (WorkItemState.Canceled == _workItemState) { throw new WorkItemCancelException("Work item canceled"); } Debug.Assert(IsCompleted); e = _exception; // Return the result return _result; } /// <summary> /// A wait handle to wait for completion, cancel, or timeout /// </summary> private WaitHandle GetWaitHandle() { lock(this) { if (null == _workItemCompleted) { _workItemCompleted = new ManualResetEvent(IsCompleted); } ++_workItemCompletedRefCount; } return _workItemCompleted; } private void ReleaseWaitHandle() { lock(this) { if (null != _workItemCompleted) { --_workItemCompletedRefCount; if (0 == _workItemCompletedRefCount) { _workItemCompleted.Close(); _workItemCompleted = null; } } } } /// <summary> /// Returns true when the work item has completed or canceled /// </summary> private bool IsCompleted { get { lock(this) { return ((_workItemState == WorkItemState.Completed) || (_workItemState == WorkItemState.Canceled)); } } } /// <summary> /// Returns true when the work item has canceled /// </summary> public bool IsCanceled { get { lock(this) { return (_workItemState == WorkItemState.Canceled); } } } #endregion #region WorkItemResult class private class WorkItemResult : IWorkItemResult { /// <summary> /// A back reference to the work item /// </summary> private WorkItem _workItem; public WorkItemResult(WorkItem workItem) { _workItem = workItem; } internal WorkItem GetWorkItem() { return _workItem; } #region IWorkItemResult Members public bool IsCompleted { get { return _workItem.IsCompleted; } } public bool IsCanceled { get { return _workItem.IsCanceled; } } public object GetResult() { return _workItem.GetResult(Timeout.Infinite, true, null); } public object GetResult(int millisecondsTimeout, bool exitContext) { return _workItem.GetResult(millisecondsTimeout, exitContext, null); } public object GetResult(TimeSpan timeout, bool exitContext) { return _workItem.GetResult((int)timeout.TotalMilliseconds, exitContext, null); } public object GetResult(int millisecondsTimeout, bool exitContext, WaitHandle cancelWaitHandle) { return _workItem.GetResult(millisecondsTimeout, exitContext, cancelWaitHandle); } public object GetResult(TimeSpan timeout, bool exitContext, WaitHandle cancelWaitHandle) { return _workItem.GetResult((int)timeout.TotalMilliseconds, exitContext, cancelWaitHandle); } public object GetResult(out Exception e) { return _workItem.GetResult(Timeout.Infinite, true, null, out e); } public object GetResult(int millisecondsTimeout, bool exitContext, out Exception e) { return _workItem.GetResult(millisecondsTimeout, exitContext, null, out e); } public object GetResult(TimeSpan timeout, bool exitContext, out Exception e) { return _workItem.GetResult((int)timeout.TotalMilliseconds, exitContext, null, out e); } public object GetResult(int millisecondsTimeout, bool exitContext, WaitHandle cancelWaitHandle, out Exception e) { return _workItem.GetResult(millisecondsTimeout, exitContext, cancelWaitHandle, out e); } public object GetResult(TimeSpan timeout, bool exitContext, WaitHandle cancelWaitHandle, out Exception e) { return _workItem.GetResult((int)timeout.TotalMilliseconds, exitContext, cancelWaitHandle, out e); } public bool Cancel() { return _workItem.Cancel(); } public object State { get { return _workItem._state; } } #endregion } #endregion #region IDisposable Members public void Dispose() { IDisposable disp = _state as IDisposable; if (null != disp) { disp.Dispose(); _state = null; } } #endregion } #endregion } --- NEW FILE: WorkItemsQueue.cs --- // Ami Bar // am...@gm... using System; using System.Collections; using System.Threading; namespace Adapdev.Threading { #region WorkItemsQueue class /// <summary> /// WorkItemsQueue class. /// </summary> internal class WorkItemsQueue : IDisposable { #region Member variables /// /// Waiters queue (implemented as stack). /// The head is a dummy and is not used. /// private WaiterEntry _headWaiterEntry = new WaiterEntry(); /// <summary> /// Waiters count /// </summary> private int _waitersCount = 0; /// <summary> /// Work items queue /// </summary> private Queue _workItems = new Queue(); /// <summary> /// Indicate that work items are allowed to be queued /// </summary> private bool _isWorkItemsQueueActive = true; /// <summary> /// A slot in the thread local storage to save some data /// </summary> private static readonly LocalDataStoreSlot _slot = Thread.AllocateDataSlot(); private bool _isDisposed = false; #endregion #region Public properties /// <summary> /// Returns the current number of work items in the queue /// </summary> public int Count { get { lock(this) { ValidateNotDisposed(); return _workItems.Count; } } } #endregion #region Public methods /// <summary> /// Enqueue a work item to the queue. /// </summary> public bool EnqueueWorkItem(WorkItem workItem) { // A work item cannot be null, since null is used in the // WaitForWorkItem() method to indicate timeout or cancel if (null == workItem) { throw new ArgumentNullException("workItem" , "workItem cannot be null"); } bool enqueue = true; // First check if there is a waiter waiting for work item. During // the check, timed out waiters are ignored. If there is no // waiter then the work item is queued. lock(this) { ValidateNotDisposed(); if (!_isWorkItemsQueueActive) { return false; } while(_waitersCount > 0) { // Dequeue a waiter. WaiterEntry waiterEntry = PopWaiter(); // Signal the waiter. On success break the loop if (waiterEntry.Signal(workItem)) { enqueue = false; break; } } if (enqueue) { // Enqueue the work item _workItems.Enqueue(workItem); } } return true; } /// <summary> /// Waits for a work item or exits on timeout or cancel /// </summary> /// <param name="millisecondsTimeout">Timeout in milliseconds</param> /// <param name="cancelEvent">Cancel wait handle</param> /// <returns>Returns true if the resource was granted</returns> public WorkItem DequeueWorkItem( int millisecondsTimeout, WaitHandle cancelEvent) { /// This method cause the caller to wait for a work item. /// If there is at least one waiting work item then the /// method returns immidiately with true. /// /// If there are no waiting work items then the caller /// is queued between other waiters for a work item to arrive. /// /// If a work item didn't come within millisecondsTimeout or /// the user canceled the wait by signaling the cancelEvent /// then the method returns false to indicate that the caller /// didn't get a work item. WaiterEntry waiterEntry = null; WorkItem workItem = null; lock(this) { ValidateNotDisposed(); // If there are waiting work items then take one and return. if (_workItems.Count > 0) { workItem = _workItems.Dequeue() as WorkItem; return workItem; } // No waiting work items ... else { // Get the wait entry for the waiters queue waiterEntry = GetThreadWaiterEntry(); // Put the waiter with the other waiters PushWaiter(waiterEntry); } } // Prepare array of wait handle for the WaitHandle.WaitAny() WaitHandle [] waitHandles = new WaitHandle [] { waiterEntry.WaitHandle, cancelEvent }; // Wait for an available resource, cancel event, or timeout. // During the wait we are supposes to exit the synchronization // domain. (Placing true as the third argument of the WaitAny()) // It just doesn't work, I don't know why, so I have lock(this) // statments insted of one. int index = WaitHandle.WaitAny( waitHandles, millisecondsTimeout, true); lock(this) { // success is true if it got a work item. bool success = (0 == index); // The timeout variable is used only for readability. // (We treat cancel as timeout) bool timeout = !success; // On timeout update the waiterEntry that it is timed out if (timeout) { // The Timeout() fails if the waiter has already been signaled timeout = waiterEntry.Timeout(); // On timeout remove the waiter from the queue. // Note that the complexity is O(1). if(timeout) { RemoveWaiter(waiterEntry, false); } // Again readability success = !timeout; } // On success return the work item if (success) { workItem = waiterEntry.WorkItem; if (null == workItem) { workItem = _workItems.Dequeue() as WorkItem; } } } // On failure return null. return workItem; } /// <summary> /// Cleanup the work items queue, hence no more work /// items are allowed to be queue /// </summary> protected virtual void Cleanup() { lock(this) { // Deactivate only once if (!_isWorkItemsQueueActive) { return; } // Don't queue more work items _isWorkItemsQueueActive = false; foreach(WorkItem workItem in _workItems) { workItem.Dispose(); } // Clear the work items that are already queued _workItems.Clear(); // Note: // I don't iterate over the queue and dispose of work items's states, // since if a work item has a state object that is still in use in the // application then I must not dispose it. // Tell the waiters that they were timed out. // It won't signal them to exit, but to ignore their // next work item. while(_waitersCount > 0) { WaiterEntry waiterEntry = PopWaiter(); waiterEntry.Timeout(); } } } #endregion #region Private methods /// <summary> /// Returns the WaiterEntry of the current thread /// </summary> /// <returns></returns> /// In order to avoid creation and destuction of WaiterEntry /// objects each thread stores its own WaiterEntry. private WaiterEntry GetThreadWaiterEntry() { WaiterEntry waiterEntry = Thread.GetData(_slot) as WaiterEntry; if (null == waiterEntry) { waiterEntry = new WaiterEntry(); Thread.SetData(_slot, waiterEntry); } waiterEntry.Reset(); return waiterEntry; } #region Waiters stack methods /// /// Push a new waiter into the waiter's stack /// /// A waiter to put in the stack private void PushWaiter(WaiterEntry newWaiterEntry) { // Remove the waiter if it is already in the stack and // update waiter's count as needed RemoveWaiter(newWaiterEntry, false); // If the stack is empty then newWaiterEntry is the new head of the stack if (null == _headWaiterEntry._nextWaiterEntry) { _headWaiterEntry._nextWaiterEntry = newWaiterEntry; newWaiterEntry._prevWaiterEntry = _headWaiterEntry; } // If the stack is not empty then put newWaiterEntry as the new head // of the stack. else { // Save the old first waiter entry WaiterEntry oldFirstWaiterEntry = _headWaiterEntry._nextWaiterEntry; // Update the links _headWaiterEntry._nextWaiterEntry = newWaiterEntry; newWaiterEntry._nextWaiterEntry = oldFirstWaiterEntry; newWaiterEntry._prevWaiterEntry = _headWaiterEntry; oldFirstWaiterEntry._prevWaiterEntry = newWaiterEntry; } // Increment the number of waiters ++_waitersCount; } /// /// Pop a waiter from the waiter's stack /// /// Returns the first waiter in the stack private WaiterEntry PopWaiter() { // Store the current stack head WaiterEntry oldFirstWaiterEntry = _headWaiterEntry._nextWaiterEntry; // Store the new stack head WaiterEntry newHeadWaiterEntry = oldFirstWaiterEntry._nextWaiterEntry; // Update the old stack head list links and decrement the number // waiters. RemoveWaiter(oldFirstWaiterEntry, true); // Update the new stack head _headWaiterEntry._nextWaiterEntry = newHeadWaiterEntry; if (null != newHeadWaiterEntry) { newHeadWaiterEntry._prevWaiterEntry = _headWaiterEntry; } // Return the old stack head return oldFirstWaiterEntry; } /// <summary> /// Remove a waiter from the stack /// </summary> /// <param name="waiterEntry">A waiter entry to remove</param> /// <param name="popDecrement">If true the waiter count is always decremented</param> private void RemoveWaiter(WaiterEntry waiterEntry, bool popDecrement) { // Store the prev entry in the list WaiterEntry prevWaiterEntry = waiterEntry._prevWaiterEntry; // Store the next entry in the list WaiterEntry nextWaiterEntry = waiterEntry._nextWaiterEntry; // A flag to indicate if we need to decrement the waiters count. // If we got here from PopWaiter then we must decrement. // If we got here from PushWaiter then we decrement only if // the waiter was already in the stack. bool decrementCounter = popDecrement; // Null the waiter's entry links waiterEntry._prevWaiterEntry = null; waiterEntry._nextWaiterEntry = null; // If the waiter entry had a prev link then update it. // It also means that the waiter is already in the list and we // need to decrement the waiters count. if (null != prevWaiterEntry) { prevWaiterEntry._nextWaiterEntry = nextWaiterEntry; decrementCounter = true; } // If the waiter entry had a next link then update it. // It also means that the waiter is already in the list and we // need to decrement the waiters count. if (null != nextWaiterEntry) { nextWaiterEntry._prevWaiterEntry = prevWaiterEntry; decrementCounter = true; } // Decrement the waiters count if needed if (decrementCounter) { --_waitersCount; } } #endregion #endregion #region WaiterEntry class // A waiter entry in the _waiters queue. private class WaiterEntry : IDisposable { #region Member variables /// <summary> /// Event to signal the waiter that it got the work item. /// </summary> private AutoResetEvent _waitHandle = new AutoResetEvent(false); /// <summary> /// Flag to know if this waiter already quited from the queue /// because of a timeout. /// </summary> private bool _isTimedout = false; /// <summary> /// Flag to know if the waiter was signaled and got a work item. /// </summary> private bool _isSignaled = false; /// <summary> /// A work item that passed directly to the waiter withou going /// through the queue /// </summary> private WorkItem _workItem = null; private bool _isDisposed = false; // Linked list members internal WaiterEntry _nextWaiterEntry = null; internal WaiterEntry _prevWaiterEntry = null; #endregion #region Construction public WaiterEntry() { Reset(); } #endregion #region Public methods public WaitHandle WaitHandle { get { return _waitHandle; } } public WorkItem WorkItem { get { lock(this) { return _workItem; } } } /// <summary> /// Signal the waiter that it got a work item. /// </summary> /// <returns>Return true on success</returns> /// The method fails if Timeout() preceded its call public bool Signal(WorkItem workItem) { lock(this) { if (!_isTimedout) { _workItem = workItem; _isSignaled = true; _waitHandle.Set(); return true; } } return false; } /// <summary> /// Mark the wait entry that it has been timed out /// </summary> /// <returns>Return true on success</returns> /// The method fails if Signal() preceded its call public bool Timeout() { lock(this) { // Time out can happen only if the waiter wasn't marked as // signaled if (!_isSignaled) { // We don't remove the waiter from the queue, the DequeueWorkItem // method skips _waiters that were timed out. _isTimedout = true; return true; } } return false; } /// <summary> /// Reset the wait entry so it can be used again /// </summary> public void Reset() { _workItem = null; _isTimedout = false; _isSignaled = false; _waitHandle.Reset(); } /// <summary> /// Free resources /// </summary> public void Close() { if (null != _waitHandle) { _waitHandle.Close(); _waitHandle = null; } } #endregion #region IDisposable Members public void Dispose() { if (!_isDisposed) { Close(); _isDisposed = true; } } ~WaiterEntry() { Dispose(); } #endregion } #endregion #region IDisposable Members public void Dispose() { if (!_isDisposed) { Cleanup(); _isDisposed = true; GC.SuppressFinalize(this); } } ~WorkItemsQueue() { Cleanup(); } private void ValidateNotDisposed() { if(_isDisposed) { throw new ObjectDisposedException(GetType().ToString(), "The SmartThreadPool has been shutdown"); } } #endregion } #endregion } --- NEW FILE: CallerThreadContext.cs --- // Ami Bar // am...@gm... using System; using System.Threading; using System.Globalization; using System.Security.Principal; using System.Reflection; using System.Runtime.Remoting.Contexts; namespace Adapdev.Threading { #region CallerThreadContext class /// <summary> /// This class stores the caller thread context in order to restore /// it when the work item is executed in the context of the thread /// from the pool. /// Note that we can't store the thread's CompressedStack, because /// it throws a security exception /// </summary> internal class CallerThreadContext { private CultureInfo _culture = null; private CultureInfo _cultureUI = null; private IPrincipal _principal; private System.Runtime.Remoting.Contexts.Context _context; private static FieldInfo _fieldInfo = GetFieldInfo(); private static FieldInfo GetFieldInfo() { Type threadType = typeof(Thread); return threadType.GetField( "m_Context", BindingFlags.Instance | BindingFlags.NonPublic); } /// <summary> /// Constructor /// </summary> private CallerThreadContext() { } /// <summary> /// Captures the current thread context /// </summary> /// <returns></returns> public static CallerThreadContext Capture() { CallerThreadContext callerThreadContext = new CallerThreadContext(); Thread thread = Thread.CurrentThread; callerThreadContext._culture = thread.CurrentCulture; callerThreadContext._cultureUI = thread.CurrentUICulture; callerThreadContext._principal = Thread.CurrentPrincipal; callerThreadContext._context = Thread.CurrentContext; return callerThreadContext; } /// <summary> /// Applies the thread context stored earlier /// </summary> /// <param name="callerThreadContext"></param> public static void Apply(CallerThreadContext callerThreadContext) { Thread thread = Thread.CurrentThread; thread.CurrentCulture = callerThreadContext._culture; thread.CurrentUICulture = callerThreadContext._cultureUI; Thread.CurrentPrincipal = callerThreadContext._principal; // Uncomment the following block to enable the Thread.CurrentThread /* if (null != _fieldInfo) { _fieldInfo.SetValue( Thread.CurrentThread, callerThreadContext._context); } */ } } #endregion } --- NEW FILE: DelegateAdapter.cs --- #region Original Copyright 2003 Richard Lowe /** Taken from the following blog: http://blogs.geekdojo.net/richard/archive/2003/12/19/492.aspx Usage: using System; using System.Collections; using System.Threading; using Timing; using DelegateAdapter; public class Program { // Create any method and a corresponding delegate: public delegate double WorkMethodHandler(double factor, string name); public static double WorkMethod(double factor, string name) { Console.WriteLine(name); return 3.14159 * factor; } public static void Main() { // Create the DelegateAdapter with the appropriate method and arguments: DelegateAdapter adapter = new DelegateAdapter(new WorkMethodHandler(WorkMethod), 3.123456789, "Richard"); // Automatically creates new ThreadStart and passes to the Thread constructor. // The adapter is implicitly convertible to a ThreadStart, which is why this works. Thread worker = new Thread(adapter); // change the arguments: adapter.Args = new object[] {9.14159d, "Roberto"}; // run it: worker.Start(); // wait to exit: worker.Join(); // get result: Console.WriteLine(adapter.ReturnValue); } } **/ #endregion #region Modified Copyright / License Information /* Copyright 2004 - 2005 Adapdev Technologies, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ============================ Author Log ============================ III Full Name SMM Sean McCormack (Adapdev) ============================ Change Log ============================ III MMDDYY Change */ #endregion namespace DelegateAdapter { using System; using System.Threading; /// <summary> /// Uses DynamicInvoke to allow any method to be easily mapped to the ThreadStart, WaitCallback or TimerCallback. /// </summary> public class DelegateAdapter { private object[] _args; public object[] Args { get { return _args; } set { _args = value; } } private Delegate _target; private object _returnValue; /// <summary> /// The return value, if any of the last execution of this DelegateAdapter's target method. /// </summary> public object ReturnValue { get { return _returnValue; } } /// <summary> /// Creates an instance of DelegateAdapter given any delegate. /// </summary> /// <param name="target">The delegate that will be invoked when one of the output delegates is invoked.</param> public DelegateAdapter(Delegate target) : this(target, null) { } /// <summary> /// Creates an instance of DelegateAdapter given any delegate and it's parameters to pass. /// </summary> /// <param name="target">The delegate that will be invoked when one of the output delegates is invoked.</param> /// <param name="args">The arguments that will be passed to the target delegate.</param> public DelegateAdapter(Delegate target, params object[] args) { _target = target; _args = args; } /// <summary> /// Dynamically invokes the target delegate with the provided arguments. /// </summary> public void Execute() { _returnValue = _target.DynamicInvoke(_args); } /// <summary> /// Dynamically invokes the target delegate with the state object provided by the caller. *Note* ignores any Args passed to the DelegateAdapter. /// </summary> /// <param name="state"></param> public void Execute(object state) { if (state is object[]) _returnValue = _target.DynamicInvoke(state as object[]); else _returnValue = _target.DynamicInvoke(new object[] {state}); } /// <summary> /// Creates a new, unique ThreadStart delegate for use with the Thread class. /// </summary> /// <returns>The new ThreadStart delegate</returns> public ThreadStart CreateThreadStart() { return new ThreadStart(Execute); } /// <summary> /// Creates a new, unique WaitCallback delegate for use with the ThreadPool class. /// </summary> /// <returns>The new WaitCallback delegate</returns> public WaitCallback CreateWaitCallback() { return new WaitCallback(Execute); } /// <summary> /// Creates a new, unique TimerCallback delegate for use with the Timer class. /// </summary> /// <returns>The new TimerCallback delegate</returns> public TimerCallback CreateTimerCallback() { return new TimerCallback(Execute); } public static implicit operator ThreadStart(DelegateAdapter adapter) { return adapter.CreateThreadStart(); } public static implicit operator WaitCallback(DelegateAdapter adapter) { return adapter.CreateWaitCallback(); } public static implicit operator TimerCallback(DelegateAdapter adapter) { return adapter.CreateTimerCallback(); } } } --- NEW FILE: STPStartInfo.cs --- // Ami Bar // am...@gm... using System; namespace Adapdev.Threading { /// <summary> /// Summary description for STPStartInfo. /// </summary> public class STPStartInfo { /// <summary> /// Idle timeout in milliseconds. /// If a thread is idle for _idleTimeout milliseconds then /// it may quit. /// </summary> private int _idleTimeout; /// <summary> /// The lower limit of threads in the pool. /// </summary> private int _minWorkerThreads; /// <summary> /// The upper limit of threads in the pool. /// </summary> private int _maxWorkerThreads; /// <summary> /// Use the caller's security context /// </summary> private bool _useCallerContext; /// <summary> /// Dispose of the state object of a work item /// </summary> private bool _disposeOfStateObjects; /// <summary> /// The option to run the post execute /// </summary> private CallToPostExecute _callToPostExecute; /// <summary> /// A post execute callback to call when none is provided in /// the QueueWorkItem method. /// </summary> private PostExecuteWorkItemCallback _postExecuteWorkItemCallback; public STPStartInfo() { _idleTimeout = SmartThreadPool.DefaultIdleTimeout; _minWorkerThreads = SmartThreadPool.DefaultMinWorkerThreads; _maxWorkerThreads = SmartThreadPool.DefaultMaxWorkerThreads; _useCallerContext = SmartThreadPool.DefaultUseCallerContext; _disposeOfStateObjects = SmartThreadPool.DefaultDisposeOfStateObjects; _callToPostExecute = SmartThreadPool.DefaultCallToPostExecute; _postExecuteWorkItemCallback = SmartThreadPool.DefaultPostExecuteWorkItemCallback; } public STPStartInfo(STPStartInfo stpStartInfo) { _idleTimeout = stpStartInfo._idleTimeout; _minWorkerThreads = stpStartInfo._minWorkerThreads; _maxWorkerThreads = stpStartInfo._maxWorkerThreads; _useCallerContext = stpStartInfo._useCallerContext; _disposeOfStateObjects = stpStartInfo._disposeOfStateObjects; _callToPostExecute = stpStartInfo._callToPostExecute; _postExecuteWorkItemCallback = stpStartInfo._postExecuteWorkItemCallback; } public int IdleTimeout { get { return _idleTimeout; } set { _idleTimeout = value; } } public int MinWorkerThreads { get { return _minWorkerThreads; } set { _minWorkerThreads = value; } } public int MaxWorkerThreads { get { return _maxWorkerThreads; } set { _maxWorkerThreads = value; } } public bool UseCallerContext { get { return _useCallerContext; } set { _useCallerContext = value; } } public bool DisposeOfStateObjects { get { return _disposeOfStateObjects; } set { _disposeOfStateObjects = value; } } public CallToPostExecute CallToPostExecute { get { return _callToPostExecute; } set { _callToPostExecute = value; } } public PostExecuteWorkItemCallback PostExecuteWorkItemCallback { get { return _postExecuteWorkItemCallback; } set { _postExecuteWorkItemCallback = value; } } } } --- NEW FILE: SmartThreadPool.cs --- // Ami Bar // am...@gm... // // Smart Thread Pool in C#. // 7 Aug 2004 - Initial release // 14 Sep 2004 - Bug fixes // 15 Oct 2004 - Added new features // - Work items return result. // - Support waiting synchronization for multiple work items. // - Work items can be cancelled. // - Passage of the caller threads context to the thread in the pool. // - Minimal usage of WIN32 handles. // - Minor bug fixes. // 26 Dec 2004 - Changes: // - Removed static constructors. // - Added finalizers. // - Changed Exceptions so they are serializable. // - Fixed the bug in one of the SmartThreadPool constructors. // - Changed the SmartThreadPool.WaitAll() so it will support any number of waiters. // The SmartThreadPool.WaitAny() is still limited by the .NET Framework. // - Added PostExecute with options on which cases to call it. // - Added option to dispose of the state objects. // - Added a WaitForIdle() method that waits until the work items queue is empty. // - Added an STPStartInfo class for the initialization of the thread pool. // - Changed exception handling so if a work item throws an exception it // is rethrown at GetResult(), rather then firing an UnhandledException event. // Note that PostExecute exception are always ignored. // 25 Mar 2005 - Fixed bug: // - Fixed bug where work items got lost. It could happen sometimes, but especially // when the idle timeout is small. // 3 Jul 2005 - Fixed bug: // - Fixed bug where Enqueue() throws an exception because PopWaiter() returned null, // hardly reconstructed // 16 Aug 2005 - Fixed bug: // - Fixed bug where the InUseThreads becomes negative when cancelling work items using System; using System.Security; using System.Threading; using System.Collections; using System.Diagnostics; namespace Adapdev.Threading { #region CallToPostExecute enumerator [Flags] public enum CallToPostExecute { Never = 0x00, WhenWorkItemCanceled = 0x01, WhenWorkItemNotCanceled = 0x02, Always = WhenWorkItemCanceled | WhenWorkItemNotCanceled, } #endregion #region SmartThreadPool class /// <summary> /// Smart thread pool class. /// </summary> public class SmartThreadPool : IDisposable { #region Default Constants /// <summary> /// Default minimum number of threads the thread pool contains. (0) /// </summary> public const int DefaultMinWorkerThreads = 0; /// <summary> /// Default maximum number of threads the thread pool contains. (25) /// </summary> public const int DefaultMaxWorkerThreads = 25; /// <summary> /// Default idle timeout in milliseconds. (One minute) /// </summary> public const int DefaultIdleTimeout = 60*1000; // One minute /// <summary> /// Indicate to copy the security context of the caller and then use it in the call. (false) /// </summary> public const bool DefaultUseCallerContext = false; /// <summary> /// Indicate to dispose of the state objects if they support the IDispose interface. (false) /// </summary> public const bool DefaultDisposeOfStateObjects = false; /// <summary> /// The default option to run the post execute /// </summary> public const CallToPostExecute DefaultCallToPostExecute = CallToPostExecute.Always; /// <summary> /// The default post execute method to run. /// When null it means not to call it. /// </summary> public static readonly PostExecuteWorkItemCallback DefaultPostExecuteWorkItemCallback = null; #endregion #region Member Variables /// <summary> /// Hashtable of all the threads in the thread pool. /// </summary> private Hashtable _workerThreads = Hashtable.Synchronized(new Hashtable()); /// <summary> /// Queue of work items. /// </summary> private WorkItemsQueue _workItemsQueue = new WorkItemsQueue(); /// <summary> /// Number of threads that currently work (not idle). /// </summary> private int _inUseWorkerThreads = 0; /// <summary> /// Start information to use. /// It is simpler than providing many constructors. /// </summary> private STPStartInfo _stpStartInfo = new STPStartInfo(); /// <summary> /// Total number of work items that are stored in the work items queue /// plus the work items that the threads in the pool are working on. /// </summary> private int _currentWorkItemsCount = 0; /// <summary> /// Signaled when the thread pool is idle, i.e. no thread is busy /// and the work items queue is empty /// </summary> private ManualResetEvent _isIdleWaitHandle = new ManualResetEvent(true); /// <summary> /// An event to signal all the threads to quit immediately. /// </summary> private ManualResetEvent _shuttingDownEvent = new ManualResetEvent(false); /// <summary> /// A flag to indicate the threads to quit. /// </summary> private bool _shutdown = false; /// <summary> /// Counts the threads created in the pool. /// It is used to name the threads. /// </summary> private int _threadCounter = 0; /// <summary> /// Indicate that the SmartThreadPool has been disposed /// </summary> private bool _isDisposed = false; #endregion #region Construction and Finalization /// <summary> /// Constructor /// </summary> public SmartThreadPool() { Start(); } /// <summary> /// Constructor /// </summary> /// <param name="idleTimeout">Idle timeout in milliseconds</param> public SmartThreadPool(int idleTimeout) { _stpStartInfo.IdleTimeout = idleTimeout; Start(); } /// <summary> /// Constructor /// </summary> /// <param name="idleTimeout">Idle timeout in milliseconds</param> /// <param name="maxWorkerThreads">Upper limit of threads in the pool</param> public SmartThreadPool( int idleTimeout, int maxWorkerThreads) { _stpStartInfo.IdleTimeout = idleTimeout; _stpStartInfo.MaxWorkerThreads = maxWorkerThreads; Start(); } /// <summary> /// Constructor /// </summary> /// <param name="idleTimeout">Idle timeout in milliseconds</param> /// <param name="maxWorkerThreads">Upper limit of threads in the pool</param> /// <param name="minWorkerThreads">Lower limit of threads in the pool</param> public SmartThreadPool( int idleTimeout, int maxWorkerThreads, int minWorkerThreads) { _stpStartInfo.IdleTimeout = idleTimeout; _stpStartInfo.MaxWorkerThreads = maxWorkerThreads; _stpStartInfo.MinWorkerThreads = minWorkerThreads; Start(); } /// <summary> /// Constructor /// </summary> /// <param name="idleTimeout">Idle timeout in milliseconds</param> /// <param name="maxWorkerThreads">Upper limit of threads in the pool</param> /// <param name="minWorkerThreads">Lower limit of threads in the pool</param> /// <param name="useCallerContext">Indicate to copy the security context of the caller and then use it in the call</param> /// <param name="disposeOfStateObjects">Indicate to dispose of the state objects if they support the IDispose interface</param> public SmartThreadPool(STPStartInfo stpStartInfo) { _stpStartInfo = new STPStartInfo(stpStartInfo); Start(); } private void Start() { ValidateSTPStartInfo(); StartThreads(_stpStartInfo.MinWorkerThreads); } private void ValidateSTPStartInfo() { if (_stpStartInfo.MinWorkerThreads < 0) { throw new ArgumentOutOfRangeException( "MinWorkerThreads", "MinWorkerThreads cannot be negative"); } if (_stpStartInfo.MaxWorkerThreads <= 0) { throw new ArgumentOutOfRangeException( "MaxWorkerThread... [truncated message content] |
From: Sean M. <int...@us...> - 2005-11-16 05:33:38
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev/Transactions In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv19977/src/Adapdev/Transactions Added Files: TransactionScope.cs Log Message: Reposting to the repository after it got hosed --- NEW FILE: TransactionScope.cs --- using System; using System.EnterpriseServices; namespace Adapdev.Transactions { /// <summary> /// Summary description for TransactionScope. /// </summary> public class TransactionScope : IDisposable { // Dispose must be called to exit the transactional block public void Dispose() { if(this.EnterSucceeded) { if(!this.Consistent && !this.HasAborted) { ContextUtil.SetAbort(); } ServiceDomain.Leave(); } } // by calling this method, you mark the scope as being consistent // and ready to for commit // if the method is never called, upon dispose, the scope will abort the transaction public void Complete() { this.Consistent = true; } public void Abort() { ContextUtil.SetAbort(); this.HasAborted = true; } public Guid TransactionId { get{return ContextUtil.TransactionId;} } public Guid ApplicationId { get{return ContextUtil.ApplicationId;} } public TransactionScope() { EnterTxContext(TransactionOption.Required); } public TransactionScope(TransactionOption txOption) { EnterTxContext(txOption); } private void EnterTxContext(TransactionOption txOption) { ServiceConfig config = new ServiceConfig(); config.Transaction = txOption; ServiceDomain.Enter(config); // Since Enter can throw, the next statement will track the success // In the case of success will we need to call Leave in Dispose this.EnterSucceeded = true; } // By default, the scope is inconsistent; // To Commit the transaction on exit, the Consistent flag // must be set to true before Dispose is called private bool Consistent = false; // Enter can throw, so we need to know if we need to call Leave in Dispose private bool EnterSucceeded = false; // Track whether it's been aborted private bool HasAborted = false; } } |
From: Sean M. <int...@us...> - 2005-11-16 05:33:38
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev/Serialization In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv19977/src/Adapdev/Serialization Added Files: Serializer.cs Log Message: Reposting to the repository after it got hosed --- NEW FILE: Serializer.cs --- #region Copyright / License Information /* Copyright 2004 - 2005 Adapdev Technologies, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ============================ Author Log ============================ III Full Name SMM Sean McCormack (Adapdev) ============================ Change Log ============================ III MMDDYY Change */ #endregion namespace Adapdev.Serialization { using System; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Runtime.Serialization.Formatters.Soap; using System.Text; using System.Xml.Serialization; /// <summary> /// Summary description for Serializer. /// </summary> /// public class Serializer { private Serializer() { } public static byte[] SerializeToBinary(object obj) { byte[] b = new byte[2500]; MemoryStream ms = new MemoryStream(); try { BinaryFormatter bformatter = new BinaryFormatter(); bformatter.Serialize(ms, obj); ms.Seek(0, 0); if (ms.Length > b.Length) b = new byte[ms.Length]; b = ms.ToArray(); } catch (SerializationException e) { Console.WriteLine("Failed to serialize. Reason: " + e.Message); throw; } finally { ms.Close(); } return b; } public static void SerializeToBinary(object obj, string path, FileMode mode) { FileStream fs = new FileStream(path, mode); // Construct a BinaryFormatter and use it to serialize the data to the stream. BinaryFormatter formatter = new BinaryFormatter(); try { formatter.Serialize(fs, obj); } catch (SerializationException e) { Console.WriteLine("Failed to serialize. Reason: " + e.Message); throw; } finally { fs.Close(); } } public static void SerializeToBinary(object obj, string path) { SerializeToBinary(obj, path, FileMode.Create); } public static string SerializeToSoap(object obj) { string s = ""; MemoryStream ms = new MemoryStream(); try { SoapFormatter sformatter = new SoapFormatter(); sformatter.Serialize(ms, obj); ms.Seek(0, 0); s = Encoding.ASCII.GetString(ms.ToArray()); } catch (SerializationException e) { Console.WriteLine("Failed to serialize. Reason: " + e.Message); throw; } finally { ms.Close(); } return s; } public static void SerializeToSoap(object obj, string path, FileMode mode) { FileStream fs = new FileStream(path, mode); // Construct a BinaryFormatter and use it to serialize the data to the stream. SoapFormatter formatter = new SoapFormatter(); try { formatter.Serialize(fs, obj); } catch (SerializationException e) { Console.WriteLine("Failed to serialize. Reason: " + e.Message); throw; } finally { fs.Close(); } } public static void SerializeToSoap(object obj, string path) { SerializeToSoap(obj, path, FileMode.Create); } public static string SerializeToXml(object obj) { string s = ""; MemoryStream ms = new MemoryStream(); try { XmlSerializer serializer = new XmlSerializer(obj.GetType()); serializer.Serialize(ms, obj); ms.Seek(0, 0); s = Encoding.ASCII.GetString(ms.ToArray()); } catch (SerializationException e) { Console.WriteLine("Failed to serialize. Reason: " + e.Message); throw; } finally { ms.Close(); } return s; } public static void SerializeToXmlFile(object obj, string path, FileMode mode) { FileStream fs = new FileStream(path, mode); // Construct a BinaryFormatter and use it to serialize the data to the stream. XmlSerializer serializer = new XmlSerializer(obj.GetType()); try { serializer.Serialize(fs, obj); } catch (SerializationException e) { Console.WriteLine("Failed to serialize. Reason: " + e.Message); throw; } finally { fs.Close(); } } public static void SerializeToXmlFile(object obj, string path) { SerializeToXmlFile(obj, path, FileMode.Create); } public static object DeserializeFromXmlFile(Type type, string path) { object o = new object(); FileStream fs = new FileStream(path, FileMode.Open); try { XmlSerializer serializer = new XmlSerializer(type); o = serializer.Deserialize(fs); } catch (SerializationException e) { Console.WriteLine("Failed to deserialize. Reason: " + e.Message); throw; } finally { fs.Close(); } return o; } public static object DeserializeFromXml(Type type, string s) { object o = new object(); try { XmlSerializer serializer = new XmlSerializer(type); o = serializer.Deserialize(new StringReader(s)); } catch (SerializationException e) { Console.WriteLine("Failed to deserialize. Reason: " + e.Message); throw; } finally { } return o; } public static object DeserializeFromSoap(Type type, string s) { object o = new object(); MemoryStream ms = new MemoryStream(new UTF8Encoding().GetBytes(s)); try { SoapFormatter serializer = new SoapFormatter(); o = serializer.Deserialize(ms); } catch (SerializationException e) { Console.WriteLine("Failed to deserialize. Reason: " + e.Message); throw; } finally { } return o; } public static object DeserializeFromBinary(Type type, byte[] bytes) { object o = new object(); MemoryStream ms = new MemoryStream(bytes); try { BinaryFormatter serializer = new BinaryFormatter(); o = serializer.Deserialize(ms); } catch (SerializationException e) { Console.WriteLine("Failed to deserialize. Reason: " + e.Message); throw; } finally { } return o; } public static object DeserializeFromBinary(Type type, string path) { object o = new object(); FileStream fs = new FileStream(path, FileMode.Open); try { BinaryFormatter serializer = new BinaryFormatter(); o = serializer.Deserialize(fs); } catch (SerializationException e) { Console.WriteLine("Failed to deserialize. Reason: " + e.Message); throw; } finally { fs.Close(); } return o; } public static long GetByteSize(object o) { BinaryFormatter bFormatter = new BinaryFormatter(); MemoryStream stream = new MemoryStream(); bFormatter.Serialize(stream, o); return stream.Length; } public static object Clone(object o) { BinaryFormatter bFormatter = new BinaryFormatter(); MemoryStream stream = new MemoryStream(); object cloned = null; try { bFormatter.Serialize(stream, o); stream.Seek(0, SeekOrigin.Begin); cloned = bFormatter.Deserialize(stream); } catch (Exception e) { } finally { stream.Close(); } return cloned; } } } |
From: Sean M. <int...@us...> - 2005-11-16 05:33:38
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev/Text In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv19977/src/Adapdev/Text Added Files: StringUtil.cs Log Message: Reposting to the repository after it got hosed --- NEW FILE: StringUtil.cs --- #region Copyright / License Information /* Copyright 2004 - 2005 Adapdev Technologies, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ============================ Author Log ============================ III Full Name SMM Sean McCormack (Adapdev) ============================ Change Log ============================ III MMDDYY Change */ #endregion namespace Adapdev.Text { using System; using System.Collections; using System.Reflection; using System.Text; using Microsoft.VisualBasic; /// <summary> /// Summary description for TextHelper. /// </summary> public class StringUtil { private StringUtil() { } public static string RemoveFinalChar(string s) { if (s.Length > 1) { s = s.Substring(0, s.Length - 1); } return s; } public static string RemoveFinalComma(string s) { if (s.Trim().Length > 0) { int c = s.LastIndexOf(","); if (c > 0) { s = s.Substring(0, s.Length - (s.Length - c)); } } return s; } public static string RemoveSpaces(string s) { s = s.Trim(); s = s.Replace(" ", ""); return s; } public static string ToProperCase(string s) { string revised = ""; if (s.Length > 0) { if (s.IndexOf(" ") > 0) { revised = Strings.StrConv(s, VbStrConv.ProperCase, 1033); } else { string firstLetter = s.Substring(0, 1).ToUpper(new System.Globalization.CultureInfo("en-US")); revised = firstLetter + s.Substring(1, s.Length - 1); } } return revised; } public static string ToTrimmedProperCase(string s) { return RemoveSpaces(ToProperCase(s)); } public static string ToString(Object o) { StringBuilder sb = new StringBuilder(); Type t = o.GetType(); PropertyInfo[] pi = t.GetProperties(); sb.Append("Properties for: " + o.GetType().Name + Environment.NewLine); foreach (PropertyInfo i in pi) { try { sb.Append("\t" + i.Name + "(" + i.PropertyType.ToString() + "): "); if (null != i.GetValue(o, null)) { sb.Append(i.GetValue(o, null).ToString()); } } catch { } sb.Append(Environment.NewLine); } FieldInfo[] fi = t.GetFields(); foreach (FieldInfo i in fi) { try { sb.Append("\t" + i.Name + "(" + i.FieldType.ToString() + "): "); if (null != i.GetValue(o)) { sb.Append(i.GetValue(o).ToString()); } } catch { } sb.Append(Environment.NewLine); } return sb.ToString(); } public static ArrayList ExtractInnerContent(string content, string start, string end) { int sindex = -1, eindex = -1; int msindex = -1, meindex = -1; int span = 0; ArrayList al = new ArrayList(); sindex = content.IndexOf(start); msindex = sindex + start.Length; eindex = content.IndexOf(end,msindex); span = eindex - msindex; if(sindex >= 0 && eindex > sindex) { al.Add(content.Substring(msindex, span)); } while(sindex >= 0 && eindex > 0) { sindex = content.IndexOf(start, eindex); if(sindex > 0) { eindex = content.IndexOf(end, sindex); msindex = sindex + start.Length; span = eindex - msindex; if(msindex > 0 && eindex > 0) { al.Add(content.Substring(msindex, span)); } } } return al; } public static ArrayList ExtractOuterContent(string content, string start, string end) { int sindex = -1, eindex = -1; ArrayList al = new ArrayList(); sindex = content.IndexOf(start); eindex = content.IndexOf(end); if(sindex >= 0 && eindex > sindex) { al.Add(content.Substring(sindex, eindex + end.Length - sindex)); } while(sindex >= 0 && eindex > 0) { sindex = content.IndexOf(start, eindex); if(sindex > 0) { eindex = content.IndexOf(end, sindex); if(sindex > 0 && eindex > 0) { al.Add(content.Substring(sindex, eindex + end.Length - sindex)); } } } return al; } } } |
From: Sean M. <int...@us...> - 2005-11-16 05:33:38
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.Data/Mappings In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv19977/src/Adapdev.Data/Mappings Added Files: ProviderInfo.cs Log Message: Reposting to the repository after it got hosed --- NEW FILE: ProviderInfo.cs --- namespace Adapdev.Data.Mappings { /// <summary> /// Represents the provider specific information for a database column type /// </summary> public class ProviderInfo { /// <summary> /// The numeric provider-specific id /// </summary> public string Id; /// <summary> /// The provider-specific name /// </summary> public string Name; /// <summary> /// The object equivalent for the provider-specific type /// </summary> public string Object; /// <summary> /// The prefix for data /// </summary> public string Prefix; /// <summary> /// The postfix for data /// </summary> public string Postfix; /// <summary> /// The default value /// </summary> public string Default; /// <summary> /// The test default value /// </summary> public string TestDefault; } } |
From: Sean M. <int...@us...> - 2005-11-16 05:33:38
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev/Mock In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv19977/src/Adapdev/Mock Added Files: SuppliersEntity.cs Log Message: Reposting to the repository after it got hosed --- NEW FILE: SuppliersEntity.cs --- /****************************************** * Auto-generated by Codus * 4/20/2005 11:18:21 AM ******************************************/ using System; using Adapdev.Text; namespace Adapdev.Mock { /// <summary> /// An object representation of the Northwind Suppliers table /// </summary> /// [Serializable] public class SuppliersEntity{ private System.String _Address = ""; private System.String _City = ""; private System.String _CompanyName = ""; private System.String _ContactName = ""; private System.String _ContactTitle = ""; private System.String _Country = ""; private System.String _Fax = ""; private System.String _HomePage = ""; private System.String _Phone = ""; private System.String _PostalCode = ""; private System.String _Region = ""; private System.Int32 _SupplierID = 0; private System.DateTime _Created = DateTime.Now; public System.DateTime InternalCreated = DateTime.Now; public System.String Address { get { return this._Address; } set { this._Address = value; } } public System.String City { get { return this._City; } set { this._City = value; } } public System.String CompanyName { get { return this._CompanyName; } set { this._CompanyName = value; } } public System.String ContactName { get { return this._ContactName; } set { this._ContactName = value; } } public System.String ContactTitle { get { return this._ContactTitle; } set { this._ContactTitle = value; } } public System.String Country { get { return this._Country; } set { this._Country = value; } } public System.String Fax { get { return this._Fax; } set { this._Fax = value; } } public System.String HomePage { get { return this._HomePage; } set { this._HomePage = value; } } public System.String Phone { get { return this._Phone; } set { this._Phone = value; } } public System.String PostalCode { get { return this._PostalCode; } set { this._PostalCode = value; } } public System.String Region { get { return this._Region; } set { this._Region = value; } } public System.Int32 SupplierID { get { return this._SupplierID; } set { this._SupplierID = value; } } public DateTime Created { get{return this._Created;} set{this._Created = value;} } /// <summary> /// Returns a string representation of the object, displaying all property and field names and values. /// </summary> public override string ToString() { return StringUtil.ToString(this); } } } |