adapdev-commits Mailing List for Adapdev.NET (Page 8)
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/Scheduling/Timer In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv11264/src/Adapdev/Scheduling/Timer Added Files: EventStorage.cs MethodCall.cs ReportTimer.cs Schedule.cs ScheduleFilter.cs ScheduleTimer.cs ScheduledItems.cs TimerJob.cs Log Message: --- 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/Scheduling/Task In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv11264/src/Adapdev/Scheduling/Task Added Files: ScheduledTasks.cs Scheduler.cs Task.cs TaskList.cs TaskSchedulerInterop.cs Trigger.cs TriggerList.cs Log Message: --- NEW FILE: Task.cs --- // Original Copyright (c) 2004 Dennis Austin. http://www.codeproject.com/csharp/tsnewlib.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.IO; using System.Runtime.InteropServices; using System.Runtime.Serialization.Formatters.Binary; namespace Adapdev.Scheduling.Task { #region Enums /// <summary> /// Options for a task, used for the Flags property of a Task. Uses the /// "Flags" attribute, so these values are combined with |. /// Some flags are documented as Windows 95 only, but they have a /// user interface in Windows XP so that may not be true. /// </summary> [Flags] public enum TaskFlags { /// <summary> /// The precise meaning of this flag is elusive. The MSDN documentation describes it /// only for use in converting jobs from the Windows NT "AT" service to the newer /// Task Scheduler. No other use for the flag is documented. /// </summary> Interactive = 0x1, /// <summary> /// The task will be deleted when there are no more scheduled run times. /// </summary> DeleteWhenDone = 0x2, /// <summary> /// The task is disabled. Used to temporarily prevent a task from being triggered normally. /// </summary> Disabled = 0x4, /// <summary> /// The task begins only if the computer is idle at the scheduled start time. /// The computer is not considered idle until the task's <see cref="Task.IdleWaitMinutes"/> time /// elapses with no user input. /// </summary> StartOnlyIfIdle = 0x10, /// <summary> /// The task terminates if the computer makes an idle to non-idle transition while the task is running. /// For information regarding idle triggers, see <see cref="OnIdleTrigger"/>. /// </summary> KillOnIdleEnd = 0x20, /// <summary> /// The task does not start if the computer is running on battery power. /// </summary> DontStartIfOnBatteries = 0x40, /// <summary> /// The task ends, and the associated application quits if the computer switches /// to battery power. /// </summary> KillIfGoingOnBatteries = 0x80, /// <summary> /// The task runs only if the system is docked. /// (Not mentioned in current MSDN documentation; probably obsolete.) /// </summary> RunOnlyIfDocked = 0x100, /// <summary> /// The task item is hidden. /// /// This is implemented by setting the job file's hidden attribute. Testing revealed that clearing /// this flag doesn't clear the file attribute, so the library sets the file attribute directly. This /// flag is kept in sync with the task's Hidden property, so they function equivalently. /// </summary> Hidden = 0x200, /// <summary> /// The task runs only if there is currently a valid Internet connection. /// Not currently implemented. (Check current MSDN documentation for updates.) /// </summary> RunIfConnectedToInternet = 0x400, /// <summary> /// The task starts again if the computer makes a non-idle to idle transition before all the /// task's task_triggers elapse. (Use this flag in conjunction with KillOnIdleEnd.) /// </summary> RestartOnIdleResume = 0x800, /// <summary> /// Wake the computer to run this task. Seems to be misnamed, but the name is taken from /// the low-level interface. /// /// </summary> SystemRequired = 0x1000, /// <summary> /// The task runs only if the user specified in SetAccountInformation() is /// logged on interactively. This flag has no effect on tasks set to run in /// the local SYSTEM account. /// </summary> RunOnlyIfLoggedOn = 0x2000 } /// <summary> /// Status values returned for a task. Some values have been determined to occur although /// they do no appear in the Task Scheduler system documentation. /// </summary> public enum TaskStatus { /// <summary> /// The task is ready to run at its next scheduled time. /// </summary> Ready = HResult.SCHED_S_TASK_READY, /// <summary> /// The task is currently running. /// </summary> Running = HResult.SCHED_S_TASK_RUNNING, /// <summary> /// One or more of the properties that are needed to run this task on a schedule have not been set. /// </summary> NotScheduled = HResult.SCHED_S_TASK_NOT_SCHEDULED, /// <summary> /// The task has not yet run. /// </summary> NeverRun = HResult.SCHED_S_TASK_HAS_NOT_RUN, /// <summary> /// The task will not run at the scheduled times because it has been disabled. /// </summary> Disabled = HResult.SCHED_S_TASK_DISABLED, /// <summary> /// There are no more runs scheduled for this task. /// </summary> NoMoreRuns = HResult.SCHED_S_TASK_NO_MORE_RUNS, /// <summary> /// The last run of the task was terminated by the user. /// </summary> Terminated = HResult.SCHED_S_TASK_TERMINATED, /// <summary> /// Either the task has no triggers or the existing triggers are disabled or not set. /// </summary> NoTriggers = HResult.SCHED_S_TASK_NO_VALID_TRIGGERS, /// <summary> /// Event triggers don't have set run times. /// </summary> NoTriggerTime = HResult.SCHED_S_EVENT_TRIGGER } #endregion /// <summary> /// Represents an item in the Scheduled Tasks folder. There are no public constructors for Task. /// New instances are generated by a <see cref="ScheduledTasks"/> object using Open or Create methods. /// A task object holds COM interfaces; call its <see cref="Close"/> method to release them. /// </summary> public class Task : IDisposable { #region Fields /// <summary> /// Internal COM interface /// </summary> private ITask iTask; /// <summary> /// Name of this task (with no .job extension) /// </summary> private string name; /// <summary> /// List of triggers for this task /// </summary> private TriggerList triggers; #endregion #region Constructors /// <summary> /// Internal constructor for a task, used by <see cref="ScheduledTasks"/>. /// </summary> /// <param name="iTask">Instance of an ITask.</param> /// <param name="taskName">Name of the task.</param> internal Task(ITask iTask, string taskName) { this.iTask = iTask; if (taskName.EndsWith(".job")) name = taskName.Substring(0, taskName.Length-4); else name = taskName; triggers = null; this.Hidden = GetHiddenFileAttr(); } #endregion #region Properties /// <summary> /// Gets the name of the task. The name is also the filename (plus a .job extension) /// the Task Scheduler uses to store the task information. To change the name of a /// task, use <see cref="Save()"/> to save it as a new name and then delete /// the old task. /// </summary> public string Name { get { return name; } } /// <summary> /// Gets the list of triggers associated with the task. /// </summary> public TriggerList Triggers { get { if (triggers == null) { // Trigger list has not been requested before; create it triggers = new TriggerList(iTask); } return triggers; } } /// <summary> /// Gets/sets the application filename that task is to run. Get returns /// an absolute pathname. A name searched with the PATH environment variable can /// be assigned, and the path search is done when the task is saved. /// </summary> public string ApplicationName { get { IntPtr lpwstr; iTask.GetApplicationName(out lpwstr); return CoTaskMem.LPWStrToString(lpwstr); } set { iTask.SetApplicationName(value); } } /// <summary> /// Gets the name of the account under which the task process will run. /// </summary> public string AccountName { get { IntPtr lpwstr = IntPtr.Zero; iTask.GetAccountInformation(out lpwstr); return CoTaskMem.LPWStrToString(lpwstr); } } /// <summary> /// Gets/sets the comment associated with the task. The comment appears in the /// Scheduled Tasks user interface. /// </summary> public string Comment { get { IntPtr lpwstr; iTask.GetComment(out lpwstr); return CoTaskMem.LPWStrToString(lpwstr); } set { iTask.SetComment(value); } } /// <summary> /// Gets/sets the creator of the task. If no value is supplied, the system /// fills in the account name of the caller when the task is saved. /// </summary> public string Creator { get { IntPtr lpwstr; iTask.GetCreator(out lpwstr); return CoTaskMem.LPWStrToString(lpwstr); } set { iTask.SetCreator(value); } } /// <summary> /// Gets/sets the number of times to retry task execution after failure. (Not implemented.) /// </summary> private short ErrorRetryCount { get { ushort ret; iTask.GetErrorRetryCount(out ret); return (short)ret; } set { iTask.SetErrorRetryCount((ushort)value); } } /// <summary> /// Gets/sets the time interval, in minutes, to delay between error retries. (Not implemented.) /// </summary> private short ErrorRetryInterval { get { ushort ret; iTask.GetErrorRetryInterval(out ret); return (short)ret; } set { iTask.SetErrorRetryInterval((ushort)value); } } /// <summary> /// Gets the Win32 exit code from the last execution of the task. If the task failed /// to start on its last run, the reason is returned as an exception. Not updated while /// in an open task; the property does not change unless the task is closed and re-opened. /// <exception>Various exceptions for a task that couldn't be run.</exception> /// </summary> public int ExitCode { get { uint ret = 0; iTask.GetExitCode(out ret); return (int)ret; } } /// <summary> /// Gets/sets the <see cref="TaskFlags"/> associated with the current task. /// </summary> public TaskFlags Flags { get { uint ret; iTask.GetFlags(out ret); return (TaskFlags)ret; } set { iTask.SetFlags((uint)value); } } /// <summary> /// Gets/sets how long the system must remain idle, even after the trigger /// would normally fire, before the task will run. /// </summary> public short IdleWaitMinutes { get { ushort ret, nothing; iTask.GetIdleWait(out ret, out nothing); return (short)ret; } set { ushort m = (ushort)IdleWaitDeadlineMinutes; iTask.SetIdleWait((ushort)value, m); } } /// <summary> /// Gets/sets the maximum number of minutes that Task Scheduler will wait for a /// required idle period to occur. /// </summary> public short IdleWaitDeadlineMinutes { get { ushort ret, nothing; iTask.GetIdleWait(out nothing, out ret); return (short)ret; } set { ushort m = (ushort)IdleWaitMinutes; iTask.SetIdleWait(m, (ushort)value); } } /// <summary> /// <p>Gets/sets the maximum length of time the task is permitted to run. /// Setting MaxRunTime also affects the value of <see cref="Task.MaxRunTimeLimited"/>. /// </p> /// <p>The longest MaxRunTime implemented is 0xFFFFFFFE milliseconds, or /// about 50 days. If you set a TimeSpan longer than that, the /// MaxRunTime will be unlimited.</p> /// </summary> /// <Remarks> /// </Remarks> public TimeSpan MaxRunTime { get { uint ret; iTask.GetMaxRunTime(out ret); return new TimeSpan((long)ret * TimeSpan.TicksPerMillisecond); } set { double proposed = ((TimeSpan)value).TotalMilliseconds; if (proposed >= uint.MaxValue) { iTask.SetMaxRunTime(uint.MaxValue); } else { iTask.SetMaxRunTime((uint)proposed); } //iTask.SetMaxRunTime((uint)((TimeSpan)value).TotalMilliseconds); } } /// <summary> /// <p>If the maximum run time is limited, the task will be terminated after /// <see cref="Task.MaxRunTime"/> expires. Setting the value to FALSE, i.e. unlimited, /// invalidates MaxRunTime.</p> /// <p>The Task Scheduler service will try to send a WM_CLOSE message when it needs to terminate /// a task. If the message can't be sent, or the task does not respond with three minutes, /// the task will be terminated using TerminateProcess.</p> /// </summary> public bool MaxRunTimeLimited { get { uint ret; iTask.GetMaxRunTime(out ret); return (ret == uint.MaxValue); } set { if (value) { uint ret; iTask.GetMaxRunTime(out ret); if (ret == uint.MaxValue) { iTask.SetMaxRunTime(72*360*1000); //72 hours. Thats what Explorer sets. } } else { iTask.SetMaxRunTime(uint.MaxValue); } } } /// <summary> /// Gets the most recent time the task began running. <see cref="DateTime.MinValue"/> /// returned if the task has not run. /// </summary> public DateTime MostRecentRunTime { get { SystemTime st = new SystemTime(); iTask.GetMostRecentRunTime(ref st); if (st.Year == 0) return DateTime.MinValue; return new DateTime((int)st.Year, (int)st.Month, (int)st.Day, (int)st.Hour, (int)st.Minute, (int)st.Second, (int)st.Milliseconds); } } /// <summary> /// Gets the next time the task will run. Returns <see cref="DateTime.MinValue"/> /// if the task is not scheduled to run. /// </summary> public DateTime NextRunTime { get { SystemTime st = new SystemTime(); iTask.GetNextRunTime(ref st); if (st.Year == 0) return DateTime.MinValue; return new DateTime((int)st.Year, (int)st.Month, (int)st.Day, (int)st.Hour, (int)st.Minute, (int)st.Second, (int)st.Milliseconds); } } /// <summary> /// Gets/sets the command-line parameters for the task. /// </summary> public string Parameters { get { IntPtr lpwstr; iTask.GetParameters(out lpwstr); return CoTaskMem.LPWStrToString(lpwstr); } set { iTask.SetParameters(value); } } /// <summary> /// Gets/sets the priority for the task process. /// Note: ProcessPriorityClass defines two levels (AboveNormal and BelowNormal) that are /// not documented in the task scheduler interface and can't be use on Win 98 platforms. /// </summary> public System.Diagnostics.ProcessPriorityClass Priority { get { uint ret; iTask.GetPriority(out ret); return (System.Diagnostics.ProcessPriorityClass)ret; } set { if (value==System.Diagnostics.ProcessPriorityClass.AboveNormal || value==System.Diagnostics.ProcessPriorityClass.BelowNormal ) { throw new ArgumentException("Unsupported Priority Level"); } iTask.SetPriority((uint)value); } } /// <summary> /// Gets the status of the task. Returns <see cref="TaskStatus"/>. /// Not updated while a task is open. /// </summary> public TaskStatus Status { get { int ret; iTask.GetStatus(out ret); return (TaskStatus)ret; } } /// <summary> /// Extended Flags associated with a task. These are associated with the ITask com interface /// and none are currently defined. /// </summary> private int FlagsEx { get { uint ret; iTask.GetTaskFlags(out ret); return (int)ret; } set { iTask.SetTaskFlags((uint)value); } } /// <summary> /// Gets/sets the initial working directory for the task. /// </summary> public string WorkingDirectory { get { IntPtr lpwstr; iTask.GetWorkingDirectory(out lpwstr); return CoTaskMem.LPWStrToString(lpwstr); } set { iTask.SetWorkingDirectory(value); } } /// <summary> /// Hidden tasks are stored in files with /// the hidden file attribute so they don't appear in the Explorer user interface. /// Because there is a special interface for Scheduled Tasks, they don't appear /// even if Explorer is set to show hidden files. /// Functionally equivalent to TaskFlags.Hidden. /// </summary> public bool Hidden { get { return (this.Flags & TaskFlags.Hidden) != 0; } set { if (value) { this.Flags |= TaskFlags.Hidden; } else { this.Flags &= ~TaskFlags.Hidden; } } } /// <summary> /// Gets/sets arbitrary data associated with the task. The tag can be used for any purpose /// by the client, and is not used by the Task Scheduler. Known as WorkItemData in the /// IWorkItem com interface. /// </summary> public object Tag { get { ushort DataLen; IntPtr Data; iTask.GetWorkItemData(out DataLen, out Data); byte[] bytes = new byte[DataLen]; Marshal.Copy(Data, bytes, 0, DataLen); MemoryStream stream = new MemoryStream(bytes, false); BinaryFormatter b = new BinaryFormatter(); return b.Deserialize(stream); } set { if (!value.GetType().IsSerializable) throw new ArgumentException("Objects set as Data for Tasks must be serializable", "value"); BinaryFormatter b = new BinaryFormatter(); MemoryStream stream = new MemoryStream(); b.Serialize(stream, value); iTask.SetWorkItemData((ushort)stream.Length, stream.GetBuffer()); } } #endregion #region Methods /// <summary> /// Set the hidden attribute on the file corresponding to this task. /// </summary> /// <param name="set">Set the attribute accordingly.</param> private void SetHiddenFileAttr(bool set) { UCOMIPersistFile iFile = (UCOMIPersistFile)iTask; string fileName; iFile.GetCurFile(out fileName); System.IO.FileAttributes attr; attr = System.IO.File.GetAttributes(fileName); if (set) attr |= System.IO.FileAttributes.Hidden; else attr &= ~System.IO.FileAttributes.Hidden; System.IO.File.SetAttributes(fileName, attr); } /// <summary> /// Get the hidden attribute from the file corresponding to this task. /// </summary> /// <returns>The value of the attribute.</returns> private bool GetHiddenFileAttr() { UCOMIPersistFile iFile = (UCOMIPersistFile)iTask; string fileName; iFile.GetCurFile(out fileName); System.IO.FileAttributes attr; try { attr = System.IO.File.GetAttributes(fileName); return (attr & System.IO.FileAttributes.Hidden) != 0; } catch { return false; } } /// <summary> /// Calculate the next time the task would be scheduled /// to run after a given arbitrary time. If the task will not run /// (perhaps disabled) then returns <see cref="DateTime.MinValue"/>. /// </summary> /// <param name="after">The time to calculate from.</param> /// <returns>The next time the task would run.</returns> public DateTime NextRunTimeAfter(DateTime after) { //Add one second to get a run time strictly greater than the specified time. after = after.AddSeconds(1); //Convert to a valid SystemTime SystemTime stAfter = new SystemTime(); stAfter.Year = (ushort)after.Year; stAfter.Month = (ushort)after.Month; stAfter.Day = (ushort)after.Day; stAfter.DayOfWeek = (ushort)after.DayOfWeek; stAfter.Hour = (ushort)after.Hour; stAfter.Minute = (ushort)after.Minute; stAfter.Second = (ushort)after.Second; SystemTime stLimit = new SystemTime(); // Would like to pass null as the second parameter to GetRunTimes, indicating that // the interval is unlimited. Can't figure out how to do that, so use a big time value. stLimit = stAfter; stLimit.Year = (ushort)DateTime.MaxValue.Year; IntPtr pTimes; ushort nFetch = 1; iTask.GetRunTimes(ref stAfter, ref stLimit, ref nFetch, out pTimes); if (nFetch == 1) { SystemTime stNext = new SystemTime(); stNext = (SystemTime)Marshal.PtrToStructure(pTimes, typeof(SystemTime)); Marshal.FreeCoTaskMem(pTimes); return new DateTime(stNext.Year, stNext.Month, stNext.Day, stNext.Hour, stNext.Minute, stNext.Second); } else { return DateTime.MinValue; } } /// <summary> /// Schedules the task for immediate execution. /// The system works from the saved version of the task, so call <see cref="Save()"/> before running. /// If the task has never been saved, it throws an argument exception. Problems starting /// the task are reported by the <see cref="ExitCode"/> property, not by exceptions on Run. /// </summary> /// <remarks>The system never updates an open task, so you don't get current results for /// the <see cref="Status"/> or the <see cref="ExitCode"/> properties until you close /// and reopen the task. /// </remarks> /// <exception cref="ArgumentException"></exception> public void Run() { iTask.Run(); } /// <summary> /// Saves changes to the established task name. /// </summary> /// <overloads>Saves changes that have been made to this Task.</overloads> /// <remarks>The account name is checked for validity /// when a Task is saved. The password is not checked, but the account name /// must be valid (or empty). /// </remarks> /// <exception cref="COMException">Unable to establish existence of the account specified.</exception> public void Save() { UCOMIPersistFile iFile = (UCOMIPersistFile)iTask; iFile.Save(null, false); SetHiddenFileAttr(Hidden); //Do the Task Scheduler's work for it because it doesn't reset properly } /// <summary> /// Saves the Task with a new name. The task with the old name continues to /// exist in whatever state it was last saved. It is no longer open, because. /// the Task object is associated with the new name from now on. /// If there is already a task using the new name, it is overwritten. /// </summary> /// <remarks>See the <see cref="Save()"/>() overload.</remarks> /// <param name="name">The new name to be used for this task.</param> /// <exception cref="COMException">Unable to establish existence of the account specified.</exception> public void Save(string name) { UCOMIPersistFile iFile = (UCOMIPersistFile)iTask; string path; iFile.GetCurFile(out path); string newPath; newPath = Path.GetDirectoryName(path) + Path.DirectorySeparatorChar + name + Path.GetExtension(path); iFile.Save(newPath, true); iFile.SaveCompleted(newPath); /* probably unnecessary */ this.name = name; SetHiddenFileAttr(Hidden); //Do the Task Scheduler's work for it because it doesn't reset properly } /// <summary> /// Release COM interfaces for this Task. After a Task is closed, accessing its /// members throws a null reference exception. /// </summary> public void Close() { if (triggers != null) { triggers.Dispose(); } Marshal.ReleaseComObject(iTask); iTask = null; } /// <summary> /// For compatibility with earlier versions. New clients should use <see cref="DisplayPropertySheet()"/>. /// </summary> /// <remarks> /// Display the property pages of this task for user editing. If the user clicks OK, the /// task's properties are updated and the task is also automatically saved. /// </remarks> public void DisplayForEdit() { iTask.EditWorkItem(0, 0); } /// <summary> /// Argument for DisplayForEdit to determine which property pages to display. /// </summary> [Flags] public enum PropPages { /// <summary> /// The task property page /// </summary> Task = 0x01, /// <summary> /// The schedule property page /// </summary> Schedule = 0x02, /// <summary> /// The setting property page /// </summary> Settings = 0x04 } /// /// <summary> /// Display all property pages. /// </summary> /// <remarks> /// The method does not return until the user has dismissed the dialog box. /// If the dialog box is dismissed with the OK button, returns true and /// updates properties in the task. /// The changes are not made permanent, however, until the task is saved. (Save() method.) /// </remarks> /// <returns><c>true</c> if dialog box was dismissed with OK, otherwise <c>false</c>.</returns> /// <overloads>Display the property pages of this task for user editing.</overloads> public bool DisplayPropertySheet() { //iTask.EditWorkItem(0, 0); //This implementation saves automatically, so we don't use it. return DisplayPropertySheet(PropPages.Task | PropPages.Schedule | PropPages.Settings); } /// <summary> /// Display only the specified property pages. /// </summary> /// <remarks> /// See the <see cref="DisplayPropertySheet()"/>() overload. /// </remarks> /// <param name="pages">Controls which pages are presented</param> /// <returns><c>true</c> if dialog box was dismissed with OK, otherwise <c>false</c>.</returns> public bool DisplayPropertySheet(PropPages pages) { PropSheetHeader hdr = new PropSheetHeader(); IProvideTaskPage iProvideTaskPage = (IProvideTaskPage)iTask; IntPtr[] hPages = new IntPtr[3]; IntPtr hPage; int nPages = 0; if ((pages & PropPages.Task) != 0) { //get task page iProvideTaskPage.GetPage(0, false, out hPage); hPages[nPages++] = hPage; } if ((pages & PropPages.Schedule) != 0) { //get task page iProvideTaskPage.GetPage(1, false, out hPage); hPages[nPages++] = hPage; } if ((pages & PropPages.Settings) != 0) { //get task page iProvideTaskPage.GetPage(2, false, out hPage); hPages[nPages++] = hPage; } if (nPages == 0) throw (new ArgumentException("No Property Pages to display")); hdr.dwSize = (uint)Marshal.SizeOf(hdr); hdr.dwFlags = (uint) (PropSheetFlags.PSH_DEFAULT | PropSheetFlags.PSH_NOAPPLYNOW); hdr.pszCaption = this.Name; hdr.nPages = (uint)nPages; GCHandle gch = GCHandle.Alloc(hPages, GCHandleType.Pinned); hdr.phpage = gch.AddrOfPinnedObject(); int res = PropertySheetDisplay.PropertySheet(ref hdr); gch.Free(); if (res < 0) throw (new Exception("Property Sheet failed to display")); return res>0; } /// <summary> /// Sets the account under which the task will run. Supply the account name and /// password as parameters. For the localsystem account, pass an empty string for /// the account name and null for the password. See Remarks. /// </summary> /// <param name="accountName">Full account name.</param> /// <param name="password">Password for the account.</param> /// <remarks> /// <p>To have the task to run under the local system account, pass the empty string ("") /// as accountName and null as the password. The caller must be running in /// an administrator account or in the local system account. /// </p> /// <p> /// You can also specify a null password if the task has the flag RunOnlyIfLoggedOn set. /// This allows you to schedule a task for an account for which you don't know the password, /// but the account must be logged on interactively at the time the task runs.</p> /// </remarks> public void SetAccountInformation(string accountName, string password) { iTask.SetAccountInformation(accountName, password); } /// <summary> /// Request that the task be terminated if it is currently running. The call returns /// immediately, although the task may continue briefly. For Windows programs, a WM_CLOSE /// message is sent first and the task is given three minutes to shut down voluntarily. /// Should it not, or if the task is not a Windows program, TerminateProcess is used. /// </summary> /// <exception cref="COMException">The task is not running.</exception> public void Terminate() { iTask.Terminate(); } /// <summary> /// Overridden. Outputs the name of the task, the application and parameters. /// </summary> /// <returns>String representing task.</returns> public override string ToString() { return string.Format("{0} (\"{1}\" {2})", name, ApplicationName, Parameters); } #endregion #region Implementation of IDisposable /// <summary> /// A synonym for Close. /// </summary> public void Dispose() { this.Close(); } #endregion } } --- NEW FILE: ScheduledTasks.cs --- // Original Copyright (c) 2004 Dennis Austin. http://www.codeproject.com/csharp/tsnewlib.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.IO; using System.Runtime.InteropServices; namespace Adapdev.Scheduling.Task { /// <summary> /// ScheduledTasks represents the a computer's Scheduled Tasks folder. Using a ScheduledTasks /// object, you can discover the names of the tasks in the folder and you can open a task /// to work with it. You can also create or delete tasks. /// </summary> /// <remarks> /// A ScheduledTasks object holds a COM interface that can be released by calling <see cref="Dispose()"/>. /// </remarks> public class ScheduledTasks : IDisposable { /// <summary> /// Underlying COM interface. /// </summary> private ITaskScheduler its = null; // --- Contructors --- /// <summary> /// Constructor to use Scheduled tasks of a remote computer identified by a UNC /// name. The calling process must have administrative privileges on the remote machine. /// May throw exception if the computer's task scheduler cannot be reached, and may /// give strange results if the argument is not in UNC format. /// </summary> /// <param name="computer">The remote computer's UNC name, e.g. "\\DALLAS".</param> /// <exception cref="ArgumentException">The Task Scheduler could not be accessed.</exception> public ScheduledTasks(string computer) : this() { its.SetTargetComputer(computer); } /// <summary> /// Constructor to use Scheduled Tasks of the local computer. /// </summary> public ScheduledTasks() { CTaskScheduler cts = new CTaskScheduler(); its = (ITaskScheduler)cts; } // --- Methods --- private string[] GrowStringArray(string[] s, uint n) { string[] sl = new string[s.Length + n]; for (int i=0; i<s.Length; i++) { sl[i] = s[i];} return sl; } /// <summary> /// Return the names of all scheduled tasks. The names returned include the file extension ".job"; /// methods requiring a task name can take the name with or without the extension. /// </summary> /// <returns>The names in a string array.</returns> public string[] GetTaskNames() { const int TASKS_TO_FETCH = 10; string[] taskNames = {}; int nTaskNames = 0; IEnumWorkItems ienum; its.Enum(out ienum); uint nFetchedTasks; IntPtr pNames; while ( ienum.Next( TASKS_TO_FETCH, out pNames, out nFetchedTasks ) >= 0 && nFetchedTasks > 0 ) { taskNames = GrowStringArray(taskNames, nFetchedTasks); while ( nFetchedTasks > 0 ) { IntPtr name = Marshal.ReadIntPtr( pNames, (int)--nFetchedTasks * IntPtr.Size ); taskNames[nTaskNames++] = Marshal.PtrToStringUni(name); Marshal.FreeCoTaskMem(name); } Marshal.FreeCoTaskMem( pNames ); } return taskNames; } /// <summary> /// Creates a new task on the system with the given <paramref name="name" />. /// </summary> /// <remarks>Task names follow normal filename character restrictions. The name /// will be come the name of the file used to store the task (with .job added).</remarks> /// <param name="name">Name for the new task.</param> /// <returns>Instance of new task.</returns> /// <exception cref="ArgumentException">There is an existing task with the given name.</exception> public Task CreateTask(string name) { Task tester = OpenTask(name); if (tester != null) { tester.Close(); throw new ArgumentException("The task \"" + name + "\" already exists."); } try { object o; its.NewWorkItem(name, ref CTaskGuid, ref ITaskGuid, out o); ITask iTask = (ITask)o; return new Task(iTask, name); } catch { return null; } } /// <summary> /// Deletes the task of the given <paramref name="name" />. /// </summary> /// <remarks>If you delete a task that is open, a subsequent save will throw an /// exception. You can save to a filename, however, to create a new task.</remarks> /// <param name="name">Name of task to delete.</param> /// <returns>True if the task was deleted, false if the task wasn't found.</returns> public bool DeleteTask(string name) { try { its.Delete(name); return true; } catch { return false; } } /// <summary> /// Opens the task with the given <paramref name="name" />. An open task holds COM interfaces /// which are released by the Task's Close() method. /// </summary> /// <remarks>If the task does not exist, null is returned.</remarks> /// <param name="name">Name of task to open.</param> /// <returns>An instance of a Task, or null if the task name couldn't be found.</returns> public Task OpenTask(string name) { try { object o; its.Activate(name, ref ITaskGuid, out o); ITask iTask = (ITask)o; return new Task(iTask, name); } catch { return null; } } #region Implementation of IDisposable /// <summary> /// The internal COM interface is released. Further access to the /// object will throw null reference exceptions. /// </summary> public void Dispose() { Marshal.ReleaseComObject(its); its = null; } #endregion // Two Guids for calls to ITaskScheduler methods Activate(), NewWorkItem(), and IsOfType() internal static Guid ITaskGuid; internal static Guid CTaskGuid; static ScheduledTasks() { ITaskGuid = Marshal.GenerateGuidForType(typeof(ITask)); CTaskGuid = Marshal.GenerateGuidForType(typeof(CTask)); } } } --- NEW FILE: Trigger.cs --- // Original Copyright (c) 2004 Dennis Austin. http://www.codeproject.com/csharp/tsnewlib.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.Runtime.InteropServices; namespace Adapdev.Scheduling.Task { #region Enums /// <summary> /// Valid types of triggers /// </summary> internal enum TriggerType { /// <summary> /// Trigger is set to run the task a single time. /// </summary> RunOnce = 0, /// <summary> /// Trigger is set to run the task on a daily interval. /// </summary> RunDaily = 1, /// <summary> /// Trigger is set to run the work item on specific days of a specific week of a specific month. /// </summary> RunWeekly = 2, /// <summary> /// Trigger is set to run the task on a specific day(s) of the month. /// </summary> RunMonthly = 3, /// <summary> /// Trigger is set to run the task on specific days, weeks, and months. /// </summary> RunMonthlyDOW = 4, /// <summary> /// Trigger is set to run the task if the system remains idle for the amount of time specified by the idle wait time of the task. /// </summary> OnIdle = 5, /// <summary> /// Trigger is set to run the task at system startup. /// </summary> OnSystemStart = 6, /// <summary> /// Trigger is set to run the task when a user logs on. /// </summary> OnLogon = 7 } /// <summary> /// Values for days of the week (Monday, Tuesday, etc.) These carry the Flags /// attribute so DaysOfTheWeek and be combined with | (or). /// </summary> [Flags] public enum DaysOfTheWeek : short { /// <summary> /// Sunday /// </summary> Sunday = 0x1, /// <summary> /// Monday /// </summary> Monday = 0x2, /// <summary> /// Tuesday /// </summary> Tuesday = 0x4, /// <summary> /// Wednesday /// </summary> Wednesday = 0x8, /// <summary> /// Thursday /// </summary> Thursday = 0x10, /// <summary> /// Friday /// </summary> Friday = 0x20, /// <summary> /// Saturday /// </summary> Saturday = 0x40 } /// <summary> /// Values for week of month (first, second, ..., last) /// </summary> public enum WhichWeek : short { /// <summary> /// First week of the month /// </summary> FirstWeek = 1, /// <summary> /// Second week of the month /// </summary> SecondWeek = 2, /// <summary> /// Third week of the month /// </summary> ThirdWeek = 3, /// <summary> /// Fourth week of the month /// </summary> FourthWeek = 4, /// <summary> /// Last week of the month /// </summary> LastWeek = 5 } /// <summary> /// Values for months of the year (January, February, etc.) These carry the Flags /// attribute so DaysOfTheWeek and be combined with | (or). /// </summary> [Flags] public enum MonthsOfTheYear : short { /// <summary> /// January /// </summary> January = 0x1, /// <summary> /// February /// </summary> February = 0x2, /// <summary> /// March /// </summary> March = 0x4, /// <summary> /// April /// </summary> April = 0x8, /// <summary> ///May /// </summary> May = 0x10, /// <summary> /// June /// </summary> June = 0x20, /// <summary> /// July /// </summary> July = 0x40, /// <summary> /// August /// </summary> August = 0x80, /// <summary> /// September /// </summary> September = 0x100, /// <summary> /// October /// </summary> October = 0x200, /// <summary> /// November /// </summary> November = 0x400, /// <summary> /// December /// </summary> December = 0x800 } #endregion /// <summary> /// Trigger is a generalization of all the concrete trigger classes, and any actual /// Trigger object is one of those types. When included in the TriggerList of a /// Task, a Trigger determines when a scheduled task will be run. /// </summary> /// <remarks> /// <para> /// Create a concrete trigger for a specific start condition and then call TriggerList.Add /// to include it in a task's TriggerList.</para> /// <para> /// A Trigger that is not yet in a Task's TriggerList is said to be unbound and it holds /// no resources (i.e. COM interfaces). Once it is added to a TriggerList, it is bound and /// holds a COM interface that is only released when the Trigger is removed from the list or /// the corresponding Task is closed.</para> /// <para> /// A Trigger that is already bound cannot be added to a TriggerList. To copy a Trigger from /// one list to another, use <see cref="Clone()"/> to create an unbound copy and then add the /// copy to the new list. To move a Trigger from one list to another, use <see cref="TriggerList.Remove"/> /// to extract the Trigger from the first list before adding it to the second.</para> /// </remarks> public abstract class Trigger : ICloneable { #region Enums /// <summary> /// Flags for triggers /// </summary> [Flags] private enum TaskTriggerFlags { HasEndDate = 0x1, KillAtDurationEnd = 0x2, Disabled = 0x4 } #endregion #region Fields private ITaskTrigger iTaskTrigger; //null for an unbound Trigger internal TaskTrigger taskTrigger; #endregion #region Constructors and Initializers /// <summary> /// Internal base constructor for an unbound Trigger. /// </summary> internal Trigger() { iTaskTrigger = null; taskTrigger = new TaskTrigger(); taskTrigger.TriggerSize = (ushort)Marshal.SizeOf(taskTrigger); taskTrigger.BeginYear = (ushort)DateTime.Today.Year; taskTrigger.BeginMonth = (ushort)DateTime.Today.Month; taskTrigger.BeginDay = (ushort)DateTime.Today.Day; } /// <summary> /// Internal constructor which initializes itself from /// from an ITaskTrigger interface. /// </summary> /// <param name="iTrigger">Instance of ITaskTrigger from system task scheduler.</param> internal Trigger(ITaskTrigger iTrigger) { if (iTrigger == null) throw new ArgumentNullException("iTrigger", "ITaskTrigger instance cannot be null"); taskTrigger = new TaskTrigger(); taskTrigger.TriggerSize = (ushort)Marshal.SizeOf(taskTrigger); iTrigger.GetTrigger(ref taskTrigger); iTaskTrigger = iTrigger; } #endregion #region Implement ICloneable /// <summary> /// Clone returns an unbound copy of the Trigger object. It can be use /// on either bound or unbound original. /// </summary> /// <returns></returns> public object Clone() { Trigger newTrigger = (Trigger)this.MemberwiseClone(); newTrigger.iTaskTrigger = null; // The clone is not bound return newTrigger; } #endregion #region Properties /// <summary> /// Get whether the Trigger is currently bound /// </summary> internal bool Bound { get { return iTaskTrigger != null; } } /// <summary> /// Gets/sets the beginning year, month, and day for the trigger. /// </summary> public DateTime BeginDate { get { return new DateTime(taskTrigger.BeginYear, taskTrigger.BeginMonth, taskTrigger.BeginDay); } set { taskTrigger.BeginYear = (ushort)value.Year; taskTrigger.BeginMonth = (ushort)value.Month; taskTrigger.BeginDay = (ushort)value.Day; SyncTrigger(); } } /// <summary> /// Gets/sets indication that the task uses an EndDate. Returns true if a value has been /// set for the EndDate property. Set can only be used to turn indication off. /// </summary> /// <exception cref="ArgumentException">Has EndDate becomes true only by setting the EndDate /// property.</exception> public bool HasEndDate { get { return ((taskTrigger.Flags & (uint)TaskTriggerFlags.HasEndDate) == (uint)TaskTriggerFlags.HasEndDate); } set { if (value) throw new ArgumentException("HasEndDate can only be set false"); taskTrigger.Flags &= ~(uint)TaskTriggerFlags.HasEndDate; SyncTrigger(); } } /// <summary> /// Gets/sets the ending year, month, and day for the trigger. After a value has been set /// with EndDate, HasEndDate becomes true. /// </summary> public DateTime EndDate { get { if (taskTrigger.EndYear == 0) return DateTime.MinValue; return new DateTime(taskTrigger.EndYear, taskTrigger.EndMonth, taskTrigger.EndDay); } set { taskTrigger.Flags |= (uint)TaskTriggerFlags.HasEndDate; taskTrigger.EndYear = (ushort)value.Year; taskTrigger.EndMonth = (ushort)value.Month; taskTrigger.EndDay = (ushort)value.Day; SyncTrigger(); } } /// <summary> /// Gets/sets the number of minutes after the trigger fires that it remains active. Used /// in conjunction with <see cref="IntervalMinutes"/> to run a task repeatedly for a period of time. /// For example, if you want to start a task at 8:00 A.M. repeatedly restart it until 5:00 P.M., /// there would be 540 minutes (9 hours) in the duration. /// Can also be used to terminate a task that is running when the DurationMinutes expire. Use /// <see cref="KillAtDurationEnd"/> to specify that task should be terminated at that time. /// </summary> /// <exception cref="ArgumentOutOfRangeException">Setting must be greater than or equal /// to the IntervalMinutes setting.</exception> public int DurationMinutes { get { return (int)taskTrigger.MinutesDuration; } set { if (value < taskTrigger.MinutesInterval) throw new ArgumentOutOfRangeException("DurationMinutes", value, "DurationMinutes must be greater than or equal the IntervalMinutes value"); taskTrigger.MinutesDuration = (ushort)value; SyncTrigger(); } } /// <summary> /// Gets/sets the number of minutes between executions for a task that is to be run repeatedly. /// Repetition continues until the interval specified in <see cref="DurationMinutes"/> expires. /// IntervalMinutes are counted from the start of the previous execution. /// </summary> /// <exception cref="ArgumentOutOfRangeException">Setting must be less than /// to the DurationMinutes setting.</exception> public int IntervalMinutes { get { return (int)taskTrigger.MinutesInterval; } set { if (value > taskTrigger.MinutesDuration) throw new ArgumentOutOfRangeException("IntervalMinutes", value, "IntervalMinutes must be less than or equal the DurationMinutes value"); taskTrigger.MinutesInterval = (uint)value; SyncTrigger(); } } /// <summary> /// Gets/sets whether task will be killed (terminated) when DurationMinutes expires. /// See <see cref="Trigger.DurationMinutes"/>. /// </summary> public bool KillAtDurationEnd { get { return ((taskTrigger.Flags & (uint)TaskTriggerFlags.KillAtDurationEnd) == (uint)TaskTriggerFlags.KillAtDurationEnd); } set { if (value) taskTrigger.Flags |= (uint)TaskTriggerFlags.KillAtDurationEnd; else taskTrigger.Flags &= ~(uint)TaskTriggerFlags.KillAtDurationEnd; SyncTrigger(); } } /// <summary> /// Gets/sets whether trigger is disabled. /// </summary> public bool Disabled { get { return ((taskTrigger.Flags & (uint)TaskTriggerFlags.Disabled) == (uint)TaskTriggerFlags.Disabled); } set { if (value) taskTrigger.Flags |= (uint)TaskTriggerFlags.Disabled; else taskTrigger.Flags &= ~(uint)TaskTriggerFlags.Disabled; SyncTrigger(); } } #endregion #region Methods /// <summary> /// Creates a new, bound Trigger object from an ITaskTrigger interface. The type of the /// concrete object created is determined by the type of ITaskTrigger. /// </summary> /// <param name="iTaskTrigger">Instance of ITaskTrigger.</param> /// <returns>One of the concrete classes derived from Trigger.</returns> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="ArgumentException">Unable to recognize trigger type.</exception> internal static Trigger CreateTrigger(ITaskTrigger iTaskTrigger) { if (iTaskTrigger == null) throw new ArgumentNullException("iTaskTrigger", "Instance of ITaskTrigger cannot be null"); TaskTrigger sTaskTrigger = new TaskTrigger(); sTaskTrigger.TriggerSize = (ushort)Marshal.SizeOf(sTaskTrigger); iTaskTrigger.GetTrigger(ref sTaskTrigger); switch ((TriggerType)sTaskTrigger.Type) { case TriggerType.RunOnce: return new RunOnceTrigger(iTaskTrigger); case TriggerType.RunDaily: return new DailyTrigger(iTaskTrigger); case TriggerType.RunWeekly: return new WeeklyTrigger(iTaskTrigger); case TriggerType.RunMonthlyDOW: return new MonthlyDOWTrigger(iTaskTrigger); case TriggerType.RunMonthly: return new MonthlyTrigger(iTaskTrigger); case TriggerType.OnIdle: return new OnIdleTrigger(iTaskTrigger); case TriggerType.OnSystemStart: return new OnSystemStartTrigger(iTaskTrigger); case TriggerType.OnLogon: return new OnLogonTrigger(iTaskTrigger); default: throw new ArgumentException("Unable to recognize type of trigger referenced in iTaskTrigger", "iTaskTrigger"); } } /// <summary> /// When a bound Trigger is changed, the corresponding trigger in the system /// Task Scheduler is updated to stay in sync with the local structure. /// </summary> protected void SyncTrigger() { if (iTaskTrigger!=null) iTaskTrigger.SetTrigger(ref taskTrigger); } /// <summary> /// Bind a Trigger object to an ITaskTrigger interface. This causes the Trigger to /// sync itself with the interface and remain in sync whenever it is modified in the future. /// If the Trigger is already bound, an ArgumentException is thrown. /// </summary> /// <param name="iTaskTrigger">An interface representing a trigger in Task Scheduler.</param> /// <exception cref="ArgumentException">Attempt to bind and already bound trigger.</exception> internal void Bind(ITaskTrigger iTaskTrigger) { if (this.iTaskTrigger != null) throw new ArgumentException("Attempt to bind an already bound trigger"); this.iTaskTrigger = iTaskTrigger; iTaskTrigger.SetTrigger(ref taskTrigger); } /// <summary> /// Bind a Trigger to the same interface the argument trigger is bound to. /// </summary> /// <param name="trigger">A bound Trigger. </param> internal void Bind(Trigger trigger) { Bind(trigger.iTaskTrigger); } /// <summary> /// Break the connection between this Trigger and the system Task Scheduler. This /// releases COM resources used in bound Triggers. /// </summary> internal void Unbind() { if (iTaskTrigger != null) { Marshal.ReleaseComObject(iTaskTrigger); iTaskTrigger = null; } } /// <summary> /// Gets a string, supplied by the WindowsTask Scheduler, of a bound Trigger. /// For an unbound trigger, returns "Unbound Trigger". /// </summary> /// <returns>String representation of the trigger.</returns> public override string ToString() { if (iTaskTrigger != null) { IntPtr lpwstr; iTaskTrigger.GetTriggerString(out lpwstr); return CoTaskMem.LPWStrToString(lpwstr); } else { return "Unbound " + this.GetType().ToString(); } } /// <summary> /// Determines if two triggers are internally equal. Does not consider whether /// the Triggers are bound or not. /// </summary> /// <param name="obj">Value of trigger to compare.</param> /// <returns>true if triggers are equivalent.</returns> public override bool Equals(object obj) { return taskTrigger.Equals(((Trigger)obj).taskTrigger); } /// <summary> /// Gets a hash code for the current trigger. A Trigger has the same hash /// code whether it is bound or not. /// </summary> /// <returns>Hash code value.</returns> public override int GetHashCode() { return taskTrigger.GetHashCode(); } #endregion } /// <summary> /// Generalization of all triggers that have a start time. /// </summary> /// <remarks>StartableTrigger serves as a base class for triggers with a /// start time, but it has little use to clients.</remarks> public abstract class StartableTrigger : Trigger { /// <summary> /// Internal constructor, same as base. /// </summary> internal StartableTrigger() : base() { } /// <summary> /// Internal constructor from ITaskTrigger interface. /// </summary> /// <param name="iTrigger">ITaskTrigger from system Task Scheduler.</param> internal StartableTrigger(ITaskTrigger iTrigger) : base(iTrigger) { } /// <summary> /// Sets the start time of the trigger. /// </summary> /// <param name="hour">Hour of the day that the trigger will fire.</param> /// <param name="minute">Minute of the hour.</param> /// <exception cref="ArgumentOutOfRangeException">The hour is not between 0 and 23 or the minute is not between 0 and 59.</exception> protected void SetStartTime(ushort hour, ushort minute) { // if (hour < 0 || hour > 23) // throw new ArgumentOutOfRangeException("hour", hour, "hour must be between 0 and 23"); // if (minute < 0 || minute > 59) // throw new ArgumentOutOfRangeException("minute", minute, "minute must be between 0 and 59"); // taskTrigger.StartHour = hour; // taskTrigger.StartMinute = minute; // base.SyncTrigger(); StartHour = (short)hour; StartMinute = (short)minute; } /// <summary> /// Gets/sets hour of the day that trigger will fire (24 hour clock). /// </summary> public short StartHour { get { return (short)taskTrigger.StartHour; } set { if (value < 0 || value > 23) throw new ArgumentOutOfRangeException("hour", value, "hour must be between 0 and 23"); taskTrigger.StartHour = (ushort)value; base.SyncTrigger(); } } /// <summary> /// Gets/sets minute of the hour (specified in <see cref="StartHour"/>) that trigger will fire. /// </summary> public short StartMinute { get { return (short)taskTrigger.StartMinute; } set { if (value < 0 || value > 59) throw new ArgumentOutOfRangeException("minute", value, "minute must be between 0 and 59"); taskTrigger.StartMinute = (ushort)value; base.SyncTrigger(); } } } /// <summary> /// Trigger that fires once only. /// </summary> public class RunOnceTrigger : StartableTrigger { /// <summary> /// Create a RunOnceTrigger that fires when specified. /// </summary> /// <param name="runDateTime">Date and time to fire.</param> public RunOnceTrigger(DateTime runDateTime) : base() { taskTrigger.BeginYear = (ushort)runDateTime.Year; taskTrigger.BeginMonth = (ushort)runDateTime.Month; taskTrigger.BeginDay = (ushort)runDateTime.Day; SetStartTime((ushort)runDateTime.Hour, (ushort)runDateTime.Minute); taskTrigger.Type = TaskTriggerType.TIME_TRIGGER_ONCE; } /// <summary> /// Internal constructor to create from existing ITaskTrigger interface. /// </summary> /// <param name="iTrigger">ITaskTrigger from system Task Scheduler.</param> internal RunOnceTrigger(ITaskTrigger iTrigger) : base(iTrigger) { } } /// <summary> /// Trigger that fires at a specified time, every so many days. /// </summary> public class DailyTrigger : StartableTrigger { /// <summary> /// Creates a DailyTrigger that fires only at an interval of so many days. /// </summary> /// <param name="hour">Hour of day trigger will fire.</param> /// <param name="minutes">Minutes of the hour trigger will fire.</param> /// <param name="daysInterval">Number of days between task runs.</param> public DailyTrigger(short hour, short minutes, short daysInterval) : base() { SetStartTime((ushort)hour, (ushort)minutes); taskTrigger.Type = TaskTriggerType.TIME_TRIGGER_DAILY; taskTrigger.Data.daily.DaysInterval = (ushort)daysInterval; } /// <summary> /// Creates DailyTrigger that fires every day. /// </summary> /// <param name="hour">Hour of day trigger will fire.</param> /// <param name="minutes">Minutes of hour (specified in "hour") trigger will fire.</param> public DailyTrigger(short hour, short minutes) : this(hour, minutes, 1) { } /// <summary> /// Internal constructor to create from existing ITaskTrigger interface. /// </summary> /// <param name="iTrigger">ITaskTrigger from system Task Scheduler.</param> internal DailyTrigger(ITaskTrigger iTrigger) : base(iTrigger) { } /// <summary> /// Gets/sets the number of days between successive firings. /// </summary> public short DaysInterval { get { return (short)taskTrigger.Data.daily.DaysInterval; } set { taskTrigger.Data.daily.DaysInterval = (ushort)value; base.SyncTrigger(); } } } /// <summary> /// Trigger that fires at a specified time, on specified days of the week, /// every so many weeks. /// </summary> public class WeeklyTrigger : StartableTrigger { /// <summary> /// Creates a WeeklyTrigger that is eligible to fire only during certain weeks. /// </summary> /// <param name="hour">Hour of day trigger will fire.</param> /// <param name="minutes">Minutes of hour (specified in "hour") trigger will fire.</param> /// <param name="daysOfTheWeek">Days of the week task will run.</param> /// <param name="weeksInterval">Number of weeks between task runs.</param> public WeeklyTrigger(short hour, short minutes, DaysOfTheWeek daysOfTheWeek, short weeksInterval) : base() { SetStartTime((ushort)hour, (ushort)minutes); taskTrigger.Type = TaskTriggerType.TIME_TRIGGER_WEEKLY; taskTrigger.Data.weekly.WeeksInterval = (ushort)weeksInterval; taskTrigger.Data.weekly.DaysOfTheWeek = (ushort)daysOfTheWeek; } /// <summary> /// Creates a WeeklyTrigger that is eligible to fire during any week. /// </summary> /// <param name="hour">Hour of day trigger will fire.</param> /// <param name="minutes">Minutes of hour (specified in "hour") trigger will fire.</param> /// <param name="daysOfTheWeek">Days of the week task will run.</param> public WeeklyTrigger(short hour, short minutes, DaysOfTheWeek daysOfTheWeek) : this(hour, minutes, daysOfTheWeek, 1) { } /// <summary> /// Internal constructor to create from existing ITaskTrigger interface. /// </summary> /// <param name="iTrigger">ITaskTrigger interface from system Task Scheduler.</param> internal WeeklyTrigger(ITaskTrigger iTrigger) : base(iTrigger) { } /// <summary> /// Gets/sets number of weeks from one eligible week to the next. /// </summary> public short WeeksInterval { get { return (short)taskTrigger.Data.weekly.WeeksInterval; } set { taskTrigger.Data.weekly.WeeksInterval = (ushort)value; base.SyncTrigger(); } } /// <summary> /// Gets/sets the days of the week on which the trigger fires. /// </summary> public DaysOfTheWeek WeekDays { get { return (DaysOfTheWeek)taskTrigger.Data.weekly.DaysOfTheWeek; } set { taskTrigger.Data.weekly.DaysOfTheWeek = (ushort)value; base.SyncTrigger(); } } } /// <summary> /// Trigger that fires at a specified time, on specified days of the week, /// in specified weeks of the month, during specified months of the year. /// </summary> public class MonthlyDOWTrigger : StartableTrigger { /// <summary> /// Creates a MonthlyDOWTrigger that fires every month. /// </summary> /// <param name="hour">Hour of day trigger will fire.</param> /// <param name="minutes">Minute of the hour trigger will fire.</param> /// <param name="daysOfTheWeek">Days of the week trigger will fire.</param> /// <param name="whichWeeks">Weeks of the month trigger will fire.</param> /// <param name="months">Months of the year trigger will fire.</param> public MonthlyDOWTrigger(short hour, short minutes, DaysOfTheWeek daysOfTheWeek, WhichWeek whichWeeks, MonthsOfTheYear months) : base() { SetStartTime((ushort)hour, (ushort)minutes); taskTrigger.Type = TaskTriggerType.TIME_TRIGGER_MONTHLYDOW; taskTrigger.Data.monthlyDOW.WhichWeek = (ushort)whichWeeks; taskTrigger.Data.monthlyDOW.DaysOfTheWeek = (ushort)daysOfTheWeek; taskTrigger.Data.monthlyDOW.Months = (ushort)months; } /// <summary> /// Creates a MonthlyDOWTrigger that fires during specified months only. /// </summary> /// <param name="hour">Hour of day trigger will fire.</param> /// <param name="minutes">Minute of the hour trigger will fire.</param> /// <param name="daysOfTheWeek">Days of the week trigger will fire.</param> /// <param name="whichWeeks">Weeks of the month trigger will fire.</param> public MonthlyDOWTrigger(short hour, short minutes, DaysOfTheWeek daysOfTheWeek, WhichWeek whichWeeks) : this(hour, minutes, daysOfTheWeek, whichWeeks, MonthsOfTheYear.January|MonthsOfTheYear.February|MonthsOfTheYear.March|MonthsOfTheYear.April|MonthsOfTheYear.May|MonthsOfTheYear.June|MonthsOfTheYear.July|MonthsOfTheYear.August|MonthsOfTheYear.September|MonthsOfTheYear.October|MonthsOfTheYear.November|MonthsOfTheYear.December) { } /// <summary> /// Internal constructor to create from existing ITaskTrigger interface. /// </summary> /// <param name="iTrigger">ITaskTrigger from the system Task Scheduler.</param> internal MonthlyDOWTrigger(ITaskTrigger iTrigger) : base(iTrigger) { } /// <summa... [truncated message content] |
From: Sean M. <int...@us...> - 2005-11-17 02:45:32
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev/XPath/Internal In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv11205/src/Adapdev/XPath/Internal Added Files: ObjectNavigationContext.cs ObjectNavigatorState.cs ObjectNavigatorStateDictionary.cs ObjectNavigatorStateItem.cs ObjectNavigatorStateList.cs ObjectNavigatorStateRoot.cs Log Message: --- 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 07:29:41
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev/Text/Indexing In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv5381/src/Adapdev/Text/Indexing Added Files: IIndex.cs IRecord.cs ISearchExpression.cs ISearchHitFilter.cs SearchResult.cs Log Message: --- NEW FILE: IIndex.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; namespace Adapdev.Text.Indexing { /// <summary> /// A index. /// </summary> public interface IIndex { /// <summary> /// Adds a new record to the index. /// </summary> /// <param name="record">the record</param> void Add(IRecord record); /// <summary> /// Removes a record from the index. /// </summary> /// <param name="record">existing record that /// must be removed</param> /// <remarks>for the sake of efficiency, /// reference comparison should always be preferred /// over object.Equals</remarks> void Remove(IRecord record); /// <summary> /// Removes all records from the index. /// </summary> void Clear(); /// <summary> /// Reindexes a existing record. Reindexing /// must always be explicitly started by /// the application. /// </summary> /// <param name="record">an existing record that /// was externally changed and thus should /// have its index updated</param> /// <remarks>for the sake of efficiency, /// reference comparison should always be preferred /// over object.Equals</remarks> void Update(IRecord record); /// <summary> /// Executes the search represented by the /// expression passed as argument.<br /> /// /// If the index does not know how to /// execute the search it should call /// <see cref="ISearchExpression.Evaluate"/>. Because /// of that, <see cref="ISearchExpression.Evaluate"/> /// must never call this method. /// </summary> /// <param name="expression">search expression</param> SearchResult Search(ISearchExpression expression); } } --- NEW FILE: ISearchHitFilter.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; namespace Adapdev.Text.Indexing { /// <summary> /// SearchHit filtering condition. /// </summary> public interface ISearchHitFilter { /// <summary> /// Test if the hit matches the filtering condition. /// </summary> /// <param name="hit">the hit</param> /// <returns>true if the hit matches the condition and should be included in the /// resulting SearchResult</returns> bool Test(SearchHit hit); } } --- NEW FILE: SearchResult.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; namespace Adapdev.Text.Indexing { #region SearchHit class /// <summary> /// A single item returned from a search. /// </summary> public class SearchHit { IRecord _record; /// <summary> /// creates a new object for the /// record passed as argument. /// </summary> /// <param name="record">a record</param> public SearchHit(IRecord record) { _record = record; } /// <summary> /// combines two search hits that refer /// to the same record. all the extended /// properties such as ranking and index specific /// information should be combined. /// </summary> /// <param name="other">the SearchHit that /// should be combined to this one</param> public void Combine(SearchHit other) { } /// <summary> /// The record. /// </summary> public IRecord Record { get { return _record; } } /// <summary> /// Creates a clone from this object. /// </summary> /// <returns>a clone</returns> public SearchHit Clone() { return new SearchHit(_record); } } #endregion #region SearchResult class /// <summary> /// Accumulates the results of a search. /// </summary> public class SearchResult : IEnumerable { #region RecordFieldComparer (used by SortByField) /// <summary> /// IComparer implementation for IRecord fields. /// </summary> public class RecordFieldComparer : System.Collections.IComparer { string _field; /// <summary> /// Creates a new RecordFieldComparer for /// a specific field. /// </summary> /// <param name="field">field that should be used /// in comparisons</param> public RecordFieldComparer(string field) { _field = field; } #region Implementation of IComparer /// <summary> /// See <see cref="IComparer.Compare"/> for details. /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <returns></returns> public int Compare(object x, object y) { IRecord lhs = ((SearchHit)x).Record; IRecord rhs = ((SearchHit)y).Record; object lhsField = lhs[_field]; object rhsField = rhs[_field]; return ((IComparable)lhsField).CompareTo(rhsField); } #endregion } #endregion #region RecordComparer internal class RecordComparer : System.Collections.IComparer { System.Collections.IComparer _comparer; public RecordComparer(System.Collections.IComparer comparer) { _comparer = comparer; } #region IComparer Members public int Compare(object x, object y) { return _comparer.Compare(((SearchHit)x).Record, ((SearchHit)y).Record); } #endregion } #endregion #region SearchHitRecordEnumerator (used by GetRecordEnumerator()) /// <summary> /// Enumerates the records in a SearchResult. /// </summary> public class SearchHitRecordEnumerator : IEnumerator, IEnumerable { IEnumerator _hits; internal SearchHitRecordEnumerator(IEnumerator hits) { _hits = hits; } #region Implementation of IEnumerator /// <summary> /// See <see cref="IEnumerator.Reset"/> for details. /// </summary> public void Reset() { _hits.Reset(); } /// <summary> /// See <see cref="IEnumerator.MoveNext"/> for details. /// </summary> /// <returns></returns> public bool MoveNext() { return _hits.MoveNext(); } /// <summary> /// The current record. /// </summary> public IRecord Current { get { return ((SearchHit)_hits.Current).Record; } } object IEnumerator.Current { get { return ((SearchHit)_hits.Current).Record; } } #endregion #region Implementation of IEnumerable System.Collections.IEnumerator IEnumerable.GetEnumerator() { return this; } #endregion } #endregion long _elapsedTime; ArrayList _hits; /// <summary> /// Creates an empty SearchResult object. /// </summary> public SearchResult() { _hits = new ArrayList(); } /// <summary> /// Number of items returned by the search. /// </summary> public int Count { get { return _hits.Count; } } /// <summary> /// Checks if the specified record was returned /// by the search. /// </summary> /// <param name="record">record to be checked</param> /// <returns>true if the record was indeed returned /// by the search</returns> /// <remarks>reference comparison is always used</remarks> public bool Contains(IRecord record) { return FindSearchHit(record) != null; } /// <summary> /// Adds a new item to the collection of items /// returned by the search. If the hit /// represents an existing record it /// will be combined to the existing hit instead. /// </summary> /// <param name="hit">the hit to be added or /// combined to a existing hit</param> public void Add(SearchHit hit) { SearchHit existing = FindSearchHit(hit.Record); if (null != existing) { existing.Combine(hit); } else { _hits.Add(hit); } } /// <summary> /// How long the search took /// </summary> public long ElapsedTime { get { return _elapsedTime; } set { _elapsedTime = value; } } /// <summary> /// Returns an item by its position /// </summary> public SearchHit this[int index] { get { return (SearchHit)_hits[index]; } } /// <summary> /// Set intersection operation. Creates /// a new SearchResult with all the records /// that exist in both SearchResult objects. /// </summary> /// <param name="other"></param> /// <returns>a SearchResult representing the /// intersection between the this and other objects /// </returns> /// <remarks>all the SearchHit objects in /// the resulting SearchResult are clones from /// the original ones combined to the ones in /// other</remarks> public SearchResult Intersect(SearchResult other) { SearchResult result = new SearchResult(); foreach (SearchHit hit in _hits) { SearchHit otherHit = other.FindSearchHit(hit.Record); if (null != otherHit) { SearchHit resultingHit = hit.Clone(); resultingHit.Combine(otherHit); result.Add(resultingHit); } } return result; } /// <summary> /// Build a new SearchResult object including /// only those elements for which the /// filter returns true. /// </summary> /// <param name="filter">filter</param> /// <returns>a new SearchResult containing all the elements for which /// <see cref="ISearchHitFilter.Test"/> returned true</returns> public SearchResult Filter(ISearchHitFilter filter) { SearchResult result = new SearchResult(); foreach (SearchHit hit in _hits) { if (filter.Test(hit)) { result.Add(hit); } } return result; } /// <summary> /// Sorts the result by a specific record field. /// </summary> /// <param name="field">the field to be used in the sort</param> public void SortByField(string field) { if (null == field) { throw new ArgumentNullException("field"); } _hits.Sort(new RecordFieldComparer(field)); } /// <summary> /// Sorts the result using the specified comparer. /// </summary> /// <param name="comparer"></param> public void Sort(IComparer comparer) { if (null == comparer) { throw new ArgumentNullException("comparer"); } _hits.Sort(new RecordComparer(comparer)); } /// <summary> /// Copies all the records to an array. The /// order is mantained so that /// this[N].Record == resultingArray[N] is /// valid for every 0 <= N < this.Count. /// </summary> /// <param name="recordType">array element type</param> /// <returns>the resulting array.</returns> public Array ToRecordArray(Type recordType) { object[] records = (object[])Array.CreateInstance(recordType, _hits.Count); for (int i=0; i<records.Length; ++i) { records[i] = ((SearchHit)_hits[i]).Record; } return records; } public Array ToRecordArray() { return ToRecordArray(typeof(object)); } /// <summary> /// Returns an enumerator for all the records /// in this object. /// </summary> /// <returns></returns> public SearchHitRecordEnumerator GetRecordEnumerator() { return new SearchHitRecordEnumerator(_hits.GetEnumerator()); } /// <summary> /// Finds a SearchHit that represents a specific /// record. /// </summary> /// <param name="record">the record to search for</param> /// <returns>the found SearchHit or null</returns> protected SearchHit FindSearchHit(IRecord record) { foreach (SearchHit hit in _hits) { if (hit.Record == record) { return hit; } } return null; } #region Implementation of IEnumerable /// <summary> /// See <see cref="IEnumerable.GetEnumerator"/> for details /// </summary> /// <returns></returns> public IEnumerator GetEnumerator() { return _hits.GetEnumerator(); } #endregion } #endregion } --- NEW FILE: IRecord.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; namespace Adapdev.Text.Indexing { /// <summary> /// A record that can be indexed by its fields. /// </summary> public interface IRecord { /// <summary> /// Field acessor. Returns the named field. /// </summary> /// <exception cref="ArgumentException">if the specified named field does not exist</exception> object this[string name] { get; } } } --- NEW FILE: ISearchExpression.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; namespace Adapdev.Text.Indexing { /// <summary> /// Models a search over an index or a set /// of indexes. /// </summary> public interface ISearchExpression { /// <summary> /// Evaluates the expression against /// the specified index.<br /> /// If the expression can not be evaluated /// using the specified index /// it should raise ArgumentException. /// </summary> /// <param name="index">the index</param> /// <remarks>the expression must never call /// <see cref="IIndex.Search"/> unless it is completely sure /// the IIndex implementation knows how to handle the expression without /// calling this method again (what whould result in a infinite recursion loop)</remarks> /// <exception cref="ArgumentException">when the expression can not be evaluated with the specified index</exception> SearchResult Evaluate(IIndex index); } } |
From: Sean M. <int...@us...> - 2005-11-16 07:19:59
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev/Threading In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv4187/src/Adapdev/Threading Added Files: DelegateAdapter.cs ThreadPoolWait.cs Log Message: --- 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: ThreadPoolWait.cs --- // Stephen Toub // st...@mi... // http://msdn.microsoft.com/msdnmag/issues/04/10/NETMatters/ using System; using System.Threading; using System.Collections; namespace Adapdev.Threading { /// <summary>ThreadPool utility class that allows for easily waiting on queued delegates.</summary> public class ThreadPoolWait : IDisposable { /// <summary>Number of items remaining to be executed.</summary> private int _remainingWorkItems = 1; /// <summary>Event that signals whether all items have been executed.</summary> private ManualResetEvent _done = new ManualResetEvent(false); /// <summary>Queues a user work item to the ThreadPool.</summary> /// <param name="callback">The work item to be queued.</param> public void QueueUserWorkItem(WaitCallback callback) { QueueUserWorkItem(callback, null); } /// <summary>Queues a user work item to the ThreadPool.</summary> /// <param name="callback">The work item to be queued.</param> /// <param name="state">State to be passed to the queued work item</param> public void QueueUserWorkItem(WaitCallback callback, object state) { ThrowIfDisposed(); QueuedCallback qc = new QueuedCallback(); qc.Callback = callback; qc.State = state; Interlocked.Increment(ref _remainingWorkItems); ThreadPool.QueueUserWorkItem(new WaitCallback(HandleWorkItem), qc); } /// <summary>Wait for all items to finish executing.</summary> public bool WaitOne() { return WaitOne(-1, false); } /// <summary>Wait for all items to finish executing.</summary> public bool WaitOne(TimeSpan timeout, bool exitContext) { return WaitOne((int)timeout.TotalMilliseconds, exitContext); } /// <summary>Wait for all items to finish executing.</summary> public bool WaitOne(int millisecondsTimeout, bool exitContext) { ThrowIfDisposed(); DoneWorkItem(); bool rv = _done.WaitOne(millisecondsTimeout, exitContext); // If the event is set, then we'll return true, but first // reset so that this instance can be used again. If the // event isn't set, put back the 1 unit removed by calling // DoneWorkItem. The next time WaitOne is called, // this unit will be removed by the call to DoneWorkItem. if (rv) { _remainingWorkItems = 1; _done.Reset(); } else Interlocked.Increment(ref _remainingWorkItems); return rv; } /// <summary>Executes the callback passed as state and signals its completion when it has finished executing.</summary> /// <param name="state"></param> private void HandleWorkItem(object state) { QueuedCallback qc = (QueuedCallback)state; try { qc.Callback(qc.State); } finally { DoneWorkItem(); } } /// <summary>Decrements the number of remaining items, signaling the ManualResetEvent if 0 are left.</summary> private void DoneWorkItem() { if (Interlocked.Decrement(ref _remainingWorkItems) == 0) _done.Set(); } /// <summary>State class that wraps a WaitCallback and the state object to be passed to it.</summary> private class QueuedCallback { /// <summary>A callback delegate queued to the ThreadPool.</summary> public WaitCallback Callback; /// <summary>The state to be passed to the callback.</summary> public object State; } /// <summary>Throws an exception if this instance has already been disposed.</summary> private void ThrowIfDisposed() { if (_done == null) throw new ObjectDisposedException(GetType().Name); } /// <summary>Disposes this ThreadPoolWait.</summary> public void Dispose() { if (_done != null) { ((IDisposable)_done).Dispose(); _done = null; } } } } |
From: Sean M. <int...@us...> - 2005-11-16 07:19:59
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev/Diagnostics In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv4187/src/Adapdev/Diagnostics Added Files: CPUMeter.cs HiPerfTimer.cs IPerfTimer.cs MillisecondsPerfTimer.cs MinutesPerfTimer.cs PerfTimerFactory.cs SecondsPerfTimer.cs TicksPerfTimer.cs Log Message: --- 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 07:19:59
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev/Text In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv4187/src/Adapdev/Text Added Files: StringUtil.cs Log Message: --- 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 07:19:59
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev/Reflection In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv4187/src/Adapdev/Reflection Added Files: ClassAccessor.cs ClassAccessorCache.cs FieldAccessor.cs FieldAccessorException.cs IValueAccessor.cs PropertyAccessor.cs PropertyAccessorException.cs ReflectionCache.cs Log Message: --- 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 07:19:59
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev/XPath In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv4187/src/Adapdev/XPath Added Files: TypeInfoCache.cs XPathObjectNavigator.cs Log Message: --- 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 07:19:59
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev/Transactions In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv4187/src/Adapdev/Transactions Added Files: TransactionScope.cs Log Message: --- 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 07:19:59
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev/UID In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv4187/src/Adapdev/UID Added Files: GuidUIDGenerator.cs TimeSpanUIDGenerator.cs UIDFactory.cs UIDGenerator.cs Log Message: --- 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++; } } } |
Update of /cvsroot/adapdev/Adapdev/src/Adapdev/Cryptography In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv4187/src/Adapdev/Cryptography Added Files: Crypto.cs DecryptTransformer.cs Decryptor.cs EncryptTransformer.cs EncryptionAlgorithm.cs Encryptor.cs Hasher.cs Log Message: --- NEW FILE: Decryptor.cs --- // Original Copyright 2002 Microsoft Corporation. http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnnetsec/html/SecNetHT10.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.Security.Cryptography; using System.IO; namespace Adapdev.Cryptography { /// <summary> /// Summary description for Decryptor. /// </summary> internal class Decryptor { private DecryptTransformer _transformer; private byte[] _initVec; /// <summary> /// Constructor /// </summary> /// <param name="algId">The algorithm to use for decryption</param> internal Decryptor(EncryptionAlgorithm algId) { _transformer = new DecryptTransformer(algId); } /// <summary> /// Decrypts the data /// </summary> /// <param name="bytesData">The data to decrypt</param> /// <param name="bytesKey">The key to use</param> /// <returns></returns> internal byte[] Decrypt(byte[] bytesData, byte[] bytesKey) { //Set up the memory stream for the decrypted data. MemoryStream memStreamDecryptedData = new MemoryStream(); //Pass in the initialization vector. _transformer.IV = _initVec; ICryptoTransform transform = _transformer.GetCryptoServiceProvider(bytesKey); CryptoStream decStream = new CryptoStream(memStreamDecryptedData, transform, CryptoStreamMode.Write); try { decStream.Write(bytesData, 0, bytesData.Length); } catch(Exception ex) { throw new Exception("Error while writing encrypted data to the stream: \n" + ex.Message); } decStream.FlushFinalBlock(); decStream.Close(); // Send the data back. return memStreamDecryptedData.ToArray(); } //end Decrypt /// <summary> /// Sets the initial vector (IV) /// </summary> internal byte[] IV { set{_initVec = value;} } } } --- NEW FILE: Hasher.cs --- // Original Copyright (c) 2004 Brad Vincent. http://www.codeproject.com/csharp/CyptoHashing.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.IO; using System.Text; using System.Security.Cryptography; namespace Adapdev.Cryptography { /// <summary> /// Hashing class. Only static members so no need to create an instance /// </summary> public class Hasher { #region enum, constants and fields //types of hashing available public enum HashType { SHA, SHA256, SHA384, SHA512, MD5 } #endregion #region static members public static string Hash(String inputText) { return ComputeHash(inputText,HashType.MD5); } public static string Hash(String inputText, HashType hashingType) { return ComputeHash(inputText,hashingType); } /// <summary> /// returns true if the input text is equal to hashed text /// </summary> /// <param name="inputText">unhashed text to test</param> /// <param name="hashText">already hashed text</param> /// <returns>boolean true or false</returns> public static bool IsHashEqual(string inputText, string hashText) { return (Hash(inputText) == hashText); } public static bool IsHashEqual(string inputText, string hashText, HashType hashingType) { return (Hash(inputText,hashingType) == hashText); } #endregion #region Hashing Engine /// <summary> /// computes the hash code and converts it to string /// </summary> /// <param name="inputText">input text to be hashed</param> /// <param name="hashingType">type of hashing to use</param> /// <returns>hashed string</returns> private static string ComputeHash(string inputText, HashType hashingType) { HashAlgorithm HA = getHashAlgorithm(hashingType); //declare a new encoder UTF8Encoding UTF8Encoder = new UTF8Encoding(); //get byte representation of input text byte[] inputBytes = UTF8Encoder.GetBytes(inputText); //hash the input byte array byte[] output = HA.ComputeHash(inputBytes); //convert output byte array to a string return Convert.ToBase64String(output); } /// <summary> /// returns the specific hashing alorithm /// </summary> /// <param name="hashingType">type of hashing to use</param> /// <returns>HashAlgorithm</returns> private static HashAlgorithm getHashAlgorithm(HashType hashingType) { switch (hashingType) { case HashType.MD5 : return new MD5CryptoServiceProvider(); case HashType.SHA : return new SHA1CryptoServiceProvider(); case HashType.SHA256 : return new SHA256Managed(); case HashType.SHA384 : return new SHA384Managed(); case HashType.SHA512 : return new SHA512Managed(); default : return new MD5CryptoServiceProvider(); } } #endregion } } --- NEW FILE: Encryptor.cs --- // Original Copyright 2002 Microsoft Corporation. http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnnetsec/html/SecNetHT10.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.Security.Cryptography; using System.IO; namespace Adapdev.Cryptography { /// <summary> /// Summary description for Encryptor. /// </summary> internal class Encryptor { private EncryptTransformer _transformer; private byte[] _initVec; private byte[] _encKey; /// <summary> /// Constructor /// </summary> /// <param name="algId">The encryption algorithm to use</param> internal Encryptor(EncryptionAlgorithm algId) { _transformer = new EncryptTransformer(algId); } /// <summary> /// Encrypts data /// </summary> /// <param name="bytesData">The data to encrypt</param> /// <param name="bytesKey">The key to use</param> /// <returns></returns> internal byte[] Encrypt(byte[] bytesData, byte[] bytesKey) { //Set up the stream that will hold the encrypted data. MemoryStream memStreamEncryptedData = new MemoryStream(); _transformer.IV = _initVec; ICryptoTransform transform = _transformer.GetCryptoServiceProvider(bytesKey); CryptoStream encStream = new CryptoStream(memStreamEncryptedData, transform, CryptoStreamMode.Write); try { //Encrypt the data, write it to the memory stream. encStream.Write(bytesData, 0, bytesData.Length); } catch(Exception ex) { throw new Exception("Error while writing encrypted data to the stream: \n" + ex.Message); } //Set the IV and key for the client to retrieve _encKey = _transformer.Key; _initVec = _transformer.IV; encStream.FlushFinalBlock(); encStream.Close(); //Send the data back. return memStreamEncryptedData.ToArray(); }//end Encrypt /// <summary> /// Gets / sets the initial vector /// </summary> internal byte[] IV { get{return _initVec;} set{_initVec = value;} } /// <summary> /// Gets / sets the key /// </summary> internal byte[] Key { get{return _encKey;} } } } --- NEW FILE: EncryptTransformer.cs --- // Original Copyright 2002 Microsoft Corporation. http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnnetsec/html/SecNetHT10.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.Security.Cryptography; namespace Adapdev.Cryptography { /// <summary> /// Summary description for EncryptTransformer. /// </summary> internal class EncryptTransformer { private EncryptionAlgorithm _algorithmID; private byte[] _initVec; private byte[] _encKey; internal EncryptTransformer(EncryptionAlgorithm algId) { //Save the algorithm being used. _algorithmID = algId; } internal ICryptoTransform GetCryptoServiceProvider(byte[] bytesKey) { // Pick the provider. switch (_algorithmID) { case EncryptionAlgorithm.Des: { DES des = new DESCryptoServiceProvider(); des.Mode = CipherMode.CBC; // See if a key was provided if (null == bytesKey) { _encKey = des.Key; } else { des.Key = bytesKey; _encKey = des.Key; } // See if the client provided an initialization vector if (null == _initVec) { // Have the algorithm create one _initVec = des.IV; } else { //No, give it to the algorithm des.IV = _initVec; } return des.CreateEncryptor(); } case EncryptionAlgorithm.TripleDes: { TripleDES des3 = new TripleDESCryptoServiceProvider(); des3.Mode = CipherMode.CBC; // See if a key was provided if (null == bytesKey) { _encKey = des3.Key; } else { des3.Key = bytesKey; _encKey = des3.Key; } // See if the client provided an IV if (null == _initVec) { //Yes, have the alg create one _initVec = des3.IV; } else { //No, give it to the alg. des3.IV = _initVec; } return des3.CreateEncryptor(); } case EncryptionAlgorithm.Rc2: { RC2 rc2 = new RC2CryptoServiceProvider(); rc2.Mode = CipherMode.CBC; // Test to see if a key was provided if (null == bytesKey) { _encKey = rc2.Key; } else { rc2.Key = bytesKey; _encKey = rc2.Key; } // See if the client provided an IV if (null == _initVec) { //Yes, have the alg create one _initVec = rc2.IV; } else { //No, give it to the alg. rc2.IV = _initVec; } return rc2.CreateEncryptor(); } case EncryptionAlgorithm.Rijndael: { Rijndael rijndael = new RijndaelManaged(); rijndael.Mode = CipherMode.CBC; // Test to see if a key was provided if(null == bytesKey) { _encKey = rijndael.Key; } else { rijndael.Key = bytesKey; _encKey = rijndael.Key; } // See if the client provided an IV if(null == _initVec) { //Yes, have the alg create one _initVec = rijndael.IV; } else { //No, give it to the alg. rijndael.IV = _initVec; } return rijndael.CreateEncryptor(); } default: { throw new CryptographicException("Algorithm ID '" + _algorithmID + "' not supported."); } } } internal byte[] IV { get{return _initVec;} set{_initVec = value;} } internal byte[] Key { get{return _encKey;} } } } --- NEW FILE: DecryptTransformer.cs --- // Original Copyright 2002 Microsoft Corporation. http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnnetsec/html/SecNetHT10.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.Security.Cryptography; namespace Adapdev.Cryptography { /// <summary> /// Summary description for DecryptTransformer. /// </summary> internal class DecryptTransformer { private EncryptionAlgorithm _algorithmID; private byte[] _initVec; internal DecryptTransformer(EncryptionAlgorithm deCryptId) { _algorithmID = deCryptId; } internal ICryptoTransform GetCryptoServiceProvider(byte[] bytesKey) { // Pick the provider. switch (_algorithmID) { case EncryptionAlgorithm.Des: { DES des = new DESCryptoServiceProvider(); des.Mode = CipherMode.CBC; des.Key = bytesKey; des.IV = _initVec; return des.CreateDecryptor(); } case EncryptionAlgorithm.TripleDes: { TripleDES des3 = new TripleDESCryptoServiceProvider(); des3.Mode = CipherMode.CBC; return des3.CreateDecryptor(bytesKey, _initVec); } case EncryptionAlgorithm.Rc2: { RC2 rc2 = new RC2CryptoServiceProvider(); rc2.Mode = CipherMode.CBC; return rc2.CreateDecryptor(bytesKey, _initVec); } case EncryptionAlgorithm.Rijndael: { Rijndael rijndael = new RijndaelManaged(); rijndael.Mode = CipherMode.CBC; return rijndael.CreateDecryptor(bytesKey, _initVec); } default: { throw new CryptographicException("Algorithm ID '" + _algorithmID + "' not supported."); } } } //end GetCryptoServiceProvider internal byte[] IV { set{_initVec = value;} } } } --- NEW FILE: EncryptionAlgorithm.cs --- // Original Copyright 2002 Microsoft Corporation. http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnnetsec/html/SecNetHT10.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.Cryptography { /// <summary> /// The available encryption methods /// </summary> public enum EncryptionAlgorithm { /// <summary> /// DES /// </summary> Des = 1, /// <summary> /// RC2 /// </summary> Rc2, /// <summary> /// Rijndael /// </summary> Rijndael, /// <summary> /// Triple DES /// </summary> TripleDes } } --- NEW FILE: Crypto.cs --- using System; using System.Text; namespace Adapdev.Cryptography { /// <summary> /// Summary description for Crypto. /// </summary> public class Crypto { // Des private static string _password8 = "aZbX12Yu"; // Rijndael / TripleDes private static string _password16 = "aI/c$kd8Hbb1R4nv"; // Des / TripleDes private static string _vector8 = "xbhhU7yp"; // Rijndael private static string _vector16 = "ai(hu#4x7^6txgGh"; /// <summary> /// Creates a new <see cref="Crypto"/> instance. /// </summary> private Crypto() { } /// <summary> /// Encrypts the specified text. /// </summary> /// <param name="text">Text.</param> /// <param name="algorithm">Algorithm.</param> public static byte[] Encrypt(string text, EncryptionAlgorithm algorithm) { if(algorithm == EncryptionAlgorithm.Des) { return Encrypt(text, Crypto._password8, Crypto._vector8, algorithm); } if(algorithm == EncryptionAlgorithm.Rijndael) { return Encrypt(text, Crypto._password16, Crypto._vector16, algorithm); } if(algorithm == EncryptionAlgorithm.TripleDes) { return Encrypt(text, Crypto._password16, Crypto._vector8, algorithm); } throw new Exception(algorithm.ToString() + " is not supported."); } /// <summary> /// Encrypts the specified text. /// </summary> /// <param name="text">Text.</param> /// <param name="key">Key.</param> /// <param name="vector">Vector.</param> /// <param name="algorithm">Algorithm.</param> public static byte[] Encrypt(string text, string key, string vector, EncryptionAlgorithm algorithm) { Validate(algorithm, key, vector); byte[] tIV = null; byte[] tkey = null; byte[] cipherText = null; byte[] plainText = Encoding.ASCII.GetBytes(text); Encryptor e = new Encryptor(algorithm); tkey = Encoding.ASCII.GetBytes(key); tIV = Encoding.ASCII.GetBytes(vector); e.IV = tIV; cipherText = e.Encrypt(plainText, tkey); return cipherText; } /// <summary> /// Validates the specified algorithm. /// </summary> /// <param name="algorithm">Algorithm.</param> /// <param name="key">Key.</param> /// <param name="vector">Vector.</param> private static void Validate(EncryptionAlgorithm algorithm, string key, string vector) { if(algorithm == EncryptionAlgorithm.Des) { if(key.Length != 8) throw new Exception("key length must be 8 for " + algorithm.ToString()); if(vector.Length != 8) throw new Exception("vector length must be 8 for " + algorithm.ToString()); } if(algorithm == EncryptionAlgorithm.Rijndael) { if(key.Length != 16) throw new Exception("key length must be 16 for " + algorithm.ToString()); if(vector.Length != 16) throw new Exception("vector length must be 16 for " + algorithm.ToString()); } if(algorithm == EncryptionAlgorithm.TripleDes) { if(key.Length != 16) throw new Exception("key length must be 16 for " + algorithm.ToString()); if(vector.Length != 8) throw new Exception("vector length must be 8 for " + algorithm.ToString()); } } /// <summary> /// Decrypts the specified bytes. /// </summary> /// <param name="key">Key.</param> /// <param name="vector">Vector.</param> /// <param name="algorithm">Algorithm.</param> /// <returns></returns> public static string Decrypt(byte[] cipherText, string key, string vector, EncryptionAlgorithm algorithm) { Validate(algorithm, key, vector); byte[] tIV = null; byte[] tkey = null; byte[] plainText = null; Decryptor dec = new Decryptor(algorithm); tkey = Encoding.ASCII.GetBytes(key); tIV = Encoding.ASCII.GetBytes(vector); dec.IV = tIV; // Go ahead and decrypt. plainText = dec.Decrypt(cipherText, tkey); return Encoding.ASCII.GetString(plainText); } /// <summary> /// Encrypts the specified text. /// </summary> /// <param name="cipherText">CipherText.</param> /// <param name="algorithm">Algorithm.</param> public static string Decrypt(byte[] cipherText, EncryptionAlgorithm algorithm) { if(algorithm == EncryptionAlgorithm.Des) { return Decrypt(cipherText, Crypto._password8, Crypto._vector8, algorithm); } if(algorithm == EncryptionAlgorithm.Rijndael) { return Decrypt(cipherText, Crypto._password16, Crypto._vector16, algorithm); } if(algorithm == EncryptionAlgorithm.TripleDes) { return Decrypt(cipherText, Crypto._password16, Crypto._vector8, algorithm); } throw new Exception(algorithm.ToString() + " is not supported."); } } } |
From: Sean M. <int...@us...> - 2005-11-16 07:19:57
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev/Serialization In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv4187/src/Adapdev/Serialization Added Files: Serializer.cs Log Message: --- 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 07:19:55
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev/IO In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv4187/src/Adapdev/IO Added Files: FileUtil.cs FileWatcher.cs Log Message: --- 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; } } } |
From: Sean M. <int...@us...> - 2005-11-16 07:19:54
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev/Mock In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv4187/src/Adapdev/Mock Added Files: SuppliersEntity.cs Log Message: --- 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); } } } |
From: Sean M. <int...@us...> - 2005-11-16 07:19:53
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev/Attributes In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv4187/src/Adapdev/Attributes Added Files: SchemaDataRewritableAttribute.cs Log Message: --- NEW FILE: SchemaDataRewritableAttribute.cs --- using System; namespace Adapdev.Attributes { /// <summary> /// Summary description for CompareAttribute. /// /// Add this attribute to Schema properties that should or shouldn't be updated when performing /// a CompareDatabaseSchema between the saved schema and DB schema's /// </summary> [AttributeUsage(AttributeTargets.Property)] public class SchemaDataRewritableAttribute : Attribute { private bool _rewrite; /// <summary> /// SchemaDataRewritableAttribute /// </summary> /// <param name="rewrite">bool - is this property going to be rewritten from the DatabaseSchema</param> public SchemaDataRewritableAttribute(bool rewrite) { this._rewrite = rewrite; } /// <summary> /// Is this Schema property it be re-written from the Database schama /// </summary> public bool Rewrite { get{return this._rewrite;} set{this._rewrite = value;} } } } |
From: Sean M. <int...@us...> - 2005-11-16 07:19:53
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev/Commands In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv4187/src/Adapdev/Commands Added Files: ICommand.cs Log Message: --- 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 07:05:48
|
Update of /cvsroot/adapdev/Adapdev/lib/nunit/222 In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv1930/lib/nunit/222 Added Files: mock-assembly.dll nonamespace-assembly.dll notestfixtures-assembly.dll nunit.core.dll nunit.extensions.dll nunit.framework.dll nunit.framework.tests.dll nunit.framework.tests.dll.config nunit.mocks.dll nunit.testutilities.dll nunit.util.dll Log Message: --- NEW FILE: notestfixtures-assembly.dll --- (This appears to be a binary file; contents omitted.) --- NEW FILE: nunit.framework.tests.dll.config --- <?xml version="1.0" encoding="utf-8" ?> <configuration> <!-- This is the configuration file for the NUnitTests.nunit test project. You may need to create a similar configuration file for your own test project. In your own configuration file, the include any appSettings that you require. The <NUnit> section is only needed if you want to use a non-default value for any of the settings. --> <configSections> <sectionGroup name="NUnit"> <section name="TestCaseBuilder" type="System.Configuration.NameValueSectionHandler"/> <section name="TestRunner" type="System.Configuration.NameValueSectionHandler"/> </sectionGroup> </configSections> <appSettings> <!-- User application and configured property settings go here.--> <!-- Example: <add key="settingName" value="settingValue"/> --> <add key="test.setting" value="54321" /> </appSettings> <NUnit> <TestCaseBuilder> <!-- Set to true to recognize old style test cases starting with "Test..." --> <add key="OldStyleTestCases" value="false" /> </TestCaseBuilder> <TestRunner> <!-- Valid values are STA,MTA. Others ignored. --> <add key="ApartmentState" value="MTA" /> <!-- See ThreadPriority enum for other valid values --> <add key="ThreadPriority" value="Normal" /> </TestRunner> </NUnit> <!-- The following <runtime> section allows running nunit tests under .NET 1.0 by redirecting assemblies. The appliesTo attribute causes the section to be ignored except under .NET 1.0. --> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1" appliesTo="v1.0.3705"> <dependentAssembly> <assemblyIdentity name="System" publicKeyToken="b77a5c561934e089" culture=""/> <bindingRedirect oldVersion="1.0.5000.0" newVersion="1.0.3300.0"/> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="System.Data" publicKeyToken="b77a5c561934e089" culture=""/> <bindingRedirect oldVersion="1.0.5000.0" newVersion="1.0.3300.0"/> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="System.Drawing" publicKeyToken="b03f5f7f11d50a3a" culture=""/> <bindingRedirect oldVersion="1.0.5000.0" newVersion="1.0.3300.0"/> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="System.Windows.Forms" publicKeyToken="b77a5c561934e089" culture=""/> <bindingRedirect oldVersion="1.0.5000.0" newVersion="1.0.3300.0"/> </dependentAssembly> <dependentAssembly> <assemblyIdentity name="System.Xml" publicKeyToken="b77a5c561934e089" culture=""/> <bindingRedirect oldVersion="1.0.5000.0" newVersion="1.0.3300.0"/> </dependentAssembly> </assemblyBinding> </runtime> </configuration> --- NEW FILE: nunit.framework.tests.dll --- (This appears to be a binary file; contents omitted.) --- NEW FILE: nunit.testutilities.dll --- (This appears to be a binary file; contents omitted.) --- NEW FILE: nunit.extensions.dll --- (This appears to be a binary file; contents omitted.) --- NEW FILE: nunit.core.dll --- (This appears to be a binary file; contents omitted.) --- NEW FILE: mock-assembly.dll --- (This appears to be a binary file; contents omitted.) --- NEW FILE: nonamespace-assembly.dll --- (This appears to be a binary file; contents omitted.) --- NEW FILE: nunit.util.dll --- (This appears to be a binary file; contents omitted.) --- NEW FILE: nunit.framework.dll --- (This appears to be a binary file; contents omitted.) --- NEW FILE: nunit.mocks.dll --- (This appears to be a binary file; contents omitted.) |
From: Sean M. <int...@us...> - 2005-11-16 07:05:48
|
Update of /cvsroot/adapdev/Adapdev/lib/nunit/220 In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv1930/lib/nunit/220 Added Files: mock-assembly.dll nonamespace-assembly.dll notestfixtures-assembly.dll nunit.core.dll nunit.extensions.dll nunit.framework.dll nunit.mocks.dll nunit.tests.dll nunit.tests.dll.config nunit.uikit.dll nunit.util.dll Log Message: --- NEW FILE: notestfixtures-assembly.dll --- (This appears to be a binary file; contents omitted.) --- NEW FILE: mock-assembly.dll --- (This appears to be a binary file; contents omitted.) --- NEW FILE: nunit.core.dll --- (This appears to be a binary file; contents omitted.) --- NEW FILE: nunit.extensions.dll --- (This appears to be a binary file; contents omitted.) --- NEW FILE: nunit.tests.dll.config --- <?xml version="1.0" encoding="utf-8" ?> <configuration> <!-- This is the configuration file for the nunit.tests.dll assembly. You may need to create a similar configuration file for your own tests. In your own configuration file, the include any appSettings that you require. The <NUnit> section is only needed if you want to use a non-default value for any of the settings. --> <configSections> <sectionGroup name="NUnit"> <section name="TestRunner" type="System.Configuration.NameValueSectionHandler"/> </sectionGroup> </configSections> <appSettings> <!-- User application and configured property settings go here.--> <!-- Example: <add key="settingName" value="settingValue"/> --> <add key="test.setting" value="54321" /> </appSettings> <NUnit> <TestRunner> <!-- Valid values are STA,MTA. Others ignored. --> <add key="ApartmentState" value="MTA" /> <!-- See ThreadPriority enum for other valid values --> <add key="ThreadPriority" value="Normal" /> </TestRunner> </NUnit> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="nunit.framework" publicKeyToken="96d09a1eb7f44a77" culture="neutral" /> <bindingRedirect oldVersion="2.1.4.0 - 2.2.1.65535" newVersion="2.2.2.0"/> </dependentAssembly> </assemblyBinding> </runtime> </configuration> --- NEW FILE: nunit.tests.dll --- (This appears to be a binary file; contents omitted.) --- NEW FILE: nunit.uikit.dll --- (This appears to be a binary file; contents omitted.) --- NEW FILE: nunit.util.dll --- (This appears to be a binary file; contents omitted.) --- NEW FILE: nunit.framework.dll --- (This appears to be a binary file; contents omitted.) --- NEW FILE: nunit.mocks.dll --- (This appears to be a binary file; contents omitted.) --- NEW FILE: nonamespace-assembly.dll --- (This appears to be a binary file; contents omitted.) |
From: Sean M. <int...@us...> - 2005-11-16 07:05:47
|
Update of /cvsroot/adapdev/Adapdev/lib In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv1930/lib Added Files: Genghis.dll MagicLibrary.DLL MySql.Data.dll Nini.dll TestDriven.Framework.dll log4net.dll nunit.framework.dll Log Message: --- NEW FILE: MySql.Data.dll --- (This appears to be a binary file; contents omitted.) --- NEW FILE: Genghis.dll --- (This appears to be a binary file; contents omitted.) --- NEW FILE: Nini.dll --- (This appears to be a binary file; contents omitted.) --- NEW FILE: MagicLibrary.DLL --- (This appears to be a binary file; contents omitted.) --- NEW FILE: TestDriven.Framework.dll --- (This appears to be a binary file; contents omitted.) --- NEW FILE: nunit.framework.dll --- (This appears to be a binary file; contents omitted.) --- NEW FILE: log4net.dll --- (This appears to be a binary file; contents omitted.) |
From: Sean M. <int...@us...> - 2005-11-16 07:05:47
|
Update of /cvsroot/adapdev/Adapdev/lib/nunit/214 In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv1930/lib/nunit/214 Added Files: nunit.framework.dll Log Message: --- NEW FILE: nunit.framework.dll --- (This appears to be a binary file; contents omitted.) |
Update of /cvsroot/adapdev/Adapdev/src/Adapdev In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev Added Files: Adapdev.csproj AppDomainManager.cs AssemblyCache.cs AssemblyInfo.cs CommandLineAliasAttribute.cs CommandLineParser.cs CommandLineSwitchAttribute.cs CommandLineSwitchInfo.cs CommandLineSwitchRecord.cs CompositeValidator.cs ICompositeValidator.cs IProgressCallback.cs IValidationRule.cs IValidator.cs LongLivingMarshalByRefObject.cs ObjectComparer.cs ObjectSorter.cs SortableCollectionBase.cs Util.cs ValidationResult.cs Log Message: --- NEW FILE: AppDomainManager.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 using System; using System.IO; using System.Reflection; using System.Runtime.Remoting; using System.Security.Permissions; using System.Security.Policy; using SecurityPermission = System.Security.Permissions.SecurityPermission; namespace Adapdev { using log4net; /// <summary> /// Summary description for Class1. /// </summary> /// public class AppDomainManager : LongLivingMarshalByRefObject { protected string domainName = String.Empty; protected AppDomain domain = null; protected string shadowCopyPath = AppDomain.CurrentDomain.BaseDirectory; protected AppDomainManager remote = null; protected DomainType domainType = DomainType.Local; protected string guid = String.Empty; protected bool unloaded = false; private string basedir = String.Empty; private string configFile = String.Empty; // create the logger private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Creates a new <see cref="AppDomainManager"/> instance. /// </summary> public AppDomainManager() { domain = AppDomain.CurrentDomain; basedir = AppDomain.CurrentDomain.BaseDirectory; } /// <summary> /// Creates a new <see cref="AppDomainManager"/> instance. /// </summary> /// <param name="shadowCopyDirectories">Shadow copy directories.</param> public AppDomainManager(params string[] shadowCopyDirectories) : this(AppDomain.CurrentDomain.BaseDirectory, "Test", String.Empty, shadowCopyDirectories){} /// <summary> /// Creates a new <see cref="AppDomainManager"/> instance. /// </summary> /// <param name="basedir">Basedir.</param> /// <param name="configFile">Name of the configuration file to use.</param> /// <param name="shadowCopyDirectories">Shadow copy directories.</param> public AppDomainManager(string basedir, string configFile, params string[] shadowCopyDirectories) : this(basedir, "Test", configFile, shadowCopyDirectories){} /// <summary> /// Creates a new <see cref="AppDomainManager"/> instance. /// </summary> /// <param name="basedir">The base directory to use.</param> /// <param name="shadowCopyDirectories">Shadow copy directories.</param> public AppDomainManager(string basedir, params string[] shadowCopyDirectories) : this(basedir, "Test", shadowCopyDirectories){} /// <summary> /// Creates a new <see cref="AppDomainManager"/> instance. /// </summary> /// <param name="domainName">Name of the domain.</param> /// <param name="configurationFile">Configuration file.</param> /// <param name="shadowCopyDirectories">Shadow copy directories.</param> public AppDomainManager(string basedir, string domainName, string configurationFile, params string[] shadowCopyDirectories) { this.domainName = domainName; this.domainType = DomainType.Remote; this.configFile = configurationFile; if(log.IsDebugEnabled) log.Debug("Loading new AppDomainManager"); Evidence baseEvidence = AppDomain.CurrentDomain.Evidence; Evidence evidence = new Evidence(baseEvidence); AppDomainSetup setup = new AppDomainSetup(); setup.ApplicationBase = basedir; setup.ApplicationName = "Test"; if(configurationFile.Length > 0) setup.ConfigurationFile = configurationFile; if(log.IsDebugEnabled) { log.Debug("ApplicationBase: " + setup.ApplicationBase); log.Debug("ApplicationName: " + setup.ApplicationName); log.Debug("ConfigurationFile: " + setup.ConfigurationFile); } if(shadowCopyDirectories != null && shadowCopyDirectories.Length >= 0) { guid = System.Guid.NewGuid().ToString(); setup.ShadowCopyFiles = "true"; setup.CachePath = this.GetCachePath(); foreach (string shadowCopyDirectory in shadowCopyDirectories) { string dir = String.Empty; if(File.Exists(shadowCopyDirectory)) { // if it's a file, grab the directory name FileInfo f = new FileInfo(shadowCopyDirectory); dir = f.DirectoryName; } else { dir = shadowCopyDirectory; } if(setup.ShadowCopyDirectories != null && setup.ShadowCopyDirectories.Length > 0) { setup.ShadowCopyDirectories += ";" + dir; } else { setup.ShadowCopyDirectories += dir; } } } domain = AppDomain.CreateDomain(this.domainName, evidence, setup); remote = (AppDomainManager)domain.CreateInstanceAndUnwrap(typeof(AppDomainManager).Assembly.FullName, typeof(AppDomainManager).FullName); } /// <summary> /// Adds the assembly. /// </summary> /// <param name="path">Path.</param> public void AddAssembly(string path) { string assemblyDirectory = Path.GetDirectoryName( path ); if(log.IsDebugEnabled)log.Debug("Adding " + path); if(this.domainType == DomainType.Local) { domain.AppendPrivatePath(assemblyDirectory); this.LoadAssembly(path); } else { domain.AppendPrivatePath(assemblyDirectory); remote.LoadAssembly(path); } } /// <summary> /// Adds the assemblies. /// </summary> /// <param name="paths">Paths.</param> public void AddAssemblies(params string[] paths) { foreach (string path in paths) { try { this.AddAssembly(path); } catch(FileNotFoundException){} } } /// <summary> /// Adds all the dlls in the directory to the AppDomain /// </summary> /// <param name="path">Path.</param> public void AddDirectory(string path) { foreach (string file in Directory.GetFiles(path)) { FileInfo f = new FileInfo(file); if(f.Extension == "dll") { this.AddAssembly(file); } } } /// <summary> /// Unloads the AppDomain. /// </summary> public void Unload() { if(!(this.domainName == String.Empty) && !unloaded) { if(log.IsDebugEnabled) { foreach(AssemblyInfo a in this.GetLoadedAssemblies()) { log.Debug("Unloading: " + a.Name + " - " + a.Version + " - " + a.Location); } } // Must unload AppDomain first, before you can delete the shadow copy directory AppDomain.Unload(this.domain); if(this.guid.Length > 0 && Directory.Exists(this.GetCachePath())) { Directory.Delete(this.GetCachePath(), true); } unloaded = true; if(log.IsDebugEnabled) log.Debug("Domain unloaded."); } } /// <summary> /// Gets the domain. /// </summary> /// <value></value> public AppDomain Domain { get { return domain; } } /// <summary> /// Loads the assembly. /// </summary> /// <param name="path">Path.</param> protected void LoadAssembly(string path) { AssemblyCache.Add(path.ToLower(), path); } /// <summary> /// Gets the loaded assemblies. /// </summary> public AssemblyInfo[] GetLoadedAssemblies() { AssemblyInfo[] ass = null; if(this.domainType == DomainType.Local){ ass = new AssemblyInfo[AppDomain.CurrentDomain.GetAssemblies().Length]; int i = 0; foreach (Assembly assembly in domain.GetAssemblies()) { try { AssemblyInfo ai = new AssemblyInfo(); ai.CodeBase = assembly.CodeBase; ai.FullName = assembly.FullName; ai.Location = assembly.Location; ai.Name = assembly.GetName().Name; ai.Version = assembly.GetName().Version.ToString(); ass[i] = ai; i++; } // In case it's a dynamic assembly, it can't be analyzed catch(Exception){} } }else { ass = remote.GetLoadedAssemblies(); } return ass; } /// <summary> /// Determines whether the specified path is loaded. /// </summary> /// <param name="path">Path.</param> /// <returns> /// <c>true</c> if the specified path is loaded; otherwise, <c>false</c>. /// </returns> public bool IsLoaded(string path) { if(this.domainType == DomainType.Local) return AssemblyCache.ContainsByPath(path); else return remote.IsLoaded(path); } /// <summary> /// Gets the cache path. /// </summary> /// <returns></returns> internal string GetCachePath() { if(guid.Length > 0) return Path.Combine(Path.Combine(System.Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "zanebugcache"),guid); return String.Empty; } /// <summary> /// Gets the domain type. /// </summary> /// <value></value> public DomainType DomainType { get { return domainType; } } /// <summary> /// Gets the object by path. /// </summary> /// <param name="path">Path.</param> /// <param name="classname">Classname.</param> /// <returns></returns> public object GetObjectByPath(string path, string classname) { string filename = Path.GetFileNameWithoutExtension(path); return this.GetObjectByName(filename, classname); } /// <summary> /// Gets the object by name. /// </summary> /// <param name="name">Name.</param> /// <param name="classname">Classname.</param> /// <returns></returns> public object GetObjectByName(string name, string classname) { return domain.CreateInstanceAndUnwrap(name, classname); } public string ConfigurationFile { get{return this.configFile;} } } public enum DomainType { Local, Remote } } --- NEW FILE: ICompositeValidator.cs --- using System; namespace Adapdev { /// <summary> /// Summary description for IRuleValidatable. /// </summary> public interface ICompositeValidator : IValidator { void AddRule(IValidationRule rule); } } --- NEW FILE: LongLivingMarshalByRefObject.cs --- (This appears to be a binary file; contents omitted.) --- NEW FILE: SortableCollectionBase.cs --- // Copyright 2004 J. Ambrose - http://dotnettemplar.net/PermaLink.aspx?guid=1d32654f-9ed5-46e2-a815-4f70b762f734 using System; using System.Reflection; using System.CodeDom.Compiler; using Microsoft.CSharp; namespace Adapdev.Collections { /// <summary> /// Base class that provides T-SQL-like sorting capabilities. /// </summary> /// <remarks>This class is not thread safe; it depends on the /// underlying collection to remain static during sorting /// operations, therefore, use the <see cref="GetNewView"/> /// methods to get a shallow copy of the collection before /// attempting sort operations if the collection instance /// could be accessed by more than one thread in your /// application.</remarks> public class SortableCollectionBase : System.Collections.CollectionBase { #region Static Caches /// <summary> /// Comparer cache that stores instances of dynamically-created comparers. /// </summary> protected static System.Collections.Hashtable comparers = new System.Collections.Hashtable(100); /// <summary> /// Table for ensuring that we only generate a unique comparer once. /// </summary> protected static System.Collections.Hashtable comparerLocks = new System.Collections.Hashtable(10); /// <summary> /// Assembly path cache that stores the paths to the referenced assemblies /// to be used when compiling dynamically-created comparers. /// </summary> protected static System.Collections.Hashtable assemblyPaths = new System.Collections.Hashtable(10); #endregion #region GetNewView /// <summary> /// Gets a new <see cref="SortableCollectionBase"/> to /// provide a unique view of the underlying collection. /// </summary> /// <overload>Gets a view of the current collection.</overload> /// <returns>A new view of the underlying collection.</returns> /// <remarks>This would typically be used when needing to modify /// the collection for display purposes, such as sorting and the like. /// <p>It performs a shallow copy of the collection.</p></remarks> public SortableCollectionBase GetNewView() { SortableCollectionBase view = new SortableCollectionBase(); for (int i = 0; i < this.List.Count; i++) { view.List.Add(this.List[i]); } return view; } /// <summary> /// Gets a view of the current collection as /// the collection type specified. /// </summary> /// <overload>Gets a view of the current collection.</overload> /// <param name="collectionType">The type of collection to return.</param> /// <returns>A collection of the specified <i>collectionType</i> /// that contains a shallow copy of the items in this collection.</returns> /// <remarks> /// Constraints: A <see cref="NotSupportedException"/> will /// be thrown if any are not met. /// <ul> /// <li>The <i>collectionType</i> must implement a /// default constructor ("new" constraint).</li> /// <li>The <i>collectionType</i> must implement the /// <see cref="System.Collections.IList"/> interface.</li> /// </ul> /// </remarks> public System.Collections.IList GetNewView(System.Type collectionType) { return this.GetNewView(collectionType, null); } /// <summary> /// Gets a view of the current collection, sorted using the given <i>sortExpression</i>. /// </summary> /// <overload>Gets a view of the current collection.</overload> /// <param name="collectionType">The type of collection to return.</param> /// <param name="sortExpression"></param> /// <returns>A collection of the specified <i>collectionType</i> /// that contains a shallow copy of the items in this collection.</returns> /// <remarks> /// Constraints: A <see cref="NotSupportedException"/> will /// be thrown if any are not met. /// <ul> /// <li>The <i>collectionType</i> must implement a /// default constructor ("new" constraint).</li> /// <li>The <i>collectionType</i> must inherit from the /// <see cref="SortableCollectionBase"/> class.</li> /// </ul> /// </remarks> public System.Collections.IList GetNewView(System.Type collectionType, string sortExpression) { System.Reflection.ConstructorInfo ctor; // retrieve the property info for the specified property ctor = collectionType.GetConstructor(new System.Type[0]); if (ctor == null) throw new NotSupportedException( String.Format("The '{0}' type must have a public default constructor.", collectionType.FullName)); // get an instance of the collection type SortableCollectionBase view = ctor.Invoke(new object[] {}) as SortableCollectionBase; if (view == null) throw new NotSupportedException( String.Format("The '{0}' type must inherit from SortableCollectionBase.", collectionType.FullName)); for (int i = 0; i < this.List.Count; i++) view.InnerList.Add(base.List[i]); if (sortExpression != null) view.Sort(sortExpression); return view; } #endregion #region Sort /// <summary> /// Sorts the list by the given expression. /// </summary> /// <param name="sortExpression">A sort expression, e.g., MyProperty ASC, MyProp2 DESC.</param> /// <remarks> /// Valid sort expressions are comma-delimited lists of properties where each property /// can optionally be followed by a sort direction (ASC or DESC).<br /> /// Sort order is from left to right, i.e., properties to the left are sorted on first. /// <p>All properties sorted on must implement <see cref="IComparable"/> and meaningfully /// override <see cref="Object.Equals"/>.</p> /// <p>If <i>sortExpression</i> is null, an <see cref="ArgumentNullException"/> is thrown.<br /> /// If <i>sortExpression</i> is empty, an <see cref="ArgumentException"/> is thrown.<br /> /// Throws an <see cref="ApplicationException"/> if there are errors compiling the comparer /// or if a new instance of a dynamically-created comparer cannot be created /// for any of the sort properties.</p> /// <p>It is assumed that all objects in the collection are of the same type.</p> /// </remarks> public void Sort(string sortExpression) { #region Parameter Checks if (sortExpression == null) throw new ArgumentNullException("sortExpression", "Argument cannot be null."); #endregion this.InnerList.Sort(this.GetMultiComparer(this.List[0].GetType(), sortExpression)); } /// <summary> /// Gets an <see cref="System.Collections.IComparer"/> for the given type and sort expression. /// </summary> /// <param name="type">The type of object to be sorted.</param> /// <param name="sortExpression">A sort expression, e.g., MyProperty ASC, MyProp2 DESC.</param> /// <returns>An <see cref="System.Collections.IComparer"/> for the given type and sort expression.</returns> protected System.Collections.IComparer GetMultiComparer(System.Type type, string sortExpression) { // split the sort expression string by the commas string[] sorts = sortExpression.Split(','); // if no sorts are present, throw an exception if (sorts.Length == 0) throw new ArgumentException("No sorts were passed in the sort expression.", "sortExpression"); string typeName = type.FullName; // create a unique type name for the comparer based on the type and sort expression string comparerName = sortExpression.Replace(",", "").Replace(" ", "") + "Comparer", dynamicTypeName = typeName + "DynamicComparers." + comparerName; System.Collections.IComparer comparer = null; // check the comparers table for an existing comparer for this type and property if (!comparers.ContainsKey(dynamicTypeName)) // not found { object comparerLock; bool generate = false; // let threads pile up here waiting their turn to look at this collection lock (comparerLocks.SyncRoot) { // First, we see if the comparer lock for this // dynamicTypeName exists. comparerLock = comparerLocks[dynamicTypeName]; if (comparerLock == null) { // This is the first thread in here looking for this // dynamicTypeName, so it gets to be the one to // create the comparer for the dynamicTypeName. generate = true; // Add lock object for any future threads to see and // know that they won't need to generate the comparer. comparerLock = new object(); comparerLocks.Add(dynamicTypeName, comparerLock); } } // comparerLock will be unique per dynamicTypeName and, consequently, // per unique comparer. However, the code above only ensures // that only one thread will do the generation of the comparer. // We now need to lock the comparerLock for each dynamicTypeName to // make non generating threads wait on the thread that is doing the // generation, so we ensure that the comparer is generated for all // threads by the time we exit the following block. lock (comparerLock) { // This ensures only that first thread in actually does any generation. if (generate) { // declare the source code for the dynamic assembly string compareCode = @" using System; namespace [TypeName]DynamicComparers { public sealed class [ComparerName] : System.Collections.IComparer { public int Compare(object first, object second) { [TypeName] firstInstance = first as [TypeName]; if (firstInstance == null) throw new ArgumentNullException(""First object cannot be null."", ""first""); [TypeName] secondInstance = second as [TypeName]; if (secondInstance == null) throw new ArgumentNullException(""Second object cannot be null."", ""second""); int result = 0; [CompareCode] } } } "; System.Text.StringBuilder compareBuilder = new System.Text.StringBuilder(); string propertyName; bool desc; for (int sortIndex = 0; sortIndex < sorts.Length; sortIndex++) { // check current sort for null, continue if null if (sorts[sortIndex] == null) continue; // split current sort by space to distinguish property from asc/desc string[] sortValues = sorts[sortIndex].Trim().Split(' '); // if there are no values after split, leave -- should have at least the prop name if (sortValues.Length == 0) continue; // prop name will be first value propertyName = sortValues[0].Trim(); // ensure property exists on specified type PropertyInfo prop = type.GetProperty(propertyName); if (prop == null) throw new ArgumentException( String.Format("Specified property '{0}' is not a property of type '{1}'.", propertyName, type.FullName), "sortExpression"); // if there, the second will be asc/desc; compare to get whether or not this // sort is descending desc = (sortValues.Length > 1) ? (sortValues[1].Trim().ToUpper() == "DESC") : false; // if property type is reference type, we need to do null checking in the compare code bool checkForNull = !prop.PropertyType.IsValueType; // check for null if the property is a reference type if (checkForNull) compareBuilder.Append("\t\t\tif (firstInstance." + propertyName + " != null)\n\t"); // compare the property compareBuilder.Append("\t\t\tresult = firstInstance." + propertyName + ".CompareTo(secondInstance." + propertyName + ");"); // check for null on the second type, if necessary if (checkForNull) { // if second type is also null, return true; otherwise, the first instance is // less than the second because it is null compareBuilder.Append("\t\t\telse if (secondInstance." + propertyName + " == null)\n"); compareBuilder.Append("\t\t\t\tresult = 0; else result = -1;\n"); } // if the two are not equal, no further comparison is needed, just return the // current compare value and flip the sign, if the current sort is descending compareBuilder.Append("\t\t\tif (result !=0) return " + (desc ? "-" : "") + "(result);\n"); } // if all comparisons were equal, we'll need the next line to return that result compareBuilder.Append("\t\t\treturn result;"); // replace the type and comparer name placeholders in the source with real values // and insert the property comparisons compareCode = compareCode.Replace("[TypeName]", typeName).Replace("[ComparerName]", comparerName) .Replace("[CompareCode]", compareBuilder.ToString()); #if TRACE System.Diagnostics.Debug.WriteLine(compareCode); #endif // create a C# compiler instance ICodeCompiler compiler = new CSharpCodeProvider().CreateCompiler(); // create a compiler parameters collection CompilerParameters parameters = new CompilerParameters(); // add necessary assembly references for the source to compile string primeAssemblyPath = type.Assembly.Location.Replace("file:///", "").Replace("/", "\\"); parameters.ReferencedAssemblies.Add(primeAssemblyPath); foreach (System.Reflection.AssemblyName asm in type.Assembly.GetReferencedAssemblies()) parameters.ReferencedAssemblies.Add(this.GetAssemblyPath(asm)); // tell the compiler to generate the IL in memory parameters.GenerateInMemory = true; // compile the new dynamic assembly using the parameters and source from above CompilerResults compiled = compiler.CompileAssemblyFromSource(parameters, compareCode); // check for compiler errors if (compiled.Errors.HasErrors) { // build error message from compiler errors string message = "Could not generate a comparer for '{0}'. Errors:\n"; for (int i = 0; i < compiled.Errors.Count; i++) message += compiled.Errors[i].ErrorText + "\n"; // throw an exception with the relevant information throw new ApplicationException( String.Format(message, dynamicTypeName)); } // get an instance of the new type as IComparer comparer = compiled.CompiledAssembly.CreateInstance(dynamicTypeName) as System.Collections.IComparer; // throw an exception if getting the new instance fails if (comparer == null) throw new ApplicationException( String.Format("Could not instantiate the dynamic type '{0}'.", dynamicTypeName)); // add the new comparer to the comparers table lock (comparers) comparers.Add(dynamicTypeName, comparer); } // (generate) } // comparer lock } // comparers cache check // At this point, we should be sure that a comparer has been generated for the // requested dynamicTypeName and stuck in the cache. If we're the thread that // did the generating, comparer will not be null, and we can just return it. // If comparer hasn't been assigned (via generating it above), get it from the cache. if (comparer == null) { // get the comparer from the cache comparer = comparers[dynamicTypeName] as System.Collections.IComparer; // throw an exception if the comparer cannot be retrieved if (comparer == null) throw new ApplicationException( String.Format("Could not retrieve the dynamic type '{0}'.", dynamicTypeName)); } // return the comparer return comparer; } /// <summary> /// Loads the given assembly to get its path (for dynamic compilation reference). /// </summary> /// <param name="assembly">AssemblyName instance to load assembly from.</param> /// <returns>The path for the given assembly or an empty /// string if it can't load/locate it.</returns> protected string GetAssemblyPath(System.Reflection.AssemblyName assembly) { string assemblyFullName = assembly.FullName; string path = string.Empty; path = (string)assemblyPaths[assemblyFullName]; if (path == null) { lock (assemblyPaths.SyncRoot) { path = (string)assemblyPaths[assemblyFullName]; if (path == null) { System.Reflection.Assembly asm = System.Reflection.Assembly.Load(assembly); if (asm != null) { path = asm.Location.Replace("file:///", "").Replace("/", "\\"); } assemblyPaths.Add(assemblyFullName, path); } } } return path; } #endregion } } --- NEW FILE: IProgressCallback.cs --- // // This code based on functions from http://www.codeproject.com/cs/miscctrl/progressdialog.asp // Original Author: About Matthew Adams // using System; namespace Adapdev { public enum ProgressMessageTypes { Info, Warning, Critical }; public enum ProgressAutoCloseTypes {AutoClose, WaitOnEnd, WaitOnError} /// <summary> /// This defines an interface which can be implemented by UI elements /// which indicate the progress of a long operation. /// (See ProgressWindow for a typical implementation) /// </summary> public interface IProgressCallback { /// <summary> /// Call this method from the worker thread to initialize /// the progress callback. /// </summary> /// <param name="minimum">The minimum value in the progress range (e.g. 0)</param> /// <param name="maximum">The maximum value in the progress range (e.g. 100)</param> void Begin( int minimum, int maximum ); /// <summary> /// Call this method from the worker thread to initialize /// the progress callback. /// </summary> /// <param name="minimum">The minimum value in the progress range (e.g. 0)</param> /// <param name="maximum">The maximum value in the progress range (e.g. 100)</param> /// <param name="autoClose">Specify to automatically close on End or Pause on End</param> void Begin(ProgressAutoCloseTypes autoClose, int minimum, int maximum ); /// <summary> /// Call this method from the worker thread to initialize /// the progress callback, without setting the range /// </summary> void Begin(); /// <summary> /// Call this method to set the AutoClose flag. True mean to autoclose on completion /// (default) and false means to wait when closing. /// </summary> /// <param name="autoClose">Sets the flag</param> void SetAutoClose( ProgressAutoCloseTypes autoClose ); /// <summary> /// Call this method from the worker thread to reset the range in the progress callback /// </summary> /// <param name="minimum">The minimum value in the progress range (e.g. 0)</param> /// <param name="maximum">The maximum value in the progress range (e.g. 100)</param> /// <remarks>You must have called one of the Begin() methods prior to this call.</remarks> void SetRange( int minimum, int maximum ); /// <summary> /// Call this method from the worker thread to update the progress text. /// </summary> /// <param name="text1">The progress text to display</param> /// <remarks>You must have called one of the Begin() methods prior to this call.</remarks> void SetText( String text1, String text2 ); void SetText( String text ); /// <summary> /// Call this method to add a message to the list box of messages /// </summary> /// <param name="message"></param> void AddMessage( string message ); void AddMessage( ProgressMessageTypes type, string message ); /// <summary> /// Call this method from the worker thread to increase the progress counter by a specified value. /// </summary> /// <param name="val">The amount by which to increment the progress indicator</param> /// <remarks>You must have called one of the Begin() methods prior to this call.</remarks> void StepTo( int val ); /// <summary> /// Call this method from the worker thread to step the progress meter to a particular value. /// </summary> /// <param name="val">The value to which to step the meter</param> /// <remarks>You must have called one of the Begin() methods prior to this call.</remarks> void Increment( int val ); /// <summary> /// If this property is true, then you should abort work /// </summary> /// <remarks>You must have called one of the Begin() methods prior to this call.</remarks> bool IsAborting { get; } /// <summary> /// Call this method from the worker thread to finalize the progress meter /// </summary> /// <remarks>You must have called one of the Begin() methods prior to this call.</remarks> void End(); } } --- NEW FILE: CommandLineParser.cs --- // Original Copyright (c) 2003 Ray Hayes. http://www.codeproject.com/csharp/commandlineparser.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 111504 Renamed class to CommandLineParser */ #endregion using System; using System.Text; using System.Reflection; using System.Text.RegularExpressions; namespace Adapdev { /// <summary> /// A command-line parsing class that is capable of having switches /// programatically registered with it; or, it can use reflection to /// find properties with the <see cref="CommandLineSwitchAttribute" /> /// </summary> public class CommandLineParser { #region Private Variables /// <summary> /// Command line on which the parser operates /// </summary> private string _commandLine = ""; /// <summary> /// String holding the part of the command line that did not match /// any switch definitions /// </summary> private string _workingString = ""; /// <summary> /// Name of the application parsed from the command line /// </summary> private string _applicationName = ""; /// <summary> /// Array of parameters (whitespace separated command line /// elements) parsed from the command line /// </summary> private string[] _splitParameters = null; /// <summary> /// Array of recognized switches parsed from the command line /// </summary> private System.Collections.ArrayList _switches = null; #endregion #region Private Utility Functions /// <summary> /// Extracts the application name from <see cref="_commandLine" /> /// and places it in <see cref="_applicationName" /> /// </summary> private void ExtractApplicationName() { Regex r = new Regex(@"^(?<commandLine>(""[^\""]+""|(\S)+))(?<remainder>.+)", RegexOptions.ExplicitCapture); Match m = r.Match(_commandLine); if ( m != null && m.Groups["commandLine"] != null ) { _applicationName = m.Groups["commandLine"].Value; _workingString = m.Groups["remainder"].Value; } } /// <summary> /// Extracts the parameters from <see cref="_commandLine" /> /// and places them in <see cref="_splitParameters" /> /// </summary> /// <remarks> /// If quotes are used, the quotes are removed but the text between /// the quotes is kept as a single parameter /// </remarks> /// <example>For example: /// if <c>_commandLine</c> has <c>one two three "four five six"</c> /// then <c>_splitParameters</c> would contain /// <list type="table"> /// <item> /// <term>_splitParameters[0]</term><description>one</description> /// </item> /// <item> /// <term>_splitParameters[1]</term><description>two</description> /// </item> /// <item> /// <term>_splitParameters[2]</term><description>three</description> /// </item> /// <item> /// <term>_splitParameters[3]</term><description>four five six</description> /// </item> /// </list> /// </example> private void SplitParameters() { // Populate the split parameters array with the remaining parameters. Regex r = new Regex(@"((\s*(""(?<param>.+?)""|(?<param>\S+))))", RegexOptions.ExplicitCapture); MatchCollection m = r.Matches( _workingString ); if ( m != null ) { _splitParameters = new string[ m.Count ]; for ( int i=0; i < m.Count; i++ ) _splitParameters[i] = m[i].Groups["param"].Value; } } /// <summary> /// Parses the command line looking for switches and setting their /// proper values /// </summary> private void HandleSwitches() { if ( _switches != null ) { foreach ( CommandLineSwitchRecord s in _switches ) { Regex r = new Regex( s.Pattern, RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase ); MatchCollection m = r.Matches( _workingString ); if ( m != null ) { for ( int i=0; i < m.Count; i++ ) { string value = null; if ( m[i].Groups != null && m[i].Groups["value"] != null ) value = m[i].Groups["value"].Value; if ( s.Type == typeof(bool)) { bool state = true; // The value string may indicate what value we want. if ( m[i].Groups != null && m[i].Groups["value"] != null ) { switch ( value ) { case "+": state = true; break; case "-": state = false; break; case "": if ( s.ReadValue != null ) state = !(bool)s.ReadValue; break; default: break; } } s.Notify( state ); break; } else if ( s.Type == typeof(string) ) s.Notify( value ); else if ( s.Type == typeof(int) ) s.Notify( int.Parse( value ) ); else if ( s.Type.IsEnum ) s.Notify( System.Enum.Parse(s.Type,value,true) ); } } _workingString = r.Replace(_workingString, " "); } } } #endregion #region Public Properties /// <summary> /// Gets the string holding the part of the command line that did not match /// any switch definitions /// </summary> public string UnhandledCommandLine { get { return _workingString.TrimStart(' '); } } /// <summary> /// Gets the name of the application parsed from the command line /// </summary> public string ApplicationName { get { return _applicationName; } } /// <summary> /// Gets an array of parameters (whitespace separated command line /// elements) parsed from the command line /// </summary> public string[] UnhandledParameters { get { return _splitParameters; } } /// <summary> /// Gets an array of recognized switches parsed from the command line /// </summary> public CommandLineSwitchInfo[] Switches { get { if ( _switches == null ) return null; else { CommandLineSwitchInfo[] si = new CommandLineSwitchInfo[ _switches.Count ]; for ( int i=0; i<_switches.Count; i++ ) si[i] = new CommandLineSwitchInfo( _switches[i] ); return si; } } } /// <summary> /// Gets the value of the switch at the specified index. /// </summary> public object this[string name] { get { if ( _switches != null ) for ( int i=0; i<_switches.Count; i++ ) if ( string.Compare( (_switches[i] as CommandLineSwitchRecord).Name, name, true )==0 ) return (_switches[i] as CommandLineSwitchRecord).Value; return null; } } /// <summary> /// Gets an array containing the switches the parser has /// recognized but have not been registered. /// </summary> /// <remark> /// The unhandled switches are not removed from the remainder /// of the command-line. /// </remark> public string[] UnhandledSwitches { get { string switchPattern = @"(\s|^)(?<match>(-{1,2}|/)(.+?))(?=(\s|$))"; Regex r = new Regex( switchPattern, RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase ); MatchCollection m = r.Matches( _workingString ); if ( m != null ) { string[] unhandled = new string[ m.Count ]; for ( int i=0; i < m.Count; i++ ) unhandled[i] = m[i].Groups["match"].Value; return unhandled; } else return new string[]{}; } } /// <summary> /// Gets a string that describes the command line usage /// based on the registered switches /// </summary> public string Usage { get { StringBuilder builder = new StringBuilder(); int oldLength; foreach ( CommandLineSwitchRecord s in _switches ) { oldLength = builder.Length; builder.Append(" /"); builder.Append(s.Name); Type valueType = s.Type; if (valueType == typeof(int)) { builder.Append(":<int>"); } else if (valueType == typeof(uint)) { builder.Append(":<uint>"); } else if (valueType == typeof(bool)) { builder.Append("[+|-]"); } else if (valueType == typeof(string)) { builder.Append(":<string>"); } else { builder.Append(":{"); bool first = true; foreach (FieldInfo field in valueType.GetFields()) { if (field.IsStatic) { if (first) first = false; else builder.Append('|'); builder.Append(field.Name); } } builder.Append('}'); } builder.Append("\r\n"); } oldLength = builder.Length; builder.Append(" @<file>"); builder.Append(' ', IndentLength(builder.Length - oldLength)); builder.Append("Read response file for more options"); builder.Append("\r\n"); return builder.ToString(); } } /// <summary> /// Computes the number of characters a line should be indented /// so that it is right justified at 40 characters. /// </summary> /// <remarks> /// If <paramref name="lineLength"/> is over 36 characters, the indent /// is simply set to four. /// </remarks> /// <param name="lineLength">Number of characters in the line</param> /// <returns>Number of spaces to indent</returns> private static int IndentLength(int lineLength) { return Math.Max(4, 40 - lineLength); } #endregion #region Public Methods /// <summary> /// Registers a switch with the command line parser /// </summary> /// <remarks> /// Switches named here should not include a switch prefix character /// such as a slash or minus. This is handled by the parser in /// <see cref="CommandLineSwitchRecord"/>. /// </remarks> /// <example>For example: /// <code> /// parser = new CommandLineParser(System.Environment.CommandLine); /// parser.AddSwitch(@"\?" , "show help"); /// parser.Parse(); /// </code> /// </example> /// <param name="name">The name of the switch.</param> /// <param name="description">Usage description for the switch.</param> public void AddSwitch( string name, string description ) { if ( _switches == null ) _switches = new System.Collections.ArrayList(); CommandLineSwitchRecord rec = new CommandLineSwitchRecord( name, description ); _switches.Add( rec ); } /// <summary> /// Registers an array of synonymous switches (aliases) with the /// command line parser /// </summary> /// <remarks> /// Switches named here should not include a switch prefix character /// such as a slash or minus. This is handled by the parser in /// <see cref="CommandLineSwitchRecord"/>. /// <para> /// The first switch in the array is considered to be the actual /// name of the switch while those that follow create the aliases /// for the switch /// </para> /// </remarks> /// <example>For example: /// <code> /// parser = new CommandLineParser(System.Environment.CommandLine); /// parser.AddSwitch(new string[] { "help", @"usage" }, "show help"); //Add a switch with an alias /// parser.Parse(); /// </code> /// </example> /// <param name="names">Name and aliases of the switch.</param> /// <param name="description">Usage description for the switch.</param> public void AddSwitch( string[] names, string description ) { if ( _switches == null ) _switches = new System.Collections.ArrayList(); CommandLineSwitchRecord rec = new CommandLineSwitchRecord( names[0], description ); for ( int s=1; s<names.Length; s++ ) rec.AddAlias( names[s] ); _switches.Add( rec ); } /// <summary> /// Parses the command line. /// </summary> public void Parse() { ExtractApplicationName(); // Remove switches and associated info. HandleSwitches(); // Split parameters. SplitParameters(); } /// <summary> /// Gets the value of the switch with the specified name /// </summary> /// <param name="name">Name of the switch</param> /// <returns>Value of the named switch</returns> public object InternalValue(string name) { if ( _switches != null ) for ( int i=0; i<_switches.Count; i++ ) if ( string.Compare( (_switches[i] as CommandLineSwitchRecord).Name, name, true )==0 ) return (_switches[i] as CommandLineSwitchRecord).InternalValue; return null; } #endregion #region Constructors /// <summary> /// Initializes a new instance of the CommandLineParser class /// </summary> /// <example>For example: /// <code> /// CommandLineParser clp = new CommandLineParser(System.Environment.CommandLine); /// clp.AddSwitch(@"\?","Show help message"); /// clp.Parse(); /// </code> /// </example> /// <param name="commandLine">The command line to parse when <see cref="Parse"/> is called.</param> public CommandLineParser( string commandLine ) { _commandLine = commandLine; } /// <summary> /// Initializes a new instance of the CommandLineParser class /// </summary> /// <example>For example: /// <code> /// class Class1 /// { /// private bool _bool; /// /// [CommandLineSwitch("bool","Provide boolean value")] /// [CommandLineAlias(new string [] {"boolean","b"})] /// public bool Bool /// { /// get { return _bool; } /// set { this._bool = value; } /// } /// /// [STAThread] /// static void Main(string[] args) /// { /// Class1 c = new Class1(); /// /// CommandLineParser clp = new CommandLineParser(System.Environment.CommandLine,c); /// clp.Parse(); /// /// Console.WriteLine("bool={0}",c.Bool); /// } /// } /// </code> /// </example> /// <param name="commandLine">The command line to parse when <see cref="Parse"/> is called.</param> /// <param name="classForAutoAttributes">The class that contains attributes from which switches are created.</param> public CommandLineParser( string commandLine, object classForAutoAttributes ) { _commandLine = commandLine; Type type = classForAutoAttributes.GetType(); System.Reflection.MemberInfo[] members = type.GetMembers(); for(int i=0; i<members.Length; i++) { object[] attributes = members[i].GetCustomAttributes(false); if(attributes.Length > 0) { CommandLineSwitchRecord rec = null; foreach ( Attribute attribute in attributes ) { if ( attribute is CommandLineSwitchAttribute ) { CommandLineSwitchAttribute switchAttrib = (CommandLineSwitchAttribute) attribute; // Get the property information. We're only handling // properties at the moment! if ( members[i] is System.Reflection.PropertyInfo ) { System.Reflection.PropertyInfo pi = (System.Reflection.PropertyInfo) members[i]; rec = new CommandLineSwitchRecord( switchAttrib.Name, switchAttrib.Description, pi.PropertyType ); // Map in the Get/Set methods. rec.SetMethod = pi.GetSetMethod(); rec.GetMethod = pi.GetGetMethod(); rec.PropertyOwner = classForAutoAttributes; // Can only handle a single switch for each property // (otherwise the parsing of aliases gets silly...) break; } } } // See if any aliases are required. We can only do this after // a switch has been registered and the framework doesn't make // any guarantees about the order of attributes, so we have to // walk the collection a second time. if ( rec != null ) { foreach ( Attribute attribute in attributes ) { if ( attribute is CommandLineAliasAttribute ) { CommandLineAliasAttribute aliasAttrib = (CommandLineAliasAttribute) attribute; foreach(string a in aliasAttrib.Alias) rec.AddAlias(a); } } } // Assuming we have a switch record (that may or may not have // aliases), add it to the collection of switches. if ( rec != null ) { if ( _switches == null ) _switches = new System.Collections.ArrayList(); _switches.Add( rec ); } } } } #endregion } } --- NEW FILE: Adapdev.csproj --- <VisualStudioProject> <CSHARP ProjectType = "Local" ProductVersion = "7.10.3077" SchemaVersion = "2.0" ProjectGuid = "{CC30A321-2569-4B1F-8E1A-781B5509B56D}" > <Build> <Settings ApplicationIcon = "" AssemblyKeyContainerName = "" AssemblyName = "Adapdev" AssemblyOriginatorKeyFile = "" DefaultClientScript = "JScript" DefaultHTMLPageLayout = "Grid" DefaultTargetSchema = "IE50" DelaySign = "false" OutputType = "Library" PreBuildEvent = "" PostBuildEvent = "" RootNamespace = "Adapdev" 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 = "System.Runtime.Remoting" AssemblyName = "System.Runtime.Remoting" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.Runtime.Remoting.dll" /> <Reference Name = "System.Runtime.Serialization.Formatters.Soap" AssemblyName = "System.Runtime.Serialization.Formatters.Soap" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.Runtime.Serialization.Formatters.Soap.dll" /> <Reference Name = "Microsoft.VisualBasic" AssemblyName = "Microsoft.VisualBasic" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\Microsoft.VisualBasic.dll" /> <Reference Name = "log4net" AssemblyName = "log4net" HintPath = "..\..\lib\log4net.dll" /> <Reference Name = "System.EnterpriseServices" AssemblyName = "System.EnterpriseServices" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.EnterpriseServices.dll" /> </References> </Build> <Files> <Include> <File RelPath = "AdapdevAssemblyInfo.cs" Link = "..\AdapdevAssemblyInfo.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "AppDomainManager.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "AssemblyCache.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "AssemblyInfo.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "CommandLineAliasAttribute.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "CommandLineParser.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "CommandLineSwitchAttribute.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "CommandLineSwitchInfo.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "CommandLineSwitchRecord.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "CompositeValidator.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "ICompositeValidator.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "IProgressCallback.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "IValidationRule.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "IValidator.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "LongLivingMarshalByRefObject.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "ObjectComparer.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "ObjectSorter.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "SortableCollectionBase.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Util.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "ValidationResult.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Attributes\SchemaDataRewritableAttribute.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Commands\ICommand.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Cryptography\Crypto.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Cryptography\Decryptor.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Cryptography\DecryptTransformer.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Cryptography\EncryptionAlgorithm.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Cryptography\Encryptor.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Cryptography\EncryptTransformer.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Cryptography\Hasher.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Diagnostics\CPUMeter.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Diagnostics\HiPerfTimer.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Diagnostics\IPerfTimer.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Diagnostics\MillisecondsPerfTimer.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Diagnostics\MinutesPerfTimer.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Diagnostics\PerfTimerFactory.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Diagnostics\SecondsPerfTimer.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Diagnostics\TicksPerfTimer.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "IO\FileUtil.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "IO\FileWatcher.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Mock\SuppliersEntity.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Reflection\ClassAccessor.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Reflection\ClassAccessorCache.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Reflection\FieldAccessor.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Reflection\FieldAccessorException.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Reflection\IValueAccessor.cs" SubType = "... [truncated message content] |
From: Sean M. <int...@us...> - 2005-11-16 07:02:16
|
Update of /cvsroot/adapdev/Adapdev/src/TestBed In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/TestBed Added Files: App.ico AssemblyInfo.cs Class1.cs TestBed.csproj Log Message: --- NEW FILE: App.ico --- (This appears to be a binary file; contents omitted.) --- NEW FILE: TestBed.csproj --- <VisualStudioProject> <CSHARP ProjectType = "Local" ProductVersion = "7.10.3077" SchemaVersion = "2.0" ProjectGuid = "{9E14EB88-A877-47C4-9A51-A9154737BC3B}" > <Build> <Settings ApplicationIcon = "App.ico" AssemblyKeyContainerName = "" AssemblyName = "TestBed" AssemblyOriginatorKeyFile = "" DefaultClientScript = "JScript" DefaultHTMLPageLayout = "Grid" DefaultTargetSchema = "IE50" DelaySign = "false" OutputType = "Exe" PreBuildEvent = "" PostBuildEvent = "" RootNamespace = "TestBed" 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.Cache" Project = "{84F894AC-EFD7-4342-B2A5-CF3EF80E0B1C}" Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" /> <Reference Name = "Adapdev.CodeGen" Project = "{2D8FC662-0244-49F1-8017-DFE73B191017}" 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 = "Adapdev.UnitTest" Project = "{D450E7B3-CF48-421E-8B5E-9526E77E24C6}" Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" /> <Reference Name = "Adapdev.Web" Project = "{49455A1D-1BBB-4356-AB83-E5690726C681}" Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" /> <Reference Name = "Adapdev.Windows.Forms" Project = "{0BE602B6-D67E-414E-B852-A2AC61305E8E}" Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" /> </References> </Build> <Files> <Include> <File RelPath = "App.ico" BuildAction = "Content" /> <File RelPath = "AssemblyInfo.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Class1.cs" SubType = "Code" BuildAction = "Compile" /> </Include> </Files> </CSHARP> </VisualStudioProject> --- NEW FILE: Class1.cs --- using System; using Adapdev.Cryptography; namespace TestBed { /// <summary> /// Summary description for Class1. /// </summary> class Class1 { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main(string[] args) { Crypto.Encrypt("Test", EncryptionAlgorithm.Des); } } } --- NEW FILE: AssemblyInfo.cs --- using System.Reflection; using System.Runtime.CompilerServices; // // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. // [assembly: AssemblyTitle("")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.*")] // // In order to sign your assembly you must specify a key to use. Refer to the // Microsoft .NET Framework documentation for more information on assembly signing. // // Use the attributes below to control which key is used for signing. // // Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used. // (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be // relative to the project output directory which is // %Project Directory%\obj\<configuration>. For example, if your KeyFile is // located in the project directory, you would specify the AssemblyKeyFile // attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. // [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] [assembly: AssemblyKeyName("")] |
From: Sean M. <int...@us...> - 2005-11-16 07:02:16
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.Web In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.Web Added Files: Adapdev.Web.csproj Log Message: --- NEW FILE: Adapdev.Web.csproj --- <VisualStudioProject> <CSHARP ProjectType = "Local" ProductVersion = "7.10.3077" SchemaVersion = "2.0" ProjectGuid = "{49455A1D-1BBB-4356-AB83-E5690726C681}" > <Build> <Settings ApplicationIcon = "" AssemblyKeyContainerName = "" AssemblyName = "Adapdev.Web" AssemblyOriginatorKeyFile = "" DefaultClientScript = "JScript" DefaultHTMLPageLayout = "Grid" DefaultTargetSchema = "IE50" DelaySign = "false" OutputType = "Library" PreBuildEvent = "" PostBuildEvent = "" RootNamespace = "Adapdev.Web" 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 = "System.Web" AssemblyName = "System.Web" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.Web.dll" /> <Reference Name = "log4net" AssemblyName = "log4net" HintPath = "..\..\lib\log4net.dll" /> </References> </Build> <Files> <Include> <File RelPath = "AdapdevAssemblyInfo.cs" Link = "..\AdapdevAssemblyInfo.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Html\HtmlAttribute.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Html\HtmlComment.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Html\HtmlDocument.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Html\HtmlDomainTreeParser.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Html\HtmlElement.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Html\HtmlElementClose.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Html\HtmlHelper.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Html\HtmlLinearParser.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Html\HtmlNode.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Html\HtmlParser.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Html\HtmlScript.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Html\HtmlStyleSheet.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Html\HtmlText.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Html\SgmlComment.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Html\XPath\crc32.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Html\XPath\Header.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Html\XPath\HtmlAttribute.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Html\XPath\HtmlDocument.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Html\XPath\HtmlEntity.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Html\XPath\HtmlNode.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Html\XPath\HtmlNodeNavigator.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Html\XPath\HtmlWeb.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Html\XPath\MixedCodeDocument.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Html\XPath\ParseReader.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Html\XPath\readme.txt" BuildAction = "Content" /> <File RelPath = "Html\XPath\tools.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Rss\atom.xsd" BuildAction = "Content" /> <File RelPath = "Rss\atom.xsx" DependentUpon = "atom.xsd" BuildAction = "None" /> <File RelPath = "Rss\IPersistentManager.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Rss\opml.xsd" BuildAction = "Content" /> <File RelPath = "Rss\opml.xsx" DependentUpon = "opml.xsd" BuildAction = "None" /> <File RelPath = "Rss\opmlbody.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Rss\opmldocument.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Rss\opmlhead.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Rss\opmloutline.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Rss\rss.xsd" BuildAction = "Content" /> <File RelPath = "Rss\rss.xsx" DependentUpon = "rss.xsd" BuildAction = "None" /> <File RelPath = "Rss\RssCacheManager.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Rss\RssCacheManager.resx" DependentUpon = "RssCacheManager.cs" BuildAction = "EmbeddedResource" /> <File RelPath = "Rss\rsschannel.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Rss\rsscloud.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Rss\rssenclosure.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Rss\rssguid.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Rss\rssimage.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Rss\rssitem.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Rss\RssReader.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Rss\rsssource.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Rss\rsstextinput.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Sgml\SgmlParser.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Sgml\SgmlReader.cs" SubType = "Code" BuildAction = "Compile" /> </Include> </Files> </CSHARP> </VisualStudioProject> |
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.Windows.Forms In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.Windows.Forms Added Files: Adapdev.Windows.Forms.csproj DatabaseExplorer.cs DatabaseExplorer.resx DatabaseSetting.cs DatabaseWizard.cs DatabaseWizard.resx DatabaseWizardForm.cs DatabaseWizardForm.resx FileTreeView.cs FileTreeView.resx IconListManager.cs IconReader.cs NewFolderForm.cs NewFolderForm.resx Settings.cs SmartTreeView.cs SmartTreeView.resx SmoothProgressBar.cs SmoothProgressBar.resx SystemInfo.cs SystemType.cs Log Message: --- NEW FILE: SmoothProgressBar.resx --- <?xml version="1.0" encoding="utf-8"?> <root> <!-- Microsoft ResX Schema Version 1.3 The primary goals of this format is to allow a simple XML format that is mostly human readable. The generation and parsing of the various data types are done through the TypeConverter classes associated with the data types. Example: ... ado.net/XML headers & schema ... <resheader name="resmimetype">text/microsoft-resx</resheader> <resheader name="version">1.3</resheader> <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader> <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader> <data name="Name1">this is my long string</data> <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data> <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64"> [base64 mime encoded serialized .NET Framework object] </data> <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64"> [base64 mime encoded string representing a byte array form of the .NET Framework object] </data> There are any number of "resheader" rows that contain simple name/value pairs. Each data row contains a name, and value. The row also contains a type or mimetype. Type corresponds to a .NET class that support text/value conversion through the TypeConverter architecture. Classes that don't support this are serialized and stored with the mimetype set. The mimetype is used for serialized objects, and tells the ResXResourceReader how to depersist the object. This is currently not extensible. For a given mimetype the value must be set accordingly: Note - application/x-microsoft.net.object.binary.base64 is the format that the ResXResourceWriter will generate, however the reader can read any of the formats listed below. mimetype: application/x-microsoft.net.object.binary.base64 value : The object must be serialized with : System.Serialization.Formatters.Binary.BinaryFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.soap.base64 value : The object must be serialized with : System.Runtime.Serialization.Formatters.Soap.SoapFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.bytearray.base64 value : The object must be serialized into a byte array : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xsd:element name="root" msdata:IsDataSet="true"> <xsd:complexType> <xsd:choice maxOccurs="unbounded"> <xsd:element name="data"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" /> <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" /> <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" /> </xsd:complexType> </xsd:element> <xsd:element name="resheader"> <xsd:complexType> <xsd:sequence> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> </xsd:sequence> <xsd:attribute name="name" type="xsd:string" use="required" /> </xsd:complexType> </xsd:element> </xsd:choice> </xsd:complexType> </xsd:element> </xsd:schema> <resheader name="resmimetype"> <value>text/microsoft-resx</value> </resheader> <resheader name="version"> <value>1.3</value> </resheader> <resheader name="reader"> <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <resheader name="writer"> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> </resheader> <data name="$this.Name"> <value>SmoothProgressBar</value> </data> </root> --- NEW FILE: NewFolderForm.cs --- using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.IO; using System.Windows.Forms; namespace Adapdev.Windows.Forms { /// <summary> /// Summary description for SingleInputForm. /// </summary> internal class NewFolderForm : System.Windows.Forms.Form { private System.Windows.Forms.Label lblQuestion; private System.Windows.Forms.TextBox txtInput; private System.Windows.Forms.Button btnCancel; private System.Windows.Forms.Button btnSubmit; private System.Windows.Forms.Label lblError; private SystemInfo info = null; internal NewFolderForm(SystemInfo info) { // // Required for Windows Form Designer support // InitializeComponent(); this.info = info; } /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.lblQuestion = new System.Windows.Forms.Label(); this.txtInput = new System.Windows.Forms.TextBox(); this.btnCancel = new System.Windows.Forms.Button(); this.btnSubmit = new System.Windows.Forms.Button(); this.lblError = new System.Windows.Forms.Label(); this.SuspendLayout(); // // lblQuestion // this.lblQuestion.Location = new System.Drawing.Point(8, 8); this.lblQuestion.Name = "lblQuestion"; this.lblQuestion.Size = new System.Drawing.Size(168, 24); this.lblQuestion.TabIndex = 0; this.lblQuestion.Text = "Enter the new folder to create:"; // // txtInput // this.txtInput.Location = new System.Drawing.Point(192, 8); this.txtInput.Name = "txtInput"; this.txtInput.Size = new System.Drawing.Size(184, 20); this.txtInput.TabIndex = 1; this.txtInput.Text = ""; // // btnCancel // this.btnCancel.Location = new System.Drawing.Point(304, 40); this.btnCancel.Name = "btnCancel"; this.btnCancel.TabIndex = 2; this.btnCancel.Text = "Cancel"; this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click); // // btnSubmit // this.btnSubmit.Location = new System.Drawing.Point(216, 40); this.btnSubmit.Name = "btnSubmit"; this.btnSubmit.TabIndex = 3; this.btnSubmit.Text = "Submit"; this.btnSubmit.Click += new System.EventHandler(this.btnSubmit_Click); // // lblError // this.lblError.ForeColor = System.Drawing.Color.Red; this.lblError.Location = new System.Drawing.Point(8, 32); this.lblError.Name = "lblError"; this.lblError.Size = new System.Drawing.Size(168, 40); this.lblError.TabIndex = 4; // // NewFolderForm // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(384, 70); this.Controls.Add(this.lblError); this.Controls.Add(this.btnSubmit); this.Controls.Add(this.btnCancel); this.Controls.Add(this.txtInput); this.Controls.Add(this.lblQuestion); this.Name = "NewFolderForm"; this.Text = "New Folder Form"; this.ResumeLayout(false); } #endregion private void btnSubmit_Click(object sender, System.EventArgs e) { if(this.txtInput.Text.Length > 0) { this.lblError.Text = ""; string dir = ""; if(info.Type == SystemType.Directory) { dir = System.IO.Path.Combine(info.Path, this.txtInput.Text); } else { dir = Path.Combine(info.Path.Substring(0, info.Path.LastIndexOf("\\")), this.txtInput.Text); } if(!Directory.Exists(dir)) { Directory.CreateDirectory(dir); this.Close(); } else { this.lblError.Text = this.txtInput.Text + " already exists."; } } } private void btnCancel_Click(object sender, System.EventArgs e) { this.Close(); } } } --- NEW FILE: IconReader.cs --- // Copyright Paul Ingles - http://www.codeproject.com/csharp/fileicon.asp using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Data; using System.Runtime.InteropServices; namespace Adapdev.Windows.Forms { /// <summary> /// Provides static methods to read system icons for both folders and files. /// </summary> /// <example> /// <code>IconReader.GetFileIcon("c:\\general.xls");</code> /// </example> public class IconReader { /// <summary> /// Options to specify the size of icons to return. /// </summary> public enum IconSize { /// <summary> /// Specify large icon - 32 pixels by 32 pixels. /// </summary> Large = 0, /// <summary> /// Specify small icon - 16 pixels by 16 pixels. /// </summary> Small = 1 } /// <summary> /// Options to specify whether folders should be in the open or closed state. /// </summary> public enum FolderType { /// <summary> /// Specify open folder. /// </summary> Open = 0, /// <summary> /// Specify closed folder. /// </summary> Closed = 1 } /// <summary> /// Returns an icon for a given file - indicated by the name parameter. /// </summary> /// <param name="name">Pathname for file.</param> /// <param name="size">Large or small</param> /// <param name="linkOverlay">Whether to include the link icon</param> /// <returns>System.Drawing.Icon</returns> public static System.Drawing.Icon GetFileIcon(string name, IconSize size, bool linkOverlay) { Shell32.SHFILEINFO shfi = new Shell32.SHFILEINFO(); uint flags = Shell32.SHGFI_ICON | Shell32.SHGFI_USEFILEATTRIBUTES; if (true == linkOverlay) flags += Shell32.SHGFI_LINKOVERLAY; /* Check the size specified for return. */ if (IconSize.Small == size) { flags += Shell32.SHGFI_SMALLICON ; } else { flags += Shell32.SHGFI_LARGEICON ; } Shell32.SHGetFileInfo( name, Shell32.FILE_ATTRIBUTE_NORMAL, ref shfi, (uint) System.Runtime.InteropServices.Marshal.SizeOf(shfi), flags ); // Copy (clone) the returned icon to a new object, thus allowing us to clean-up properly System.Drawing.Icon icon = (System.Drawing.Icon)System.Drawing.Icon.FromHandle(shfi.hIcon).Clone(); User32.DestroyIcon( shfi.hIcon ); // Cleanup return icon; } /// <summary> /// Used to access system folder icons. /// </summary> /// <param name="size">Specify large or small icons.</param> /// <param name="folderType">Specify open or closed FolderType.</param> /// <returns>System.Drawing.Icon</returns> public static System.Drawing.Icon GetFolderIcon( IconSize size, FolderType folderType ) { // Need to add size check, although errors generated at present! uint flags = Shell32.SHGFI_ICON | Shell32.SHGFI_USEFILEATTRIBUTES; if (FolderType.Open == folderType) { flags += Shell32.SHGFI_OPENICON; } if (IconSize.Small == size) { flags += Shell32.SHGFI_SMALLICON; } else { flags += Shell32.SHGFI_LARGEICON; } // Get the folder icon Shell32.SHFILEINFO shfi = new Shell32.SHFILEINFO(); Shell32.SHGetFileInfo( null, Shell32.FILE_ATTRIBUTE_DIRECTORY, ref shfi, (uint) System.Runtime.InteropServices.Marshal.SizeOf(shfi), flags ); System.Drawing.Icon.FromHandle(shfi.hIcon); // Load the icon from an HICON handle // Now clone the icon, so that it can be successfully stored in an ImageList System.Drawing.Icon icon = (System.Drawing.Icon)System.Drawing.Icon.FromHandle(shfi.hIcon).Clone(); User32.DestroyIcon( shfi.hIcon ); // Cleanup return icon; } } /// <summary> /// Wraps necessary Shell32.dll structures and functions required to retrieve Icon Handles using SHGetFileInfo. Code /// courtesy of MSDN Cold Rooster Consulting case study. /// </summary> /// // This code has been left largely untouched from that in the CRC example. The main changes have been moving // the icon reading code over to the IconReader type. public class Shell32 { public const int MAX_PATH = 256; [StructLayout(LayoutKind.Sequential)] public struct SHITEMID { public ushort cb; [MarshalAs(UnmanagedType.LPArray)] public byte[] abID; } [StructLayout(LayoutKind.Sequential)] public struct ITEMIDLIST { public SHITEMID mkid; } [StructLayout(LayoutKind.Sequential)] public struct BROWSEINFO { public IntPtr hwndOwner; public IntPtr pidlRoot; public IntPtr pszDisplayName; [MarshalAs(UnmanagedType.LPTStr)] public string lpszTitle; public uint ulFlags; public IntPtr lpfn; public int lParam; public IntPtr iImage; } // Browsing for directory. public const uint BIF_RETURNONLYFSDIRS = 0x0001; public const uint BIF_DONTGOBELOWDOMAIN = 0x0002; public const uint BIF_STATUSTEXT = 0x0004; public const uint BIF_RETURNFSANCESTORS = 0x0008; public const uint BIF_EDITBOX = 0x0010; public const uint BIF_VALIDATE = 0x0020; public const uint BIF_NEWDIALOGSTYLE = 0x0040; public const uint BIF_USENEWUI = (BIF_NEWDIALOGSTYLE | BIF_EDITBOX); public const uint BIF_BROWSEINCLUDEURLS = 0x0080; public const uint BIF_BROWSEFORCOMPUTER = 0x1000; public const uint BIF_BROWSEFORPRINTER = 0x2000; public const uint BIF_BROWSEINCLUDEFILES = 0x4000; public const uint BIF_SHAREABLE = 0x8000; [StructLayout(LayoutKind.Sequential)] public struct SHFILEINFO { public const int NAMESIZE = 80; public IntPtr hIcon; public int iIcon; public uint dwAttributes; [MarshalAs(UnmanagedType.ByValTStr, SizeConst=MAX_PATH)] public string szDisplayName; [MarshalAs(UnmanagedType.ByValTStr, SizeConst=NAMESIZE)] public string szTypeName; }; public const uint SHGFI_ICON = 0x000000100; // get icon public const uint SHGFI_DISPLAYNAME = 0x000000200; // get display name public const uint SHGFI_TYPENAME = 0x000000400; // get type name public const uint SHGFI_ATTRIBUTES = 0x000000800; // get attributes public const uint SHGFI_ICONLOCATION = 0x000001000; // get icon location public const uint SHGFI_EXETYPE = 0x000002000; // return exe type public const uint SHGFI_SYSICONINDEX = 0x000004000; // get system icon index public const uint SHGFI_LINKOVERLAY = 0x000008000; // put a link overlay on icon public const uint SHGFI_SELECTED = 0x000010000; // show icon in selected state public const uint SHGFI_ATTR_SPECIFIED = 0x000020000; // get only specified attributes public const uint SHGFI_LARGEICON = 0x000000000; // get large icon public const uint SHGFI_SMALLICON = 0x000000001; // get small icon public const uint SHGFI_OPENICON = 0x000000002; // get open icon public const uint SHGFI_SHELLICONSIZE = 0x000000004; // get shell size icon public const uint SHGFI_PIDL = 0x000000008; // pszPath is a pidl public const uint SHGFI_USEFILEATTRIBUTES = 0x000000010; // use passed dwFileAttribute public const uint SHGFI_ADDOVERLAYS = 0x000000020; // apply the appropriate overlays public const uint SHGFI_OVERLAYINDEX = 0x000000040; // Get the index of the overlay public const uint FILE_ATTRIBUTE_DIRECTORY = 0x00000010; public const uint FILE_ATTRIBUTE_NORMAL = 0x00000080; [DllImport("Shell32.dll")] public static extern IntPtr SHGetFileInfo( string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbFileInfo, uint uFlags ); } /// <summary> /// Wraps necessary functions imported from User32.dll. Code courtesy of MSDN Cold Rooster Consulting example. /// </summary> public class User32 { /// <summary> /// Provides access to function required to delete handle. This method is used internally /// and is not required to be called separately. /// </summary> /// <param name="hIcon">Pointer to icon handle.</param> /// <returns>N/A</returns> [DllImport("User32.dll")] public static extern int DestroyIcon( IntPtr hIcon ); } } --- NEW FILE: Adapdev.Windows.Forms.csproj --- <VisualStudioProject> <CSHARP ProjectType = "Local" ProductVersion = "7.10.3077" SchemaVersion = "2.0" ProjectGuid = "{0BE602B6-D67E-414E-B852-A2AC61305E8E}" > <Build> <Settings ApplicationIcon = "" AssemblyKeyContainerName = "" AssemblyName = "Adapdev.Windows.Forms" AssemblyOriginatorKeyFile = "" DefaultClientScript = "JScript" DefaultHTMLPageLayout = "Grid" DefaultTargetSchema = "IE50" DelaySign = "false" OutputType = "Library" PreBuildEvent = "" PostBuildEvent = "" RootNamespace = "Adapdev.Windows.Forms" 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 = "System.Windows.Forms" AssemblyName = "System.Windows.Forms" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.Windows.Forms.dll" /> <Reference Name = "System.Drawing" AssemblyName = "System.Drawing" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.Drawing.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 = "log4net" AssemblyName = "log4net" HintPath = "..\..\lib\log4net.dll" /> </References> </Build> <Files> <Include> <File RelPath = "AdapdevAssemblyInfo.cs" Link = "..\AdapdevAssemblyInfo.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "DatabaseExplorer.cs" SubType = "UserControl" BuildAction = "Compile" /> <File RelPath = "DatabaseExplorer.resx" DependentUpon = "DatabaseExplorer.cs" BuildAction = "EmbeddedResource" /> <File RelPath = "DatabaseSetting.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "DatabaseWizard.cs" SubType = "UserControl" BuildAction = "Compile" /> <File RelPath = "DatabaseWizard.resx" DependentUpon = "DatabaseWizard.cs" BuildAction = "EmbeddedResource" /> <File RelPath = "DatabaseWizardForm.cs" SubType = "Form" BuildAction = "Compile" /> <File RelPath = "DatabaseWizardForm.resx" DependentUpon = "DatabaseWizardForm.cs" BuildAction = "EmbeddedResource" /> <File RelPath = "FileTreeView.cs" SubType = "Component" BuildAction = "Compile" /> <File RelPath = "FileTreeView.resx" DependentUpon = "FileTreeView.cs" BuildAction = "EmbeddedResource" /> <File RelPath = "IconListManager.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "IconReader.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "NewFolderForm.cs" SubType = "Form" BuildAction = "Compile" /> <File RelPath = "NewFolderForm.resx" DependentUpon = "NewFolderForm.cs" BuildAction = "EmbeddedResource" /> <File RelPath = "Settings.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "SmartTreeView.cs" SubType = "Component" BuildAction = "Compile" /> <File RelPath = "SmartTreeView.resx" DependentUpon = "SmartTreeView.cs" BuildAction = "EmbeddedResource" /> <File RelPath = "SmoothProgressBar.cs" SubType = "UserControl" BuildAction = "Compile" /> <File RelPath = "SmoothProgressBar.resx" DependentUpon = "SmoothProgressBar.cs" BuildAction = "EmbeddedResource" /> <File RelPath = "SystemInfo.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "SystemType.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Commands\AbstractGUICommand.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Commands\IGUICommand.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Commands\ShowErrorMessageCommand.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Commands\vssver.scc" BuildAction = "None" /> <File RelPath = "Progress\ProgressWindow.cs" SubType = "Form" BuildAction = "Compile" /> <File RelPath = "Progress\ProgressWindow.resx" DependentUpon = "ProgressWindow.cs" BuildAction = "EmbeddedResource" /> </Include> </Files> </CSHARP> </VisualStudioProject> --- NEW FILE: IconListManager.cs --- // Copyright Paul Ingles - http://www.codeproject.com/csharp/fileicon.asp using System; using System.Collections; using System.Windows.Forms; namespace Adapdev.Windows.Forms { /// <summary> /// Maintains a list of currently added file extensions /// </summary> public class IconListManager { private Hashtable _extensionList = new Hashtable(); private System.Collections.ArrayList _imageLists = new ArrayList(); //will hold ImageList objects private IconReader.IconSize _iconSize; bool ManageBothSizes = false; //flag, used to determine whether to create two ImageLists. /// <summary> /// Creates an instance of <c>IconListManager</c> that will add icons to a single <c>ImageList</c> using the /// specified <c>IconSize</c>. /// </summary> /// <param name="imageList"><c>ImageList</c> to add icons to.</param> /// <param name="iconSize">Size to use (either 32 or 16 pixels).</param> public IconListManager(System.Windows.Forms.ImageList imageList, IconReader.IconSize iconSize ) { // Initialise the members of the class that will hold the image list we're // targeting, as well as the icon size (32 or 16) _imageLists.Add( imageList ); _iconSize = iconSize; } /// <summary> /// Creates an instance of IconListManager that will add icons to two <c>ImageList</c> types. The two /// image lists are intended to be one for large icons, and the other for small icons. /// </summary> /// <param name="smallImageList">The <c>ImageList</c> that will hold small icons.</param> /// <param name="largeImageList">The <c>ImageList</c> that will hold large icons.</param> public IconListManager(System.Windows.Forms.ImageList smallImageList, System.Windows.Forms.ImageList largeImageList ) { //add both our image lists _imageLists.Add( smallImageList ); _imageLists.Add( largeImageList ); //set flag ManageBothSizes = true; } /// <summary> /// Used internally, adds the extension to the hashtable, so that its value can then be returned. /// </summary> /// <param name="Extension"><c>String</c> of the file's extension.</param> /// <param name="ImageListPosition">Position of the extension in the <c>ImageList</c>.</param> private void AddExtension( string Extension, int ImageListPosition ) { _extensionList.Add( Extension, ImageListPosition ); } /// <summary> /// Called publicly to add a file's icon to the ImageList. /// </summary> /// <param name="filePath">Full path to the file.</param> /// <returns>Integer of the icon's position in the ImageList</returns> public int AddFileIcon( string filePath ) { // Check if the file exists, otherwise, throw exception. if (!System.IO.File.Exists( filePath )) throw new System.IO.FileNotFoundException("File does not exist"); // Split it down so we can get the extension string[] splitPath = filePath.Split(new Char[] {'.'}); string extension = (string)splitPath.GetValue( splitPath.GetUpperBound(0) ); //Check that we haven't already got the extension, if we have, then //return back its index if (_extensionList.ContainsKey( extension.ToUpper() )) { return (int)_extensionList[extension.ToUpper()]; //return existing index } else { // It's not already been added, so add it and record its position. int pos = ((ImageList)_imageLists[0]).Images.Count; //store current count -- new item's index if (ManageBothSizes == true) { //managing two lists, so add it to small first, then large ((ImageList)_imageLists[0]).Images.Add( IconReader.GetFileIcon( filePath, IconReader.IconSize.Small, false ) ); ((ImageList)_imageLists[1]).Images.Add( IconReader.GetFileIcon( filePath, IconReader.IconSize.Large, false ) ); } else { //only doing one size, so use IconSize as specified in _iconSize. ((ImageList)_imageLists[0]).Images.Add( IconReader.GetFileIcon( filePath, _iconSize, false ) ); //add to image list } AddExtension( extension.ToUpper(), pos ); // add to hash table return pos; } } /// <summary> /// Clears any <c>ImageLists</c> that <c>IconListManager</c> is managing. /// </summary> public void ClearLists() { foreach( ImageList imageList in _imageLists ) { imageList.Images.Clear(); //clear current imagelist. } _extensionList.Clear(); //empty hashtable of entries too. } } } --- NEW FILE: Settings.cs --- namespace Adapdev.Windows.Forms { using System; using System.Collections; /// <summary> /// Summary description for Settings. /// </summary> /// [Serializable] public class Settings { private ArrayList dbsettings = new ArrayList(); public ArrayList DatabaseSettings { get { return dbsettings; } } public void AddDatabaseSetting(DatabaseSetting ds) { this.dbsettings.Add(ds); } } } --- NEW FILE: DatabaseWizard.cs --- using System; using System.Collections; using System.Data; using System.Windows.Forms; using Adapdev.Data; namespace Adapdev.Windows.Forms { /// <summary> /// Summary description for DatabaseWizard. /// </summary> public class DatabaseWizard : System.Windows.Forms.UserControl { private System.Windows.Forms.OpenFileDialog openFileDialog1; private System.Windows.Forms.TextBox tbConnectionString; private System.Windows.Forms.Label lblConnection; private System.Windows.Forms.Button btnNewDatabase; private System.Windows.Forms.Button btnTestConnection; private System.ComponentModel.IContainer components; private System.Windows.Forms.ImageList imageList1; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.Button btnOpenFile; private System.Windows.Forms.TextBox tbConnectionName; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label lblName; private System.Windows.Forms.TextBox tbName; private System.Windows.Forms.Label lblPassword; private System.Windows.Forms.Label lblUsername; private System.Windows.Forms.Label lblLocation; private System.Windows.Forms.TextBox tbPassword; private System.Windows.Forms.TextBox tbUsername; private System.Windows.Forms.TextBox tbLocation; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.GroupBox groupBox3; private System.Windows.Forms.TreeView tvConnectionTypes; private readonly string AllFilesMask = "All files (*.*)|*.*"; private readonly int iconDatabase = 0; private readonly int iconDisabled = 3; private readonly int iconProvider = 2; private readonly int iconSelected = 1; private DbConnectionProvider _connectionProvider = null; private System.Windows.Forms.Label lblFilter; private System.Windows.Forms.TextBox tbFilter; private ProviderConfig _providersConfig = null; public DatabaseWizard() { // This call is required by the Windows.Forms Form Designer. InitializeComponent(); // Hack, since VS.NET IDE bombs out when loading // this control since it can't find the // ProviderConfig.xml file try{ this._providersConfig = new ProviderConfig(); this.BuildConnectionsTree(this.tvConnectionTypes); this.SetGUIProperties(null); } catch(Exception){} // TODO: Add any initialization after the InitializeComponent call } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(DatabaseWizard)); this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog(); this.tbConnectionString = new System.Windows.Forms.TextBox(); this.lblConnection = new System.Windows.Forms.Label(); this.btnNewDatabase = new System.Windows.Forms.Button(); this.btnTestConnection = new System.Windows.Forms.Button(); this.imageList1 = new System.Windows.Forms.ImageList(this.components); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.tbFilter = new System.Windows.Forms.TextBox(); this.lblFilter = new System.Windows.Forms.Label(); this.tbLocation = new System.Windows.Forms.TextBox(); this.btnOpenFile = new System.Windows.Forms.Button(); this.lblName = new System.Windows.Forms.Label(); this.tbName = new System.Windows.Forms.TextBox(); this.lblPassword = new System.Windows.Forms.Label(); this.lblUsername = new System.Windows.Forms.Label(); this.lblLocation = new System.Windows.Forms.Label(); this.tbPassword = new System.Windows.Forms.TextBox(); this.tbUsername = new System.Windows.Forms.TextBox(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.tbConnectionName = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.groupBox3 = new System.Windows.Forms.GroupBox(); this.tvConnectionTypes = new System.Windows.Forms.TreeView(); this.groupBox1.SuspendLayout(); this.groupBox2.SuspendLayout(); this.groupBox3.SuspendLayout(); this.SuspendLayout(); // // openFileDialog1 // this.openFileDialog1.RestoreDirectory = true; // // tbConnectionString // this.tbConnectionString.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.tbConnectionString.Location = new System.Drawing.Point(112, 256); this.tbConnectionString.Name = "tbConnectionString"; this.tbConnectionString.ReadOnly = true; this.tbConnectionString.Size = new System.Drawing.Size(424, 20); this.tbConnectionString.TabIndex = 9; this.tbConnectionString.Text = ""; // // lblConnection // this.lblConnection.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.lblConnection.Location = new System.Drawing.Point(8, 256); this.lblConnection.Name = "lblConnection"; this.lblConnection.Size = new System.Drawing.Size(104, 23); this.lblConnection.TabIndex = 40; this.lblConnection.Text = "Connection String:"; this.lblConnection.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // btnNewDatabase // this.btnNewDatabase.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.btnNewDatabase.Location = new System.Drawing.Point(112, 280); this.btnNewDatabase.Name = "btnNewDatabase"; this.btnNewDatabase.Size = new System.Drawing.Size(56, 23); this.btnNewDatabase.TabIndex = 10; this.btnNewDatabase.Text = "New"; this.btnNewDatabase.Click += new System.EventHandler(this.btnNewDatabase_Click); // // btnTestConnection // this.btnTestConnection.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.btnTestConnection.Location = new System.Drawing.Point(176, 280); this.btnTestConnection.Name = "btnTestConnection"; this.btnTestConnection.Size = new System.Drawing.Size(96, 23); this.btnTestConnection.TabIndex = 11; this.btnTestConnection.Text = "Test Connection"; this.btnTestConnection.Click += new System.EventHandler(this.btnTestConnection_Click); // // imageList1 // this.imageList1.ColorDepth = System.Windows.Forms.ColorDepth.Depth24Bit; this.imageList1.ImageSize = new System.Drawing.Size(16, 16); this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream"))); this.imageList1.TransparentColor = System.Drawing.Color.Transparent; // // groupBox1 // this.groupBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Right))); this.groupBox1.Controls.Add(this.tbFilter); this.groupBox1.Controls.Add(this.lblFilter); this.groupBox1.Controls.Add(this.tbLocation); this.groupBox1.Controls.Add(this.btnOpenFile); this.groupBox1.Controls.Add(this.lblName); this.groupBox1.Controls.Add(this.tbName); this.groupBox1.Controls.Add(this.lblPassword); this.groupBox1.Controls.Add(this.lblUsername); this.groupBox1.Controls.Add(this.lblLocation); this.groupBox1.Controls.Add(this.tbPassword); this.groupBox1.Controls.Add(this.tbUsername); this.groupBox1.FlatStyle = System.Windows.Forms.FlatStyle.System; this.groupBox1.Location = new System.Drawing.Point(248, 64); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(288, 184); this.groupBox1.TabIndex = 3; this.groupBox1.TabStop = false; this.groupBox1.Text = "Enter the Database Properties"; // // tbFilter // this.tbFilter.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.tbFilter.Location = new System.Drawing.Point(112, 152); this.tbFilter.Name = "tbFilter"; this.tbFilter.Size = new System.Drawing.Size(136, 20); this.tbFilter.TabIndex = 7; this.tbFilter.Text = ""; this.tbFilter.TextChanged += new System.EventHandler(this.tbFilter_TextChanged); // // lblFilter // this.lblFilter.Location = new System.Drawing.Point(8, 152); this.lblFilter.Name = "lblFilter"; this.lblFilter.TabIndex = 0; this.lblFilter.Text = "Schema Filter:"; this.lblFilter.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // tbLocation // this.tbLocation.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.tbLocation.Location = new System.Drawing.Point(112, 24); this.tbLocation.Name = "tbLocation"; this.tbLocation.Size = new System.Drawing.Size(136, 20); this.tbLocation.TabIndex = 3; this.tbLocation.Text = ""; this.tbLocation.TextChanged += new System.EventHandler(this.tbLocation_TextChanged); // // btnOpenFile // this.btnOpenFile.Location = new System.Drawing.Point(248, 24); this.btnOpenFile.Name = "btnOpenFile"; this.btnOpenFile.Size = new System.Drawing.Size(24, 20); this.btnOpenFile.TabIndex = 4; this.btnOpenFile.Text = "..."; this.btnOpenFile.Click += new System.EventHandler(this.btnOpenFile_Click); // // lblName // this.lblName.Location = new System.Drawing.Point(8, 56); this.lblName.Name = "lblName"; this.lblName.TabIndex = 0; this.lblName.Text = "Name: "; this.lblName.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // tbName // this.tbName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.tbName.Location = new System.Drawing.Point(112, 56); this.tbName.Name = "tbName"; this.tbName.Size = new System.Drawing.Size(136, 20); this.tbName.TabIndex = 4; this.tbName.Text = ""; this.tbName.TextChanged += new System.EventHandler(this.tbName_TextChanged); // // lblPassword // this.lblPassword.Location = new System.Drawing.Point(8, 120); this.lblPassword.Name = "lblPassword"; this.lblPassword.TabIndex = 0; this.lblPassword.Text = "Password: "; this.lblPassword.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // lblUsername // this.lblUsername.Location = new System.Drawing.Point(8, 88); this.lblUsername.Name = "lblUsername"; this.lblUsername.TabIndex = 0; this.lblUsername.Text = "Username: "; this.lblUsername.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // lblLocation // this.lblLocation.Location = new System.Drawing.Point(8, 24); this.lblLocation.Name = "lblLocation"; this.lblLocation.TabIndex = 0; this.lblLocation.Text = "Server / Location: "; this.lblLocation.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // tbPassword // this.tbPassword.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.tbPassword.Location = new System.Drawing.Point(112, 120); this.tbPassword.Name = "tbPassword"; this.tbPassword.Size = new System.Drawing.Size(136, 20); this.tbPassword.TabIndex = 6; this.tbPassword.Text = ""; this.tbPassword.TextChanged += new System.EventHandler(this.tbPassword_TextChanged); // // tbUsername // this.tbUsername.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.tbUsername.Location = new System.Drawing.Point(112, 88); this.tbUsername.Name = "tbUsername"; this.tbUsername.Size = new System.Drawing.Size(136, 20); this.tbUsername.TabIndex = 5; this.tbUsername.Text = ""; this.tbUsername.TextChanged += new System.EventHandler(this.tbUsername_TextChanged); // // groupBox2 // this.groupBox2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.groupBox2.Controls.Add(this.tbConnectionName); this.groupBox2.Controls.Add(this.label1); this.groupBox2.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.groupBox2.Location = new System.Drawing.Point(248, 8); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(288, 48); this.groupBox2.TabIndex = 1; this.groupBox2.TabStop = false; this.groupBox2.Text = "Connection Settings"; // // tbConnectionName // this.tbConnectionName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.tbConnectionName.Location = new System.Drawing.Point(112, 16); this.tbConnectionName.Name = "tbConnectionName"; this.tbConnectionName.Size = new System.Drawing.Size(168, 20); this.tbConnectionName.TabIndex = 2; this.tbConnectionName.Text = ""; // // label1 // this.label1.Location = new System.Drawing.Point(8, 16); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(88, 23); this.label1.TabIndex = 0; this.label1.Text = "Name: "; this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // groupBox3 // this.groupBox3.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.groupBox3.Controls.Add(this.tvConnectionTypes); this.groupBox3.Location = new System.Drawing.Point(0, 8); this.groupBox3.Name = "groupBox3"; this.groupBox3.Size = new System.Drawing.Size(240, 240); this.groupBox3.TabIndex = 1; this.groupBox3.TabStop = false; this.groupBox3.Text = "Select the connection type:"; // // tvConnectionTypes // this.tvConnectionTypes.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.tvConnectionTypes.FullRowSelect = true; this.tvConnectionTypes.ImageIndex = 2; this.tvConnectionTypes.ImageList = this.imageList1; this.tvConnectionTypes.Location = new System.Drawing.Point(8, 16); this.tvConnectionTypes.Name = "tvConnectionTypes"; this.tvConnectionTypes.SelectedImageIndex = 1; this.tvConnectionTypes.Size = new System.Drawing.Size(224, 208); this.tvConnectionTypes.TabIndex = 1; this.tvConnectionTypes.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.tvConnectionTypes_AfterSelect); // // DatabaseWizard // this.Controls.Add(this.groupBox3); this.Controls.Add(this.btnTestConnection); this.Controls.Add(this.btnNewDatabase); this.Controls.Add(this.lblConnection); this.Controls.Add(this.tbConnectionString); this.Controls.Add(this.groupBox1); this.Controls.Add(this.groupBox2); this.Name = "DatabaseWizard"; this.Size = new System.Drawing.Size(536, 304); this.groupBox1.ResumeLayout(false); this.groupBox2.ResumeLayout(false); this.groupBox3.ResumeLayout(false); this.ResumeLayout(false); } #endregion #region Form Public Properties public string DbLocation { get { return this.tbLocation.Text; } set { this.tbLocation.Text = value; } } public string DbName { get { return this.tbName.Text; } set { this.tbName.Text = value; } } public string Username { get { return this.tbUsername.Text; } set { this.tbUsername.Text = value; } } public string Password { get { return this.tbPassword.Text; } set { this.tbPassword.Text = value; } } public string Filter { get { return this.tbFilter.Text; } set { this.tbFilter.Text = value; } } public string ConnectionName { get { return this.tbConnectionName.Text; } set { this.tbConnectionName.Text = value; } } public TextBox ConnectionControl { get { return this.tbConnectionName; } } public TreeView TypesTreeView { get { return this.tvConnectionTypes; } } #endregion #region Form Event Handlers private void btnOpenFile_Click(object sender, EventArgs e) { if (_connectionProvider != null) { this.openFileDialog1.Filter = _connectionProvider.FileMask == "" ? AllFilesMask : _connectionProvider.FileMask + "|" + AllFilesMask ; } DialogResult dr = this.openFileDialog1.ShowDialog(); if (dr == DialogResult.OK) { this.tbLocation.Text = this.openFileDialog1.FileName; } } private void btnNewDatabase_Click(object sender, System.EventArgs e) { this.Clear(); } private void btnTestConnection_Click(object sender, System.EventArgs e) { TestConnection(); } public void Clear() { this.tbConnectionName.Text = ""; this.tbLocation.Text = ""; this.tbName.Text = ""; this.tbPassword.Text = ""; this.tbUsername.Text = ""; this.tbFilter.Text = ""; } #endregion #region Form KeyPress Handlers private void DatabasePropertiesUC_TextChanged(object sender, System.EventArgs e) { this.tbConnectionString.Text = GetConnectionString(); } private void tbLocation_TextChanged(object sender, System.EventArgs e) { this.DatabasePropertiesUC_TextChanged(sender, e); } private void tbUsername_TextChanged(object sender, System.EventArgs e) { this.DatabasePropertiesUC_TextChanged(sender, e); } private void tbPassword_TextChanged(object sender, System.EventArgs e) { this.DatabasePropertiesUC_TextChanged(sender, e); } private void tbFilter_TextChanged(object sender, System.EventArgs e) { this.DatabasePropertiesUC_TextChanged(sender, e); } private void tbName_TextChanged(object sender, System.EventArgs e) { this.DatabasePropertiesUC_TextChanged(sender, e); } #endregion #region Connection Methods /// <summary> /// Tests Connections using the selected provider type AND OLEDB since OLEDB is required to be able /// to retrieve the relevant Table Information. /// </summary> /// <returns>true if we can connect</returns> /// public void TestConnection() { this.btnTestConnection.Enabled = false; if (this.TestConnections()) { MessageBox.Show(this, "Successfully connected!", "Success!", MessageBoxButtons.OK, MessageBoxIcon.Information); } this.btnTestConnection.Enabled = true; } /// <summary> /// This routine actually does the work of testing the Main and INternal connection methods. /// </summary> /// <returns>true if both connections were sucessfull</returns> public bool TestConnections() { bool validSelected = false; bool validInternal = false; try { validSelected = TestConnectionType(_connectionProvider.ProviderType, GetConnectionString()); // // 7/17/2005 benr: // changed parameter of TestConnectionType to read from the internal // provider as specified in the ProviderConfig.xml file // validInternal = (_connectionProvider.ProviderType == DbProviderType.OLEDB ? true : TestConnectionType(_connectionProvider.InternalProvider.ProviderType, this.GetInternalProviderConnectionString())); } catch (Exception ex) { if (!validSelected) { MessageBox.Show(this, "Unable to connect using the selected Provider. \nMessage: " + ex.Message, "Failure!", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { MessageBox.Show(this, "Unable to connect using the Internal Provider. (Usually OLEDB and needed to retrieve Table information)\nMessage: " + ex.Message, "Failure!", MessageBoxButtons.OK, MessageBoxIcon.Error); } } return (validSelected && validInternal); } /// <summary> /// Tests a given connection Provider Type for a given database. /// </summary> /// <param name="type"></param> /// <returns></returns> public bool TestConnectionType(DbProviderType type, string conString) { using (IDbConnection connection = DbProviderFactory.CreateConnection(type)) { connection.ConnectionString = conString; connection.Open(); } return true; } public string GetConnectionString() { return (_connectionProvider == null) ? string.Empty : _connectionProvider.ConnectionString(this.tbLocation.Text, this.tbName.Text, this.tbUsername.Text, this.tbPassword.Text); } public string GetInternalProviderConnectionString() { return (_connectionProvider == null) ? string.Empty : _connectionProvider.InternalProviderString(this.tbLocation.Text, this.tbName.Text, this.tbUsername.Text, this.tbPassword.Text); } public void SetDatabaseSetting(DatabaseSetting settings) { this.ConnectionName = settings.ConnectionName; this.DbLocation = settings.DatabaseLocation; this.DbName = settings.DatabaseName; this.Password = settings.Password; this.Username = settings.UserName; this.Filter = settings.Filter; try { _connectionProvider = _providersConfig.ConnectionTypes[settings.ConnectionRef].Providers[settings.ProviderRef]; FindConnectionInList(_connectionProvider); SetGUIProperties (_connectionProvider.Parent); } catch (Exception ex) { MessageBox.Show(this, "Unable to load settings. \nMessage: " + ex.Message, "Failure!", MessageBoxButtons.OK, MessageBoxIcon.Error); } } public DatabaseSetting GetDatabaseSetting() { DatabaseSetting ds = new DatabaseSetting(); ds.ConnectionName = this.ConnectionName; ds.DatabaseLocation = this.DbLocation; ds.DatabaseName = this.DbName; ds.Password = this.Password; ds.UserName = this.Username; ds.Filter = this.Filter; ds.ConnectionString = this.GetConnectionString(); ds.OleDbConnectionString = this.GetInternalProviderConnectionString(); ds.DbProviderType = _connectionProvider.ProviderType; ds.DbType = _connectionProvider.DbType; ds.ConnectionRef = _connectionProvider.Parent.Name; ds.ProviderRef = _connectionProvider.Name; return ds; } #endregion #region UI Update methods /// <summary> /// Finds a connection by the Name in the listbox and marks that entry as the active entry /// </summary> public void FindConnectionInList(string type, string provider) { foreach (TreeNode parent in this.tvConnectionTypes.Nodes) { if (parent.Text.Equals(type)) { foreach (TreeNode child in parent.Nodes) { if (child.Text.Equals(provider)) { child.EnsureVisible(); tvConnectionTypes.SelectedNode = child; return; } } } } } public void FindConnectionInList(DbConnectionProvider provider) { FindConnectionInList(provider.Parent.Name, provider.Name); } /// <summary> /// Builds a TreeView control with the Connection->Providers information /// </summary> /// <param name="treeView">TreeView control to populate</param> public void BuildConnectionsTree ( System.Windows.Forms.TreeView treeView) { if (_providersConfig != null) { foreach (DictionaryEntry entryType in this._providersConfig.ConnectionTypes) { DbConnectionType dbType = (DbConnectionType)entryType.Value; TreeNode parent = new TreeNode(dbType.Name); parent.Tag = null; parent.ImageIndex = iconDatabase; parent.SelectedImageIndex = iconDatabase; foreach (DictionaryEntry entryProvider in dbType.Providers) { DbConnectionProvider dbProvider = (DbConnectionProvider)entryProvider.Value; if (dbProvider.Enabled) { TreeNode child = new TreeNode(dbProvider.Name); child.Tag = dbProvider; child.ImageIndex = iconProvider; child.SelectedImageIndex = iconSelected; parent.Nodes.Add(child); } } if (parent.Nodes.Count == 0) { parent.ImageIndex = iconDisabled; parent.SelectedImageIndex = iconDisabled; } treeView.Nodes.Add(parent); } } } private void tvConnectionTypes_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e) { SetConnectionProvider(e.Node.Tag); } private void SetConnectionProvider(object obj) { if (obj == null) { _connectionProvider = null; SetGUIProperties (null); } else { _connectionProvider = obj as DbConnectionProvider; if (_connectionProvider != null) SetGUIProperties (_connectionProvider.Parent); } } /// <summary> /// Depending on the selected Connection/Provider, sets the relevant UI controls enabled/disabled /// </summary> /// <param name="connectionType">A reference to a DbConnectionProvider instance</param> private void SetGUIProperties ( DbConnectionType connectionType) { if (connectionType != null) { SetPromptLabels(connectionType); SetPromptState(true); SetPromptState(true, this.lblLocation, this.tbLocation); SetPromptState(connectionType.SupportsName, this.lblName, this.tbName); SetPromptState(connectionType.SupportsUserID, this.lblUsername, this.tbUsername); SetPromptState(connectionType.SupportsPassword, this.lblPassword, this.tbPassword); SetPromptState(connectionType.SupportsFilter, this.lblFilter, this.tbFilter); this.tbConnectionString.Text = GetConnectionString(); } else { SetPromptLabels(DbConnectionTypes.UnknownConnectionType()); SetPromptState (false); this.tbConnectionString.Text = String.Empty; } } private void SetPromptState ( bool state ) { SetPromptState (state, this.lblLocation, this.tbLocation); SetPromptState (state, this.lblName, this.tbName); SetPromptState (state, this.lblUsername, this.tbUsername); SetPromptState (state, this.lblPassword, this.tbPassword); SetPromptState (state, this.lblFilter, this.tbFilter); this.btnTestConnection.Enabled = state; this.tbConnectionString.Enabled = state; this.lblConnection.Enabled = state; } private void SetPromptLabels(DbConnectionType connectionType) { if (connectionType.SupportsFile) { this.lblLocation.Text = connectionType.PromptFile; this.btnOpenFile.Visible = true; this.btnOpenFile.Enabled = true; } else { this.lblLocation.Text = connectionType.PromptServer; this.btnOpenFile.Visible = false; this.btnOpenFile.Enabled = false; } this.lblName.Text = connectionType.PromptName; this.lblUsername.Text = connectionType.PromptUserID; this.lblPassword.Text = connectionType.PromptPassword; } private void SetPromptState ( bool state, System.Windows.Forms.Label label, System.Windows.Forms.TextBox text ) { text.Enabled = state; label.Enabled = state; } #endregion } } --- NEW FILE: SystemType.cs --- using System; namespace Adapdev.Windows.Forms { /// <summary> /// The type of system resource /// </summary> public enum SystemType { File, Directory } } --- NEW FILE: DatabaseSetting.cs --- namespace Adapdev.Windows.Forms { using System; using Adapdev.Data; using Adapdev.Data.Schema; [Serializable] public class DatabaseSetting { private string connectionName; private strin... [truncated message content] |