adapdev-commits Mailing List for Adapdev.NET (Page 17)
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/Task In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv19977/src/Adapdev/Scheduling/Task Added Files: ScheduledTasks.cs Scheduler.cs Task.cs TaskList.cs TaskSchedulerInterop.cs Trigger.cs TriggerList.cs Log Message: Reposting to the repository after it got hosed --- 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 ... [truncated message content] |
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.Data/Schema In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv19977/src/Adapdev.Data/Schema Added Files: AbstractSchemaBuilder.cs AssociationType.cs ColumnSchema.cs ColumnSchemaCollection.cs ColumnSchemaDictionary.cs ColumnSchemaEnumerator.cs CompareDatabaseSchemas.cs DatabaseSchema.cs ForeignKeyAssociation.cs ISchemaBuilder.cs LoadDatabaseSchema.cs MySqlSchemaBuilder.cs OleDbSchemaBuilder.cs ParameterSchema.cs ParameterSchemaDictionary.cs ProcedureInfo.cs ProcedureSchema.cs SaveDatabaseSchema.cs SchemaBuilder.cs SchemaConstants.cs TableSchema.cs TableSchemaCollection.cs TableSchemaDictionary.cs TableSchemaEnumerator.cs TableType.cs TableTypeConverter.cs Log Message: Reposting to the repository after it got hosed --- NEW FILE: TableType.cs --- namespace Adapdev.Data.Schema { /// <summary> /// The type of table /// </summary> public enum TableType { /// <summary> /// A system view table /// </summary> SYSTEM_VIEW, /// <summary> /// A system table /// </summary> SYSTEM_TABLE, /// <summary> /// A table /// </summary> TABLE, /// <summary> /// A view table /// </summary> VIEW, /// <summary> /// A alias to a Table /// </summary> SYNONYM } } --- NEW FILE: ParameterSchemaDictionary.cs --- namespace Adapdev.Data.Schema { using System; using System.Collections; using System.Text; /// <summary> /// Summary description for CacheMetaDataDictionary. /// </summary> /// [Serializable] public class ParameterSchemaDictionary : DictionaryBase { public ParameterSchema this[String key] { get { return ((ParameterSchema) Dictionary[key]); } set { Dictionary[key] = value; } } public ICollection Keys { get { return (Dictionary.Keys); } } public ICollection Values { get { return (Dictionary.Values); } } public void Add(String key, ParameterSchema value) { Dictionary.Add(key, value); } public bool Contains(String key) { return (Dictionary.Contains(key)); } public void Remove(String key) { Dictionary.Remove(key); } public override string ToString() { StringBuilder sb = new StringBuilder(); foreach (ParameterSchema ci in this.Values) { sb.Append(ci.ToString()); } return sb.ToString(); } } } --- NEW FILE: ParameterSchema.cs --- namespace Adapdev.Data.Schema { /// <summary> /// Summary description for ParameterSchema. /// </summary> public class ParameterSchema { public string Name; public int Ordinal; public int DataTypeId; public bool HasDefault; public object Default; public bool AllowNulls; public int MaxLength; public string Description; public string DataTypeName; } } --- NEW FILE: CompareDatabaseSchemas.cs --- using System; namespace Adapdev.Data.Schema { using System.Reflection; using Adapdev.Attributes; /// <summary> /// Summary description for CompareSchemasCommand. /// </summary> public class CompareDatabaseSchemas { private DatabaseSchema _databaseSchema; private DatabaseSchema _savedDatabaseSchema; public CompareDatabaseSchemas(DatabaseSchema databaseSchema, DatabaseSchema savedDatabaseSchema) { this._databaseSchema = databaseSchema; this._savedDatabaseSchema = savedDatabaseSchema; } /// <summary> /// Compare the saved Schema and the database Schema by iterating through the DatabaseSchema's tables /// </summary> /// <returns>DatabaseSchema - the updated DatabaseSchema</returns> public DatabaseSchema Compare() { foreach(TableSchema table in _databaseSchema.SortedTables.Values) { //If the table exists check it otherwise add the table if(null != this._savedDatabaseSchema.GetTable(table.Name)) { foreach (PropertyInfo property in table.GetType().GetProperties()) { foreach (object attribute in property.GetCustomAttributes(typeof(SchemaDataRewritableAttribute),true)) { if(isRewritable(attribute, property)) { rewritePropertyForTable(table, property); } } } findAndUpdateColumns(table); } else { this._savedDatabaseSchema.AddTable(table); } } return _savedDatabaseSchema; } /// <summary> /// Iterate through the ColumnSchema's for a TableSchema and update properties that are rewritable from the Database Schema /// </summary> /// <param name="table">TableSchema table that we will check it's ColumnSchema's</param> private void findAndUpdateColumns(TableSchema table) { foreach(ColumnSchema column in table.SortedColumns.Values) { //If the column exists check it otherwise add the column if(null != this._savedDatabaseSchema.GetTable(table.Name).GetColumn(column.Name)) { foreach (PropertyInfo property in column.GetType().GetProperties()) { foreach(object attribute in property.GetCustomAttributes(typeof(SchemaDataRewritableAttribute),true)) { if(isRewritable(attribute,property)) { rewritePropertyForColumn(table,column,property); } } } } else { this._savedDatabaseSchema.GetTable(table.Name).AddColumn(column); } } } /// <summary> /// Rewrite the TableSchema proprety to match that from the Database /// </summary> /// <param name="tableToUpdateFrom">TableSchema object that we will use to update from</param> /// <param name="property">PropertyInfo</param> private void rewritePropertyForTable(TableSchema tableToUpdateFrom, PropertyInfo property) { TableSchema tableToUpdate = this._savedDatabaseSchema.GetTable(tableToUpdateFrom.Name); PropertyInfo tablePropertyToUpdate = tableToUpdate.GetType().GetProperty(property.Name); tablePropertyToUpdate.SetValue(this._savedDatabaseSchema.GetTable(tableToUpdateFrom.Name), property.GetValue(tableToUpdateFrom,null),null); } /// <summary> /// Rewrite the ColumnSchema proprety to match that from the Database /// </summary> /// <param name="tableToUpdateFrom">TableSchema object that we will use to update from</param> /// <param name="columnToUpdateFrom">ColumnSchema object that we will use to update from</param> /// <param name="property">PropertyInfo</param> private void rewritePropertyForColumn(TableSchema tableToUpdateFrom, ColumnSchema columnToUpdateFrom, PropertyInfo property) { ColumnSchema columnToUpdate = this._savedDatabaseSchema.GetTable(tableToUpdateFrom.Name).GetColumn(columnToUpdateFrom.Name); PropertyInfo columnPropertyToUpdate = columnToUpdate.GetType().GetProperty(property.Name); columnPropertyToUpdate.SetValue(columnToUpdate, property.GetValue(columnToUpdateFrom, null),null); } /// <summary> /// Is the SchemaDataRewritableAttribute set to update. /// </summary> /// <param name="attribute">The custom attribute for the property</param> /// <param name="property">The Schema PropertyInfo</param> /// <returns>bool</returns> private bool isRewritable(object attribute,PropertyInfo property) { return ((SchemaDataRewritableAttribute) attribute).Rewrite && property.CanWrite; } } } --- NEW FILE: ISchemaBuilder.cs --- using System; namespace Adapdev.Data.Schema { /// <summary> /// Summary description for ISchemaBuilder. /// </summary> internal interface ISchemaBuilder { DatabaseSchema BuildDatabaseSchema(string connectionString, Adapdev.Data.DbType databaseType, DbProviderType providerType, string schemaFilter); } } --- NEW FILE: AbstractSchemaBuilder.cs --- using System; namespace Adapdev.Data.Schema { /// <summary> /// Summary description for AbstractSchemaBuilder. /// </summary> public abstract class AbstractSchemaBuilder : ISchemaBuilder { #region ISchemaBuilder Members public abstract DatabaseSchema BuildDatabaseSchema(string connectionString, Adapdev.Data.DbType databaseType, Adapdev.Data.DbProviderType providerType, string schemaFilter); public static bool EndProgress (Adapdev.IProgressCallback _callback, string message, bool ok) { if (_callback != null) { if (_callback.IsAborting) return false; _callback.SetText(message,""); _callback.SetRange(0, 1); if (ok) { _callback.StepTo(1); } else { _callback.StepTo(0); _callback.AddMessage(ProgressMessageTypes.Critical,"No database schema information found."); } } return true; } public static bool IncrProgress(Adapdev.IProgressCallback _callback, string message, ref int count) { if (_callback != null) { if (_callback.IsAborting) return false; _callback.SetText(message); _callback.StepTo(count++); } return true; } public static bool StartProgress (Adapdev.IProgressCallback _callback, string message, int max, ref int stepto) { if (max > 0) { if (_callback != null) { if (_callback.IsAborting) return false; _callback.SetText(message,""); _callback.SetRange(0, max); _callback.StepTo(stepto = 0); } } return true; } #endregion } } --- NEW FILE: MySqlSchemaBuilder.cs --- using System; using System.Data; using System.Data.OleDb; using System.Text; using Adapdev.Data.Sql; using MySql.Data.MySqlClient; namespace Adapdev.Data.Schema { /// <summary> /// Summary description for MySqlSchemaBuilder. /// </summary> public class MySqlSchemaBuilder : AbstractSchemaBuilder { private Adapdev.Data.DbProviderType dbProviderType = DbProviderType.MYSQL; private Adapdev.IProgressCallback _callback = null; private int recordCount = 0; public MySqlSchemaBuilder(Adapdev.IProgressCallback callback, ref int recordCount) { this._callback = callback; this.recordCount = recordCount; } public override DatabaseSchema BuildDatabaseSchema(string connectionString, Adapdev.Data.DbType databaseType, Adapdev.Data.DbProviderType providerType, string schemaFilter) { return this.CreateMySqlDatabaseSchema(connectionString); } private DatabaseSchema CreateMySqlDatabaseSchema(string connectionString) { DataTable schemaTables = this.GetMySqlSchema(connectionString); DatabaseSchema di = new DatabaseSchema(); MySqlConnection c = new MySqlConnection(connectionString); di.Name = c.Database; c = null; foreach (DataRow dr in schemaTables.Rows) { TableSchema ti = CreateMySqlTableSchema(dr); CreateColumnSchemas(ti, connectionString, Adapdev.Data.DbType.MYSQL); DataTable columns = this.GetMySqlColumnSchema(connectionString, ti.Name); foreach(DataRow columnRow in columns.Rows) { if (columnRow["Key"] + "" == "PRI") { ti[columnRow["Field"].ToString()].IsPrimaryKey = true; } else if (columnRow["Key"] + "" == "MUL") { ti[columnRow["Field"].ToString()].IsForeignKey = true; } } di.AddTable(ti); } return di; } /// <summary> /// Creates the ColumnSchemas for a specified table /// </summary> /// <param name="ts">The TableSchema to add the ColumnSchema to</param> /// <param name="connectionString">The OleDb connectionstring to use</param> private void CreateColumnSchemas(TableSchema ts, string connectionString, Adapdev.Data.DbType databaseType) { DataTable dt = this.GetReaderSchema(connectionString, ts.Name, databaseType); if (!(dt == null)) { foreach (DataRow dr in dt.Rows) { ColumnSchema ci = new ColumnSchema(); ci.Alias = (string) dr["ColumnName"]; ci.AllowNulls = (bool) dr["AllowDBNull"]; ci.DataTypeId = (int) dr["ProviderType"]; ci.DataType = ProviderInfoManager.GetInstance().GetNameById(this.dbProviderType, ci.DataTypeId); ci.DefaultTestValue = ProviderInfoManager.GetInstance().GetTestDefaultById(this.dbProviderType, ci.DataTypeId); ci.DefaultValue = ProviderInfoManager.GetInstance().GetDefaultById(this.dbProviderType, ci.DataTypeId); ci.IsAutoIncrement = (bool) dr["IsAutoIncrement"]; ci.IsForeignKey = false; ci.IsPrimaryKey = false; ci.IsUnique = (bool) dr["IsUnique"]; ci.Length = (int) dr["ColumnSize"]; ci.Name = (string) dr["ColumnName"]; ci.NetType = dr["DataType"].ToString(); ci.Ordinal = (int) dr["ColumnOrdinal"]; ci.IsReadOnly = (bool) dr["IsReadOnly"]; // hack because MySql has the same provider type for // strings and blobs, which results in blob // default and test values being incorrectly assigned to // string columns if((ci.DataTypeId == 252 && ci.NetType.Equals("System.String")) || ci.DataTypeId == 254) { ci.DataTypeId = 253; ci.DataType = ProviderInfoManager.GetInstance().GetNameById(this.dbProviderType, ci.DataTypeId); ci.DefaultTestValue = ProviderInfoManager.GetInstance().GetTestDefaultById(this.dbProviderType, ci.DataTypeId); ci.DefaultValue = ProviderInfoManager.GetInstance().GetDefaultById(this.dbProviderType, ci.DataTypeId); } ts.AddColumn(ci); } } } /// <summary> /// Gets the OleDbDataReader.GetSchemaTable() for a specified database table /// </summary> /// <param name="oledbConnectionString">The connection string to use</param> /// <param name="tableName">The table to grab the schema for</param> /// <returns></returns> private DataTable GetReaderSchema(string oledbConnectionString, string tableName, Adapdev.Data.DbType databaseType) { return GetReaderSchema(new MySqlConnection(), new MySqlCommand(), oledbConnectionString, databaseType, tableName); } private DataTable GetReaderSchema(IDbConnection cn, IDbCommand cmd, string connectionString, Adapdev.Data.DbType databaseType, string tableName) { DataTable schemaTable = null; try { cn.ConnectionString = connectionString; cn.Open(); // Please Note: Use the GetPre and GetPostDelimiters here as in the case of // Oracle using [ ] around a Column Name is not valid. cmd.Connection = cn; cmd.CommandText = "SELECT * FROM " + QueryHelper.GetPreDelimeter(databaseType) + tableName + QueryHelper.GetPostDelimeter(databaseType); IDataReader myReader = cmd.ExecuteReader(CommandBehavior.KeyInfo | CommandBehavior.SchemaOnly); schemaTable = myReader.GetSchemaTable(); myReader.Close(); cn.Close(); } catch (Exception ex) { schemaTable = null; if (_callback != null) _callback.AddMessage(ProgressMessageTypes.Warning, "Could not load Column information for " + tableName + ". " + ex.Message); } return schemaTable; } private TableSchema CreateMySqlTableSchema(DataRow dr) { TableSchema ti = new TableSchema(); ti.Alias = dr[0].ToString(); ti.Name = ti.Alias; ti.TableType = TableType.TABLE; return ti; } private DataTable GetMySqlColumnSchema(string connectionString, string tableName) { DataTable schemaTable = new DataTable(); MySqlConnection cn = new MySqlConnection(); MySqlCommand cmd = new MySqlCommand(); MySqlDataAdapter da = new MySqlDataAdapter(); cn.ConnectionString = connectionString; cn.Open(); cmd.Connection = cn; cmd.CommandText = "SHOW COLUMNS IN " + tableName; da.SelectCommand = cmd; da.Fill(schemaTable); cn.Close(); return schemaTable; } /// <summary> /// Gets the OleDbConnection.GetOleDbSchemaTable for a specified connection /// </summary> /// <param name="mysqlConnectionString">The connection to use</param> /// <returns></returns> private DataTable GetMySqlSchema(string mysqlConnectionString) { MySqlConnection conn = new MySqlConnection(mysqlConnectionString); conn.Open(); MySqlCommand command = new MySqlCommand("SHOW TABLES", conn); DataTable tbl = new DataTable(); MySqlDataAdapter da = new MySqlDataAdapter(command); da.Fill(tbl); conn.Close(); return tbl; } public string PrintReaderSchema(string connectionString, string table) { StringBuilder sb = new StringBuilder(); DataTable schemaTable; schemaTable = this.GetReaderSchema(connectionString, table, Adapdev.Data.DbType.MYSQL); sb.Append("\r\n=========== " + table + " Schema =====================\r\n\r\n"); foreach (DataRow myField in schemaTable.Rows) { foreach (DataColumn myProperty in schemaTable.Columns) { sb.Append(myProperty.ColumnName + " : " + myField[myProperty].ToString() + "\r\n"); } sb.Append("\r\n"); } sb.Append("\r\n\r\n"); return sb.ToString(); } } } --- NEW FILE: ColumnSchemaEnumerator.cs --- using System; using System.Collections; namespace Adapdev.Data.Schema { public class ColumnSchemaEnumerator : IEnumerator { private IEnumerator baseEnumerator; private IEnumerable temp; public ColumnSchemaEnumerator(ColumnSchemaCollection mappings) { this.temp = ((IEnumerable)(mappings)); this.baseEnumerator = temp.GetEnumerator(); } public ColumnSchemaEnumerator(ColumnSchemaDictionary mappings) { this.temp = ((IEnumerable)(mappings)); this.baseEnumerator = temp.GetEnumerator(); } public ColumnSchema Current { get { return ((ColumnSchema)(baseEnumerator.Current)); } } object IEnumerator.Current { get { return baseEnumerator.Current; } } public bool MoveNext() { return baseEnumerator.MoveNext(); } bool IEnumerator.MoveNext() { return baseEnumerator.MoveNext(); } public void Reset() { baseEnumerator.Reset(); } void IEnumerator.Reset() { baseEnumerator.Reset(); } } } --- NEW FILE: ForeignKeyAssociation.cs --- using System; namespace Adapdev.Data.Schema { using Adapdev.Text; /// <summary> /// Summary description for ForeignKeyAssociation. /// </summary> public class ForeignKeyAssociation { private ColumnSchema _foreignColumn = null; private TableSchema _foreignTable = null; private ColumnSchema _columnSchema = null; private AssociationType _association = AssociationType.OneToMany; public ColumnSchema ForeignColumn { get { return _foreignColumn; } set { _foreignColumn = value; } } public string ForeignColumnName { get{return this._foreignColumn.Name;} } public ColumnSchema Column { get { return _columnSchema; } set { _columnSchema = value; } } public string ColumnName { get{return this._columnSchema.Name;} } public TableSchema ForeignTable { get { return _foreignTable; } set { _foreignTable = value; } } public string ForeignTableName { get{return this._foreignTable.Name;} } public string ForeignKeyName { get{return this.ColumnName + "-" + this.ForeignTableName + "." + this.ForeignColumnName;} } public AssociationType AssociationType { get { return _association; } set { _association = value; } } public ForeignKeyAssociation(ColumnSchema columnSchema, ColumnSchema foreignColumn, TableSchema foreignTable) { this._columnSchema = columnSchema; this._foreignColumn = foreignColumn; this._foreignTable = foreignTable; } public override string ToString() { return StringUtil.ToString(this); } } } --- NEW FILE: ProcedureSchema.cs --- namespace Adapdev.Data.Schema { /// <summary> /// Represents the schema for a database procedure /// </summary> public class ProcedureSchema { protected ParameterSchemaDictionary parameters = new ParameterSchemaDictionary(); /// <summary> /// The name of the procedure /// </summary> public string Name; /// <summary> /// Adds a ParameterSchema /// </summary> /// <param name="p"></param> public void AddParameter(ParameterSchema p) { parameters[p.Name] = p; } /// <summary> /// Removes a ParameterSchema /// </summary> /// <param name="name">The name of the ParameterSchema to remove</param> public void RemoveParameter(string name) { parameters.Remove(name); } /// <summary> /// Retrieves a ParameterSchema /// </summary> /// <param name="name">The name of the ParameterSchema to retrieve</param> /// <returns></returns> public ParameterSchema GetParameter(string name) { return parameters[name]; } /// <summary> /// Returns a collection of parameters /// </summary> /// <returns></returns> public ParameterSchemaDictionary Parameters { get{return parameters;} set{this.parameters = value;} } } } --- NEW FILE: ColumnSchemaDictionary.cs --- namespace Adapdev.Data.Schema { using System; using System.Collections; using System.Text; using System.Xml.Serialization; /// <summary> /// Strongly-typed collection for ColumnSchemas /// </summary> /// [Serializable] public class ColumnSchemaDictionary : DictionaryBase, IXmlSerializable { private const string nameSpace = ""; private const string columnDictionaryElement = "ColumnDictionary"; public ColumnSchema this[String key] { get { return ((ColumnSchema) Dictionary[key]); } set { Dictionary[key] = value; } } public ICollection Keys { get { return (Dictionary.Keys); } } public ICollection Values { get { return (Dictionary.Values); } } public void Add(String key, ColumnSchema value) { Dictionary.Add(key, value); } public bool Contains(String key) { return (Dictionary.Contains(key)); } public void Remove(String key) { Dictionary.Remove(key); } public override string ToString() { StringBuilder sb = new StringBuilder(); foreach (ColumnSchema ci in this.Values) { sb.Append(ci.ToString()); } return sb.ToString(); } #region IXmlSerializable Members /// <summary> /// XmlWriter that is used to write the ColumnSchemaDictionary as it implements IDictory that is not serializable /// using the normal methods. This uses the interface IXmlSerializable which isn't offically supported but still /// exists in the next framework /// </summary> /// <param name="writer">System.Xml.XmlWriter</param> public void WriteXml(System.Xml.XmlWriter writer) { XmlSerializer keySer = new XmlSerializer(typeof(String)); XmlSerializer valueSer = new XmlSerializer(typeof(ColumnSchema)); writer.WriteStartElement(columnDictionaryElement, nameSpace); foreach(object key in Dictionary.Keys) { writer.WriteStartElement("key", nameSpace); keySer.Serialize(writer,key); writer.WriteEndElement(); writer.WriteStartElement("value", nameSpace); object value = Dictionary[key]; valueSer.Serialize(writer, value); writer.WriteEndElement(); } writer.WriteEndElement(); } public System.Xml.Schema.XmlSchema GetSchema() { return null; } /// <summary> /// Custom XmlReader to read the ColumnSchemaDictionary /// </summary> /// <param name="reader">System.Xml.XmlReader</param> public void ReadXml(System.Xml.XmlReader reader) { XmlSerializer keySer = new XmlSerializer(typeof(String)); XmlSerializer valueSer = new XmlSerializer(typeof(ColumnSchema)); reader.Read(); reader.ReadStartElement(columnDictionaryElement, nameSpace); while(reader.NodeType != System.Xml.XmlNodeType.EndElement) { reader.ReadStartElement("key", nameSpace); object key = keySer.Deserialize(reader); reader.ReadEndElement(); reader.ReadStartElement("value", nameSpace); object value = valueSer.Deserialize(reader); reader.ReadEndElement(); Dictionary.Add(key, value); reader.MoveToContent(); } reader.ReadEndElement(); } #endregion } } --- NEW FILE: TableSchemaEnumerator.cs --- using System; using System.Collections; namespace Adapdev.Data.Schema { public class TableSchemaEnumerator : IEnumerator { private IEnumerator baseEnumerator; private IEnumerable temp; public TableSchemaEnumerator(TableSchemaCollection mappings) { this.temp = ((IEnumerable)(mappings)); this.baseEnumerator = temp.GetEnumerator(); } public TableSchemaEnumerator(TableSchemaDictionary mappings) { this.temp = ((IEnumerable)(mappings)); this.baseEnumerator = temp.GetEnumerator(); } public TableSchema Current { get { return ((TableSchema)(baseEnumerator.Current)); } } object IEnumerator.Current { get { return baseEnumerator.Current; } } public bool MoveNext() { return baseEnumerator.MoveNext(); } bool IEnumerator.MoveNext() { return baseEnumerator.MoveNext(); } public void Reset() { baseEnumerator.Reset(); } void IEnumerator.Reset() { baseEnumerator.Reset(); } } } --- NEW FILE: LoadDatabaseSchema.cs --- using System; namespace Adapdev.Data.Schema { using System.Collections; using System.IO; using System.Xml.Serialization; /// <summary> /// Summary description for LoadDatabaseSchema. /// </summary> public class LoadDatabaseSchema { private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private DatabaseSchema _dbSchema; private String schemaFile; private String _savedSchemaName; public LoadDatabaseSchema(String savedSchemaName, DatabaseSchema dbSchema) { this._savedSchemaName = savedSchemaName; this._dbSchema = dbSchema; } public DatabaseSchema Load() { schemaFile = System.IO.Path.Combine(SchemaConstants.SCHEMAPATH,this._savedSchemaName); if(File.Exists(schemaFile)) { XmlSerializer dbSerializer = new XmlSerializer(typeof(DatabaseSchema)); FileStream dbStream = new FileStream(schemaFile, FileMode.Open); _dbSchema = (DatabaseSchema) dbSerializer.Deserialize(dbStream); dbStream.Close(); } return _dbSchema; } } } --- NEW FILE: SchemaConstants.cs --- using System; namespace Adapdev.Data.Schema { /// <summary> /// Summary description for Constants Associated with the Schema /// </summary> public class SchemaConstants { public static readonly string SCHEMAPATH = System.Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData); } } --- NEW FILE: AssociationType.cs --- using System; namespace Adapdev.Data.Schema { /// <summary> /// Summary description for AssociationType. /// </summary> public enum AssociationType { OneToOne, OneToMany, ManyToMany, ManyToOne } } --- NEW FILE: DatabaseSchema.cs --- namespace Adapdev.Data.Schema { using System; using System.Collections; using Adapdev.Text; /// <summary> /// Represents the schema for a database /// </summary> /// [Serializable] [XmlRoot("DatabaseSchema")] public class DatabaseSchema { protected TableSchemaDictionary tables = new TableSchemaDictionary(); protected string name = String.Empty; protected string connectionString = String.Empty; protected DbType databaseType = DbType.SQLSERVER; protected DbProviderType databaseProviderType = DbProviderType.SQLSERVER; /// <summary> /// Constructor /// </summary> public DatabaseSchema() { } /// <summary> /// Constructor /// </summary> /// <param name="name">The name of the database</param> public DatabaseSchema(string name) { this.Name = name; } /// <summary> /// The database name /// </summary> public string Name { get { return this.name; } set { this.name = value; } } /// <summary> /// The database connectionstring /// </summary> public string ConnectionString { get { return this.connectionString; } set { this.connectionString = value; } } /// <summary> /// The database type /// </summary> public DbType DatabaseType { get { return this.databaseType; } set { this.databaseType = value; } } /// <summary> /// The database provider type /// </summary> public DbProviderType DatabaseProviderType { get { return this.databaseProviderType; } set { this.databaseProviderType = value; } } /// <summary> /// Adds the specified table schema to the database /// </summary> /// <param name="table">The TableSchema to add</param> public void AddTable(TableSchema table) { tables[table.Name] = table; } /// <summary> /// Gets the specified table schema /// </summary> /// <param name="name">The name of the TableSchema to retrieve</param> /// <returns>TableSchema</returns> public TableSchema GetTable(string name) { return tables[name]; } /// <summary> /// Indexer to retrieve a TableSchema /// </summary> public TableSchema this[String key] { get { return (tables[key]); } set { tables[key] = value; } } /// <summary> /// Returns a dictionary of the database's TableSchemas /// </summary> /// <returns></returns> public TableSchemaDictionary Tables { get{return this.tables;} set{this.tables = value;} } /// <summary> /// Returnes a SortedList of TableSchemas, sorted by the table names /// </summary> /// <returns>SortedList</returns> public SortedList SortedTables { get { SortedList sl = new SortedList(); foreach (TableSchema t in this.tables.Values) { sl.Add(t.Name, t); } return sl; } } public override string ToString() { return Environment.NewLine + StringUtil.ToString(this) + Environment.NewLine + this.Tables.ToString(); } } } --- NEW FILE: TableSchema.cs --- namespace Adapdev.Data.Schema { using System; using System.Collections; using System.Xml.Serialization; using Adapdev.Attributes; using Adapdev.Text; /// <summary> /// Represents the schema for a database table /// </summary> [Serializable] public class TableSchema { protected TableType tableType = TableType.TABLE; protected bool _active = true; protected string _name = String.Empty; protected string _alias = String.Empty; protected ColumnSchemaDictionary columns = new ColumnSchemaDictionary(); protected DatabaseSchema parent = null; /// <summary> /// Property TableType (TableType) /// </summary> public TableType TableType { get { return this.tableType; } set { this.tableType = value; } } /// <summary> /// Adds the specified ColumnSchema /// </summary> /// <param name="c"></param> public void AddColumn(ColumnSchema c) { this.columns[c.Name] = c; } /// <summary> /// Removes the specified ColumnSchema /// </summary> /// <param name="name">The name of the ColumnSchema to remove</param> public void RemoveColumn(string name) { this.columns.Remove(name); } /// <summary> /// Retrieves the specified ColumnSchema /// </summary> /// <param name="name">The name of the ColumnSchema to retrieve</param> /// <returns></returns> public ColumnSchema GetColumn(string name) { return this.columns[name]; } /// <summary> /// Indexer to retrieve a ColumnSchema by name /// </summary> public ColumnSchema this[String key] { get { return (columns[key]); } set { columns[key] = value; } } /// <summary> /// Gets the number of primary keys /// </summary> /// <returns></returns> [XmlAttribute] [SchemaDataRewritableAttribute(false)] public int PrimaryKeyCount { get { int i = 0; foreach (ColumnSchema c in columns.Values) { if(c.IsPrimaryKey)i++; } return i; } } /// <summary> /// Gets the number of foreign keys /// </summary> /// <returns></returns> [XmlAttribute] [SchemaDataRewritableAttribute(false)] public int ForeignKeyCount { get { int i = 0; foreach (ColumnSchema c in columns.Values) { if(c.IsForeignKey)i++; } return i; } } /// <summary> /// Gets the specified primary key Column Schema by index. /// </summary> /// <param name="index"></param> /// <returns></returns> /// <remarks> /// If a database table contains two primary keys, then index 0 would retrieve /// the first, and index 1 would be the second. The index is in relation /// to the number of primary keys, not the total number of columns /// </remarks> public ColumnSchema GetPrimaryKey(int index) { ArrayList al = new ArrayList(this.PrimaryKeys.Values); return ((ColumnSchema) al[index]); } /// <summary> /// Gets the specified primary key Column Schema by index. /// </summary> /// <param name="index"></param> /// <returns></returns> /// <remarks> /// If a database table contains two foreign keys, then index 0 would retrieve /// the first, and index 1 would be the second. The index is in relation /// to the number of foreign keys, not the total number of columns /// </remarks> public ColumnSchema GetForeignKey(int index) { ArrayList al = new ArrayList(this.ForeignKeys.Values); return ((ColumnSchema) al[index]); } /// <summary> /// Returns the list of ColumnSchemas, sorted by their ordinal representation /// </summary> /// <returns></returns> [XmlIgnore] public SortedList OrdinalColumns { get { SortedList sl = new SortedList(); foreach (ColumnSchema c in this.columns.Values) { sl[c.Ordinal] = c; } return sl; } } /// <summary> /// Returns the list of ColumnSchemas, sorted by their names /// </summary> /// <returns></returns> [XmlIgnore] public SortedList SortedColumns { get { SortedList sl = new SortedList(); foreach (ColumnSchema c in this.columns.Values) { sl.Add(c.Name, c); } return sl; } } /// <summary> /// Returns the table name in proper case, with all spaces removed /// </summary> /// <returns></returns> [XmlAttribute] [SchemaDataRewritableAttribute(false)] public string ProperName { get{return StringUtil.ToTrimmedProperCase(this.Name);} } /// <summary> /// Specifies whether the table is active. Used primarily /// for on/off state in GUIs. It allows for a table to still /// be part of a DatabaseSchema, but ignored for various reasons /// </summary> [XmlAttribute] [SchemaDataRewritableAttribute(false)] public bool IsActive { get { return this._active; } set { this._active = value; } } /// <summary> /// The table name /// </summary> [XmlAttribute] [SchemaDataRewritableAttribute(true)] public string Name { get { return this._name; } set { this._name = value; } } /// <summary> /// The table alias /// </summary> [XmlAttribute] [SchemaDataRewritableAttribute(false)] public string Alias { get { if(this._alias.Length == 0 || this._alias == this._name) return this.ProperName; else return this._alias; } set { this._alias = value; } } [XmlAttribute] [SchemaDataRewritableAttribute(false)] public bool HasForeignKeys { get { if(this.ForeignKeyCount > 0) return true; else return false; } } [XmlAttribute] [SchemaDataRewritableAttribute(false)] public bool HasPrimaryKeys { get { if(this.PrimaryKeyCount > 0) return true; else return false; } } /// <summary> /// Returns a collection of ColumnSchemas /// </summary> /// <returns></returns> [XmlElement(Type = typeof(ColumnSchemaDictionary), ElementName = "Columns")] public ColumnSchemaDictionary Columns { get{return this.columns;} set{this.columns = value;} } /// <summary> /// Returns a collection of ColumnSchemas that are primary keys /// </summary> /// <returns></returns> [XmlElement(Type = typeof(ColumnSchemaDictionary), ElementName = "PrimaryKeys")] public ColumnSchemaDictionary PrimaryKeys { get { ColumnSchemaDictionary pks = new ColumnSchemaDictionary(); foreach(ColumnSchema c in this.columns.Values) { if(c.IsPrimaryKey)pks[c.Name] = c; } return pks; } } /// <summary> /// Returns a collection of ColumnSchemas that are foreign keys /// </summary> /// <returns></returns> [XmlElement(Type = typeof(ColumnSchemaDictionary), ElementName = "ForeignKeys")] public ColumnSchemaDictionary ForeignKeys { get { ColumnSchemaDictionary fks = new ColumnSchemaDictionary(); foreach(ColumnSchema c in this.columns.Values) { if(c.IsForeignKey)fks[c.Name] = c; } return fks; } } public override string ToString() { return Environment.NewLine + StringUtil.ToString(this) + Environment.NewLine + this.Columns.ToString(); } } } --- NEW FILE: TableTypeConverter.cs --- namespace Adapdev.Data.Schema { using System; /// <summary> /// Converts the string representation of a table type to a TableType enum /// </summary> public class TableTypeConverter { private TableTypeConverter() { } /// <summary> /// Converts the string representation of a table type to a TableType enum /// </summary> /// <param name="tableType">The string representation to convert</param> /// <returns></returns> public static TableType Convert(string tableType) { switch (tableType.ToUpper(new System.Globalization.CultureInfo("en-US"))) { case "SYSTEM TABLE": case "ACCESS TABLE": return TableType.SYSTEM_TABLE; case "SYSTEM VIEW": return TableType.SYSTEM_VIEW; case "TABLE": return TableType.TABLE; case "VIEW": return TableType.VIEW; case "SYNONYM": return TableType.SYNONYM; default: throw new Exception("TableType " + tableType + " is not supported."); } } } } --- NEW FILE: OleDbSchemaBuilder.cs --- using System; using System.Data; using System.Data.OleDb; using System.Text; using Adapdev.Data.Sql; namespace Adapdev.Data.Schema { /// <summary> /// Summary description for OleDbSchemaBuilder. /// </summary> public class OleDbSchemaBuilder : AbstractSchemaBuilder { private Adapdev.IProgressCallback _callback = null; private Adapdev.Data.DbProviderType dbProviderType = DbProviderType.OLEDB; private int recordCount = 0; public OleDbSchemaBuilder(Adapdev.IProgressCallback callback, ref int recordCount) { this._callback = callback; this.recordCount = recordCount; } public override DatabaseSchema BuildDatabaseSchema(string connectionString, Adapdev.Data.DbType databaseType, Adapdev.Data.DbProviderType providerType, string schemaFilter) { DataTable schemaTables = this.GetOleDbSchema(_callback, connectionString, OleDbSchemaGuid.Tables, "",schemaFilter,"",""); DatabaseSchema di = new DatabaseSchema(); di.DatabaseProviderType = providerType; di.DatabaseType = databaseType; this.dbProviderType = providerType; if (schemaTables != null) { if (schemaTables.Rows.Count > 0) { //TODO: Note sure if this is valid. It does not work for Oracle DB's di.Name = schemaTables.Rows[0]["TABLE_CATALOG"].ToString(); if (di.Name == String.Empty) di.Name = "Unknown"; // Build the base schema information if (!StartProgress(_callback, "Building Table Details",schemaTables.Rows.Count,ref recordCount)) return null; foreach (DataRow dr in schemaTables.Rows) { TableType tableType = TableTypeConverter.Convert(dr["TABLE_TYPE"].ToString()); if (tableType == TableType.TABLE || tableType == TableType.VIEW) { if (!IncrProgress(_callback, dr["TABLE_NAME"].ToString(), ref recordCount)) return null; TableSchema ti = CreateTableSchema(dr); CreateColumnSchemas(ti, connectionString, databaseType); if(ti.Columns.Count > 0) di.AddTable(ti); } } // Get the primary key information DataTable pkeys = this.GetOleDbSchema(_callback, connectionString, OleDbSchemaGuid.Primary_Keys, "",schemaFilter,"",""); if (pkeys != null) { if (!StartProgress(_callback, "Building Primary Key Details",pkeys.Rows.Count,ref recordCount)) return null; foreach (DataRow dr in pkeys.Rows) { string pkTable = dr["TABLE_NAME"].ToString(); if (!IncrProgress(_callback, dr["TABLE_NAME"].ToString(), ref recordCount)) return null; TableSchema tip = di[pkTable]; if (tip != null) { ColumnSchema ci = tip[dr["COLUMN_NAME"].ToString()]; if (ci != null) { ci.IsPrimaryKey = true; tip.AddColumn(ci); } } } } // Get the foreign key information DataTable fkeys = this.GetOleDbSchema(_callback, connectionString, OleDbSchemaGuid.Foreign_Keys, "",schemaFilter,"",""); if (fkeys != null) { if (!StartProgress(_callback, "Building Foreign Key Details",fkeys.Rows.Count,ref recordCount)) return null; foreach (DataRow dr in fkeys.Rows) { string fkTable = dr["FK_TABLE_NAME"].ToString(); if (!IncrProgress(_callback, dr["FK_TABLE_NAME"].ToString(), ref recordCount)) return null; TableSchema tif = di[fkTable]; if (tif != null) { ColumnSchema ci = tif[dr["FK_COLUMN_NAME"].ToString()]; if (ci != null) { ci.IsForeignKey = true; tif.AddColumn(ci); } } } } // Setup the Progress Display if one is defined. if (fkeys != null) { if (!StartProgress(_callback, "Building Foreign Key Relationships",fkeys.Rows.Count,ref recordCount)) return null; foreach (DataRow dr in fkeys.Rows) { if (!IncrProgress(_callback, dr["PK_TABLE_NAME"].ToString(), ref recordCount)) return null; // Get the name of the primary key table string pkTable = dr["PK_TABLE_NAME"].ToString(); // Get the name of the foreign key table string fkTable = dr["FK_TABLE_NAME"].ToString(); // Get the name of the foreign key column string fkColumn = dr["FK_COLUMN_NAME"].ToString(); // Get the table containing the primary key TableSchema tif = di[pkTable]; // Get the table containing the foreign key TableSchema fk = di[fkTable]; if (tif != null) { // Get the primary key ColumnSchema ci = tif[dr["PK_COLUMN_NAME"].ToString()]; // Get the foreign key ColumnSchema cf = fk[fkColumn]; if (ci != null) { // Add the association to the table and column containing the foreign key ci.ForeignKeyTables.Add(new ForeignKeyAssociation(ci, cf ,fk)); } } } } if (!EndProgress(_callback, "Finished Loading Tables",true)) return null; } else { if (!EndProgress(_callback, "No database schema information found.",false)) return null; } } else { if (!EndProgress(_callback, "No database schema information found.",false)) return null; } return di; } private TableSchema CreateTableSchema(DataRow dr) { TableSchema ti = new TableSchema(); ti.Alias = dr["TABLE_NAME"].ToString(); ti.Name = dr["TABLE_NAME"].ToString(); ti.TableType = TableTypeConverter.Convert(dr["TABLE_TYPE"].ToString()); return ti; } /// <summary> /// Creates the ColumnSchemas for a specified table /// </summary> /// <param name="ts">The TableSchema to add the ColumnSchema to</param> /// <param name="oledbConnectionString">The OleDb connectionstring to use</param> public void CreateColumnSchemas(TableSchema ts, string oledbConnectionString, Adapdev.Data.DbType databaseType) { DataTable dt = this.GetReaderSchema(oledbConnectionString, ts.Name, databaseType); if (!(dt == null)) { foreach (DataRow dr in dt.Rows) { ColumnSchema ci = new ColumnSchema(); ci.Alias = (string) dr["ColumnName"]; ci.AllowNulls = (bool) dr["AllowDBNull"]; ci.DataTypeId = (int) dr["ProviderType"]; ci.DataType = ProviderInfoManager.GetInstance().GetNameById(dbProviderType, ci.DataTypeId); ci.DefaultTestValue = ProviderInfoManager.GetInstance().GetTestDefaultById(this.dbProviderType, ci.DataTypeId); ci.DefaultValue = ProviderInfoManager.GetInstance().GetDefaultById(this.dbProviderType, ci.DataTypeId); ci.IsAutoIncrement = (bool) dr["IsAutoIncrement"]; ci.IsForeignKey = false; ci.IsPrimaryKey = false; ci.IsUnique = (bool) dr["IsUnique"]; ci.Length = (int) dr["ColumnSize"]; ci.Name = (string) dr["ColumnName"]; ci.NetType = dr["DataType"].ToString(); ci.Ordinal = (int) dr["ColumnOrdinal"]; ci.IsReadOnly = (bool) dr["IsReadOnly"]; ts.AddColumn(ci); } } } /// <summary> /// Gets the OLE db schema. /// </summary> /// <param name="oledbConnectionString">Oledb connection string.</param> /// <param name="guid">GUID.</param> /// <param name="filterCatalog">Filter catalog.</param> /// <param name="filterSchema">Filter schema.</param> /// <param name="filterName">Name of the filter.</param> /// <param name="filterType">Filter type.</param> /// <returns></returns> public DataTable GetOleDbSchema(Adapdev.IProgressCallback _callback, string oledbConnectionString, Guid guid, string filterCatalog, string filterSchema, string filterName, string filterType) { DataTable schemaTable = null; OleDbConnection conn = new OleDbConnection(oledbConnectionString); conn.Open(); try { schemaTable = conn.GetOleDbSchemaTable(guid, GetFilters(guid, filterCatalog, filterSchema, filterName, filterType)); } catch (Exception ex) { if (_callback != null) _callback.AddMessage(ProgressMessageTypes.Critical, "Error obtaining Schema Information: " + ex.Message); } conn.Close(); return schemaTable; } private static object[] GetFilters(Guid guid, string filterCatalog, string filterSchema, string filterName, string filterType) { // Different OleDbSchemaGuid's require a different number of parameters. // These parameter depend on what we are trying to retirve from the database // so this function returns the correct parameter sets. // This should be a Switch statement, but the compiler did not like it. filterCatalog = filterCatalog == string.Empty ? null : filterCatalog; filterSchema = filterSchema == string.Empty ? null : filterSchema; filterName = filterName == string.Empty ? null : filterName; filterType = filterType == string.Empty ? null : filterType; if (guid.Equals(OleDbSchemaGuid.Tables)) return new object[] {filterCatalog, filterSchema, filterName, filterType}; if (guid.Equals(OleDbSchemaGuid.Views)) return new object[] {filterCatalog, filterSchema, filterName}; if (guid.Equals(OleDbSchemaGuid.Primary_Keys)) return new object[] {filterCatalog, filterSchema, filterName}; if (guid.Equals(OleDbSchemaGuid.Foreign_Keys)) return new object[] {filterCatalog, filterSchema, filterName, filterCatalog, filterSchema, filterName}; if (guid.Equals(OleDbSchemaGuid.Columns)) return new object[] {filterCatalog, filterSchema, filterName, string.Empty}; return null; } public StringBuilder PrintOleDbSchema(string oledbConnection, Guid guid, string filter) { StringBuilder sb = new StringBuilder(); DataTable schemaTable; schemaTable = GetOleDbSchema(null, oledbConnection, guid, "","","",filter); foreach (DataRow row in schemaTable.Rows) { foreach (DataColumn column in schemaTable.Columns) { sb.Append("\t\t" + column + " : " + row[column] + "\r\n"); } sb.Append("\r\n"); } sb.Append("\r\n\r\n"); return sb; } public DataTable GetReaderSchema(string oledbConnectionString, string tableName, Adapdev.Data.DbType databaseType) { return GetReaderSchema(new OleDbConnection(), new OleDbCommand(), oledbConnectionString, databaseType, tableName); } private DataTable GetReaderSchema(IDbConnection cn, IDbCommand cmd, string connectionString, Adapdev.Data.DbType databaseType, string tableName) { DataTable schemaTable = null; try { cn.ConnectionString = connectionString; cn.Open(); // Please Note: Use the GetPre and GetPostDelimiters here as in the case of // Oracle using [ ] around a Column Name is not valid. cmd.Connection = cn; cmd.CommandText = "SELECT * FROM " + QueryHelper.GetPreDelimeter(databaseType) + tableName + QueryHelper.GetPostDelimeter(databaseType); IDataReader myReader = cmd.ExecuteReader(CommandBehavior.KeyInfo | CommandBehavior.SchemaOnly); schemaTable = myReader.GetSchemaTable(); myReader.Close(); cn.Close(); } catch (Exception ex) { schemaTable = null; if (_callback != null) _callback.AddMessage(ProgressMessageTypes.Warning, "Could not load Column information for " + tableName + ". " + ex.Message); } return schemaTable; } public StringBuilder PrintOleDbSchema(string oledbConnectionString, Guid guid) { return PrintOleDbSchema(oledbConnectionString, guid, ""); } } } --- NEW FILE: SchemaBuilder.cs --- namespace Adapdev.Data.Schema { using System; using System.Data; using System.Data.OleDb; using System.Text; using Adapdev.Data; using Adapdev.Data.Sql; using MySql.Data.MySqlClient; /// <summary> /// SchemaBuilder builds the schema for a specified database /// </summary> public class SchemaBuilder { private static Adapdev.IProgressCallback _callback; /// <summary> /// Builds the DatabaseSchema for a specified database /// </summary> /// <param name="oledbConnectionString">The OleDb connection to use</param> /// <returns></returns> public static DatabaseSchema CreateDatabaseSchema(string oledbConnectionString, Adapdev.Data.DbType databaseType, DbProviderType providerType) { return SchemaBuilder.CreateDatabaseSchema(oledbConnectionString, databaseType, providerType, "", null); } /// <summary> /// Builds the DatabaseSchema for a specified database /// </summary> /// <param name="oledbConnectionString">The OleDb connection to use</param> /// <param name="providerType">The DbProviderType to set the DatabaseSchema to</param> /// <returns></returns> public static DatabaseSchema CreateDatabaseSchema(string oledbConnectionString, string databaseType, string providerType, string schemaFilter, Adapdev.IProgressCallback progress) { return SchemaBuilder.CreateDatabaseSchema(oledbConnectionString, DbTypeConverter.Convert(databaseType), DbProviderTypeConverter.Convert(providerType), schemaFilter, progress); } /// <summary> /// Builds the DatabaseSchema for a specified database /// </summary> /// <param name="connectionString">The OleDb connection to use</param> /// <param name="providerType">The DbProviderType to set the DatabaseSchema to</param> /// <returns></returns> public static DatabaseSchema CreateDatabaseSchema(string connectionString, Adapdev.Data.DbType databaseType, DbProviderType providerType, string schemaFilter, Adapdev.IProgressCallback progress) { int recordCount = 0; _callback = progress as Adapdev.IProgressCallback; if (_callback != null) { _callback.SetText("Obtaining Schema Details",""); _callback.SetAutoClose(ProgressAutoCloseTypes.WaitOnError); } DatabaseSchema ds = null; switch(providerType) { case DbProviderType.OLEDB: case DbProviderType.SQLSERVER: case DbProviderType.ORACLE: ds = new OleDbSchemaBuilder(_callback, ref recordCount).BuildDatabaseSchema(connectionString, databaseType, providerType, schemaFilter); break; case DbProviderType.MYSQL: ds = new MySqlSchemaBuilder(_callback, ref recordCount).BuildDatabaseSchema(connectionString, databaseType, providerType, schemaFilter); break; } return ds; } // public static StringBuilder PrintReaderSchema(string oledbConnectionString, string table, Adapdev.Data.DbType databaseType) // { // StringBuilder sb = new StringBuilder(); // // DataTable schemaTable; // schemaTable = SchemaBuilder.GetReaderSchema(oledbConnectionString, table, databaseType); // // sb.Append("\r\n=========== " + table + " Schema =====================\r\n\r\n"); // // foreach (DataRow myField in schemaTable.Rows) // { // foreach (DataColumn myProperty in schemaTable.Columns) // { // sb.Append(myProperty.ColumnName + " : " + myField[myProperty].ToString() + "\r\n"); // } // sb.Append("\r\n"); // } // // sb.Append("\r\n\r\n"); // return sb; // } } } --- NEW FILE: ColumnSchemaCollection.cs --- using System; using System.Collections; using Adapdev.Data.Schema; namespace Adapdev.Data.Schema { [Serializable()] public class ColumnSchemaCollection : CollectionBase { public ColumnSchemaCollection() { } public ColumnSchemaCollection(IList value) { this.AddRange(value); } public ColumnSchemaCollection(ColumnSchema[] value) { this.AddRange(value); } public ColumnSchema this[int index] { get { return ((ColumnSchema)(List[index])); } set { List[index] = value; } } public int Add(ColumnSchema value) { return List.Add(value); } public void AddRange(ColumnSchema[] value) { for (int i = 0; (i < value.Length); i = (i + 1)) { this.Add(value[i]); } } public void AddRange(IList value) { for (int i = 0; (i < value.Count); i = (i + 1)) { this.Add((ColumnSchema)value[i]); } } public bool Contains(ColumnSchema value) { return List.Contains(value); } public void CopyTo(ColumnSchema[] array, int index) { List.CopyTo(array, index); } public int IndexOf(ColumnSchema value) { return List.IndexOf(value); } public void Insert(int index, ColumnSchema value) { List.Insert(index, value); } public new ColumnSchemaEnumerator GetEnumerator() { return new ColumnSchemaEnumerator(this); } public void Remove(ColumnSchema value) { List.Remove(value); } } } --- NEW FILE: TableSchemaDictionary.cs --- namespace Adapdev.Data.Schema { using System; using System.Collections; using System.Text; using System.Xml.Serialization; [Serializable] public class TableSchemaDictionary : DictionaryBase, IXmlSerializable { private const string nameSpace = ""; private const string tableDictionaryElement = "TableDictionary"; public TableSchema this[String key] { get { return ((TableSchema) Dictionary[key]); } set { Dictionary[key] = value; } } public ICollection Keys { get { return (Dictionary.Keys); } } public ICollection Values { get { return (Dictionary.Values); } } public void Add(String key, TableSchema value) { Dictionary.Add(key, value); } public bool Contains(String key) { return (Dictionary.Contains(key)); } public void Remove(String key) { Dictionary.Remove(key); } public override string ToString() { StringBuilder sb = new StringBuilder(); foreach (TableSchema ti in this.Values) { sb.Append(ti.ToString()); } return sb.ToString(); } #region IXmlSerializable Members /// <summary> /// XmlWriter that is used to write the TableSchemaDictionary as it implements IDictory that is not serializable /// using the normal methods. This uses the interface IXmlSerializable which isn't offically supported but still /// exists in the next framework /// </summary> /// <param name="writer">System.Xml.XmlWriter</param> public void WriteXml(System.Xml.XmlWriter writer) { XmlSerializer keySer = new XmlSerializer(typeof(String)); XmlSerializer valueSer = new XmlSerializer(typeof(TableSchema)); writer.WriteStartElement(tableDictionaryElement,nameSpace); foreach(object key in Dictionary.Keys){ writer.WriteStartElement("key", nameSpace); keySer.Serialize(writer,key); writer.WriteEndElement(); writer.WriteStartElement("value", nameSpace); object value = Dictionary[key]; valueSer.Serialize(writer, value); writer.WriteEndElement(); } writer.WriteEndElement(); } public System.Xml.Schema.XmlSchema GetSchema() { return null; } /// <summary> /// Custom XmlReader to read the TableSchemaDictionary /// </summary> /// <param name="reader">System.Xml.XmlReader</param> public void ReadXml(System.Xml.XmlReader reader) { XmlSerializer keySer = new XmlSerializer(typeof(String)); XmlSerializer valueSer = new XmlSerializer(typeof(TableSchema)); reader.Read(); reader.ReadStartElement(tableDictionaryElement,nameSpace); while(reader.Name != tableDictionaryElement && reader.NodeType != System.Xml.XmlNodeType.EndElement) { reader.ReadStartElement("key", nameSpace); object key = keySer.Deserialize(reader); reader.ReadEndElement(); reader.ReadStartElement("value", nameSpace); object value = valueSer.Deserialize(reader); reader.ReadEndElement(); Dictionary.Add(key, value); reader.MoveToContent(); //navigate past the end element tags to the next table do{ reader.Skip(); }while(reader.NodeType == System.Xml.XmlNodeType.EndElement && reader.Name != tableDictionaryElement); } reader.ReadEndElement(); } #endregion } } --- NEW FILE: TableSchemaCollection.cs --- using System; using System.Collections; using Adapdev.Data.Schema; namespace Adapdev.Data.Schema { using System.Text; using Adapdev.Text; [Serializable()] public class TableSchemaCollection : CollectionBase { public TableSchemaCollection() { } public TableSchemaCollection(IList value) { this.AddRange(value); } public TableSchemaCollection(TableSchema[] value) { this.AddRange(value); } public TableSchema this[int index] { get { return ((TableSchema)(List[index])); } set { List[index] = value; } } public int Add(TableSchema value) { return List.Add(value); } public void AddRange(TableSchema[] value) { for (int i = 0; (i < value.Length); i = (i + 1)) { this.Add(value[i]); } } public void AddRange(IList value) { for (int i = 0; (i < value.Count); i = (i + 1)) { this.Add((TableSchema)value[i]); } } public bool Contains(TableSchema value) { return List.Contains(value); } public void CopyTo(TableSchema[] array, int index) { List.CopyTo(array, index); } public int IndexOf(TableSchema value) { return List.IndexOf(value); } public void Insert(int index, TableSchema value) { List.Insert(index, value); } public new TableSchemaEnumerator GetEnumerator() { return new TableSchemaEnumerator(this); } public void Remove(TableSchema value) { List.Remove(value); } } } --- NEW FILE: SaveDatabaseSchema.cs --- using System; namespace Adapdev.Data.Schema { using System.IO; using System.Xml.Serialization; /// <summary> /// Summary description for SaveDatabaseSchema. /// </summary> public class SaveDatabaseSchema { private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private DatabaseSchema _dbSchema; private String schemaFile; private String _savedSchemaName; public SaveDatabaseSchema(DatabaseSchema dbSchema, String savedSchemaName) { this._dbSchema = dbSchema; this._savedSchemaName = savedSchemaName; } public void Save() { schemaFile = System.IO.Path.Combine(SchemaConstants.SCHEMAPATH,_savedSchemaName); XmlSerializer dbSerializer = new XmlSerializer(typeof(DatabaseSchema)); StreamWriter schemaWriter = new StreamWriter(schemaFile); dbSerializer.Serialize(schemaWriter, _dbSchema); schemaWriter.Close(); } } } --- NEW FILE: ColumnSchema.cs --- namespace Adapdev.Data.Schema { using System; using System.Collections; using System.Xml.Serialization; using Adapdev.Attributes; using Adapdev.Text; /// <summary> /// Represents the schema for a column in a table /// </summary> /// [Serializable] public class ColumnSchema { private string _name = String.Empty; private string _alias = String.Empty; private int _length; private string _dataType = String.Empty; private int _dataTypeId; private string _netType = String.Empty; private bool _isForeignKey; private bool _isPrimaryKey; private bool _isAutoIncrement; private bool _isUnique; private bool _allowNulls; private bool _active = true; private int _ordinal; private bool _isReadOnly; private string _defaultValue = String.Empty; private string _defaultTestValue = String.Empty; private ArrayList _fkReferences = new ArrayList(); private TableSchema _parent = null; /// <summary> /// Specifies whether the column is readonly /// </summary> [XmlAttribute] [SchemaDataRewritableAttribute(true)] public bool IsReadOnly { get { return this._isReadOnly; } set { this._isReadOnly = value; } } /// <summary> /// Specifies whether the column is active. Used primarily /// for on/off state in GUIs. It allows for a column to still /// be part of a TableSchema, but ignored for various reasons /// </summary> [XmlAttribute] [SchemaDataRewritableAttribute(false)] public bool IsActive { get { return this._active; } set { this._active = value; } } ... [truncated message content] |
From: Sean M. <int...@us...> - 2005-11-16 05:33:37
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev/Text/Indexing/FullText In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv19977/src/Adapdev/Text/Indexing/FullText Added Files: FullTextSearchExpression.cs FullTextSearchIndex.cs FullTextSearchMode.cs ITokenFilter.cs ITokenizer.cs IndexedField.cs IndexedFieldCollection.cs Posting.cs Postings.cs TermOccurenceCollection.cs TermOccurrence.cs Token.cs Log Message: Reposting to the repository after it got hosed --- NEW FILE: FullTextSearchMode.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.FullText { /// <summary> /// Search mode. /// </summary> public enum FullTextSearchMode { /// <summary> /// Include a record in the result if /// any of the words in the search expression /// occurs in the record /// </summary> IncludeAny, /// <summary> /// Include a record in the result only /// if all of the words in the search expression /// occurs in the record /// </summary> IncludeAll } } --- NEW FILE: ITokenFilter.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.FullText { /// <summary> /// Marker interface for token filters. /// </summary> public interface ITokenFilter : ITokenizer { } } --- NEW FILE: FullTextSearchIndex.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 Adapdev.Text.Indexing; using Adapdev.Text.Indexing.FullText.Filters; using Adapdev.Text.Indexing.FullText.Tokenizers; namespace Adapdev.Text.Indexing.FullText { /// <summary> /// An index for full text searches over record objects. /// </summary> /// <remarks> /// <b>The mutating methods of this class (such as /// <see cref="Add" />, <see cref="Remove" /> and /// <see cref="Update" />) /// are not thread-safe, all the /// synchronization work must be done by the /// application.</b><br /><br /> /// Non mutating methods such as the various <see cref="Search" /> /// implementations <b>can be safely called from multiple threads</b> /// simultaneously. /// </remarks> /// <example> /// <code> /// FullTextSearchIndex index = new FullTextSearchIndex(); /// index.Fields.Add("title"); /// index.Fields.Add("author"); /// /// HashtableRecord book1 = new HashtableRecord(); /// book1["title"] = "A Midsummer Night's Dream"; /// book1["author"] = "Shakespeare, William" /// /// HashtableRecord book2 = new HashtableRecord(); /// book2["title"] = "Much Ado About Nothing"; /// book2["author"] = "Shakespeare, William"; /// /// index.Add(book1); /// index.Add(book2); /// /// SearchResult result1 = index.Search("midsummer dream"); /// AssertEquals(1, result1.Count); /// Assert(result1.Contains(book1)); /// /// SearchResult result2 = index.Search("shakespeare"); /// result2.SortByField("title"); /// /// AssertEquals(2, result2.Count); /// AssertEquals(book1, result2[0].Record); /// AssertEquals(book2, result2[1].Record); /// </code> /// </example> [Serializable] public class FullTextSearchIndex : IIndex { /// <summary> /// A filter that considers only tokens with more than 2 characters /// and replaces special characters (like '', '') by their /// simpler counterparts ('c', 'a'). /// </summary> public static ITokenFilter DefaultFilter = new SpecialCharactersFilter(new TokenLengthFilter(3)); IndexedFieldCollection _fields; Hashtable _postings; ITokenFilter _filter = FullTextSearchIndex.DefaultFilter; /// <summary> /// Creates an empty index. /// </summary> public FullTextSearchIndex() { _fields = new IndexedFieldCollection(); _postings = new Hashtable(); } /// <summary> /// Creates an empty index with a specific filter /// chain for token filtering. /// </summary> /// <param name="filter">the filter chain that /// should be used by the index to filter /// tokens</param> public FullTextSearchIndex(ITokenFilter filter) : this() { Filter = filter; } /// <summary> /// Gets/sets the filter chain that will be used /// for all text preprocessing /// </summary> public ITokenFilter Filter { get { return _filter; } set { if (null == value) { throw new ArgumentNullException("value", "Filter cannot be null!"); } _filter = value; } } /// <summary> /// Returns a snapshot of all the Postings held /// by this index. Each Postings instance represents /// a currently indexed term and all its occurrences. /// </summary> public Postings[] Postings { get { Postings[] postings = new Postings[_postings.Count]; _postings.Values.CopyTo(postings, 0); return postings; } } /// <summary> /// Returns a snapshot of all the records currently /// held by this index. /// </summary> public IRecord[] Records { get { Hashtable records = new Hashtable(); foreach (Postings postings in _postings.Values) { foreach (IRecord record in postings.Records) { records[record] = null; } } IRecord[] returnValue = new IRecord[records.Count]; records.Keys.CopyTo(returnValue, 0); return returnValue; } } /// <summary> /// Collection of fields that compose the index. /// </summary> public IndexedFieldCollection Fields { get { return _fields; } } #region Implementation of IIndex /// <summary> /// See <see cref="Adapdev.Text.Indexing.IIndex.Add"/> for details. /// </summary> /// <param name="record">record that should be indexed</param> /// <remarks> /// Indexes all the fields included in the /// <see cref="Fields"/> collection. Notice /// however that the record is never automatically /// reindexed should its fields change or should /// the collection of indexed fields (<see cref="Fields"/>) /// change.<br /> /// The application is always responsible for calling /// <see cref="Update"/> in such cases. /// </remarks> public void Add(Adapdev.Text.Indexing.IRecord record) { foreach (IndexedField field in _fields) { IndexByField(record, field); } } public void Clear() { _postings.Clear(); } /// <summary> /// See <see cref="Adapdev.Text.Indexing.IIndex.Remove"/> for details. /// </summary> /// <param name="record">record that should be removed from the index</param> /// <remarks>reference comparison is always used</remarks> public void Remove(Adapdev.Text.Indexing.IRecord record) { foreach (Postings postings in _postings.Values) { postings.Remove(record); } } /// <summary> /// See <see cref="Adapdev.Text.Indexing.IIndex.Update"/> for details. /// </summary> /// <param name="record">existing record that should have its index information updated</param> /// <remarks>reference comparison is always used</remarks> public void Update(Adapdev.Text.Indexing.IRecord record) { Remove(record); Add(record); } /// <summary> /// When the expression passed as argument is an instance /// of FullTextSearchExpression this method behaves exactly /// as <see cref="Search(FullTextSearchExpression)" />, otherwise /// it behaves as expression.Evaluate(this). /// </summary> /// <param name="expression">search expression</param> /// <returns>the result of applying the search against this index</returns> public Adapdev.Text.Indexing.SearchResult Search(Adapdev.Text.Indexing.ISearchExpression expression) { FullTextSearchExpression ftexpression = expression as FullTextSearchExpression; if (null != ftexpression) { return Search(ftexpression); } return expression.Evaluate(this); } #endregion /// <summary> /// Convenience method that creates a new <see cref="FullTextSearchExpression"/> /// for the expression passed as argument and calls /// <see cref="Search(FullTextSearchExpression)"/>. /// </summary> /// <param name="expression">search expression</param> /// <returns><see cref="Search(FullTextSearchExpression)"/></returns> public Adapdev.Text.Indexing.SearchResult Search(string expression) { return Search(new FullTextSearchExpression(expression)); } /// <summary> /// Searches the index for the words included in /// the expression passed as argument. <br /> /// All the fields are searched for every word /// in the expression.<br /> /// </summary> /// <param name="expression">search expression</param> /// <returns> /// When expression.SearchMode is /// <see cref="FullTextSearchMode.IncludeAny"/> every /// record for which at least one word in the expression /// implies a match will be returned.<br /> /// When expression.SearchMode is /// <see cref="FullTextSearchMode.IncludeAll" /> only /// those records for which all of the words in the expression /// imply a match will be returned. /// </returns> public Adapdev.Text.Indexing.SearchResult Search(FullTextSearchExpression expression) { ITokenizer tokenizer = CreateTokenizer(expression.Expression); Token token = tokenizer.NextToken(); if (null == token) { throw new ArgumentException("Invalid search expression. The expression must contain at least one valid token!", "expression"); } long begin = System.Environment.TickCount; SearchResult result = null; if (expression.SearchMode == FullTextSearchMode.IncludeAny) { result = IncludeAny(tokenizer, token); } else { result = IncludeAll(tokenizer, token); } result.ElapsedTime = System.Environment.TickCount - begin; return result; } SearchResult IncludeAny(ITokenizer tokenizer, Token token) { SearchResult result = new SearchResult(); while (null != token) { SearchToken(result, token); token = tokenizer.NextToken(); } return result; } SearchResult IncludeAll(ITokenizer tokenizer, Token token) { ArrayList results = new ArrayList(); while (null != token) { SearchResult tokenResult = new SearchResult(); SearchToken(tokenResult, token); results.Add(tokenResult); token = tokenizer.NextToken(); } SearchResult result = (SearchResult)results[0]; for (int i=1; i<results.Count && result.Count > 0; ++i) { result = result.Intersect((SearchResult)results[i]); } return result; } void IndexByField(IRecord record, IndexedField field) { string value = (string)record[field.Name]; ITokenizer tokenizer = CreateTokenizer(value); Token token = tokenizer.NextToken(); while (null != token) { IndexByToken(token, record, field); token = tokenizer.NextToken(); } } void IndexByToken(Token token, IRecord record, IndexedField field) { Postings postings = (Postings)_postings[token.Value]; if (null == postings) { postings = new Postings(token.Value); _postings[token.Value] = postings; } postings.Add(record, field, token.Position); } void SearchToken(SearchResult result, Token token) { Postings postings = (Postings)_postings[token.Value]; if (null != postings) { AddToResult(result, postings); } } void AddToResult(SearchResult result, Postings found) { foreach (Posting posting in found) { result.Add(new SearchHit(posting.Record)); } } ITokenizer CreateTokenizer(string value) { if (null == value || 0 == value.Length) { return NullTokenizer.Instance; } return _filter.Clone(new StringTokenizer(value)); } } } --- NEW FILE: Postings.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.Text; namespace Adapdev.Text.Indexing.FullText { /// <summary> /// A collection of Posting objects for a /// specific term.<br /> /// Posting objects are indexed by record for /// fast Add and Remove operations. /// </summary> [Serializable] public class Postings : System.Collections.IEnumerable { Hashtable _postings; string _term; /// <summary> /// Creates a new Postings object for /// a term. /// </summary> /// <param name="term">the term</param> public Postings(string term) { _term = term; _postings = new Hashtable(); } /// <summary> /// the term /// </summary> public string Term { get { return _term; } } /// <summary> /// Returns a snapshot of all the /// records currently indexed by the term /// </summary> public IRecord[] Records { get { IRecord[] records = new IRecord[_postings.Count]; _postings.Keys.CopyTo(records, 0); return records; } } /// <summary> /// Adds a new occurrence of the term. The occurrence /// information (field and position) will be added /// to an existing Posting object whenever possible. /// </summary> /// <param name="record">the record where the term was found</param> /// <param name="field">the field where the term was found</param> /// <param name="position">the position in the field where the term was found</param> public void Add(IRecord record, IndexedField field, int position) { Posting posting = _postings[record] as Posting; if (null == posting) { posting = new Posting(record); _postings[record] = posting; } posting.Occurrences.Add(field, position); } /// <summary> /// Removes all information related to a /// specific record from this object. /// </summary> /// <param name="record">the record to be removed</param> public void Remove(IRecord record) { _postings.Remove(record); } /// <summary> /// Enumerates through all the Posting objects. /// </summary> /// <returns></returns> public System.Collections.IEnumerator GetEnumerator() { return _postings.Values.GetEnumerator(); } /// <summary> /// Builds a readable representation of this object. /// </summary> /// <returns></returns> public override string ToString() { StringBuilder builder = new StringBuilder(); builder.Append(_term); builder.Append(" => ["); foreach (Posting posting in _postings.Values) { builder.Append(posting.ToString()); builder.Append(", "); } if (builder.Length > 1) { builder.Remove(builder.Length-2, 2); } builder.Append("]"); return builder.ToString(); } } } --- NEW FILE: ITokenizer.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.FullText { /// <summary> /// A tokenizer is a source of or a filter for <see cref="Token"/> objects. /// </summary> public interface ITokenizer { /// <summary> /// For chaining tokenizers together. /// </summary> ITokenizer Previous { get; set; } /// <summary> /// Clone the tokenizer. If the tokenizer /// supports chaining it should also clone /// the Previous tokenizer in the chain. If /// Previous is null the value of the tail /// parameter should be used instead (but without cloning /// the tail). /// </summary> /// <param name="tail">the last tokenizer in the chain</param> /// <example> /// <code> /// public ITokenizer Clone(ITokenizer tail) /// { /// ITokenizer clone = this.MemberwiseClone() as ITokenizer; /// if (null == this.Previous) /// { /// clone.Previous = tail; /// } /// else /// { /// clone.Previous = this.Previous.Clone(tail); /// } /// return clone; /// } /// </code> /// </example> ITokenizer Clone(ITokenizer tail); /// <summary> /// Retrieves the next token. /// </summary> /// <returns> /// next token or null if no more tokens /// are available. /// </returns> Token NextToken(); } } --- NEW FILE: Posting.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.FullText { /// <summary> /// A Posting object represents the occurrence /// of a term in a record and stores all /// the information associated to this occurrence /// (in which fields does the term occur? how many /// times?).<br /> /// The term itself is not stored in the posting but /// should be used to index the posting in a /// dictionary. /// </summary> [Serializable] public class Posting { IRecord _record; TermOccurrenceCollection _occurrences; /// <summary> /// Creates a new posting for a record. /// </summary> /// <param name="record">the record</param> public Posting(IRecord record) { _record = record; _occurrences = new TermOccurrenceCollection(); } /// <summary> /// Occurrences of the term in the record. /// </summary> internal TermOccurrenceCollection Occurrences { get { return _occurrences; } } /// <summary> /// The record. /// </summary> public IRecord Record { get { return _record; } } /// <summary> /// Builds a more friendly representation of this object. /// </summary> /// <returns></returns> public override string ToString() { return "<" + _record + " => " + _occurrences + ">"; } } } --- NEW FILE: TermOccurrence.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.Text; namespace Adapdev.Text.Indexing.FullText { /// <summary> /// Answers the questions: /// <list type="bullet"> /// <item>in which field does the term occur?</item> /// <item>how many times does the term occur in that specific field?</item> /// <item>in which positions?</item> /// </list> /// This information can be used for ranking the search and /// for specific search types such as proximity search, /// searching for terms only in specific fields, etc. /// </summary> [Serializable] public class TermOccurrence { IndexedField _field; int[] _positions; /// <summary> /// Creates a new TermOccurrence for the /// field and position passed as arguments. /// </summary> /// <param name="field">the field where the term was found</param> /// <param name="position">the position where the term was found</param> public TermOccurrence(IndexedField field, int position) { _field = field; _positions = new int[] { position }; } /// <summary> /// Field where the term was found /// </summary> public IndexedField Field { get { return _field; } } /// <summary> /// Positions in the field where /// the term was found. /// </summary> public int[] Positions { get { return _positions; } } internal void Add(int position) { int[] newPositions = new int[_positions.Length + 1]; Array.Copy(_positions, newPositions, _positions.Length); newPositions[_positions.Length] = position; } /// <summary> /// More readable representation of the object. /// </summary> /// <returns></returns> public override string ToString() { StringBuilder builder = new StringBuilder(); builder.Append("<"); builder.Append(_field.ToString()); builder.Append(" => "); builder.Append("["); for (int i=0; i<_positions.Length; ++i) { builder.Append(_positions[i]); builder.Append(", "); } builder.Append("]"); return builder.ToString(); } } } --- NEW FILE: FullTextSearchExpression.cs --- #region license // Bamboo.Prevalence - a .NET object prevalence engine // Copyright (C) 2004 Rodrigo B. de Oliveira // // Based on the original concept and implementation of Prevayler (TM) // by Klaus Wuestefeld. Visit http://www.prevayler.org for details. // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, // and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE // OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // Contact Information // // http://bbooprevalence.sourceforge.net // mailto:rod...@us... #endregion using System; using Adapdev.Text.Indexing; namespace Adapdev.Text.Indexing.FullText { /// <summary> /// Search expression class for searches over /// a <see cref="FullTextSearchIndex"/>. /// </summary> [Serializable] public class FullTextSearchExpression : ISearchExpression { string _expression; FullTextSearchMode _mode; /// <summary> /// Creates a new search expression that will /// return all the records that include any of /// the words (<see cref="FullTextSearchMode.IncludeAny"/>) /// in the expression passed as argument. /// </summary> /// <param name="expression">words to search for</param> public FullTextSearchExpression(string expression) { _expression = expression; _mode = FullTextSearchMode.IncludeAny; } /// <summary> /// Creates a new search expression for /// the words in the expression argument /// with the specific behavior indicated by the mode /// argument. /// </summary> /// <param name="expression">words to search for</param> /// <param name="mode">search mode</param> public FullTextSearchExpression(string expression, FullTextSearchMode mode) { _expression = expression; _mode = mode; } /// <summary> /// Search expression /// </summary> public string Expression { get { return _expression; } } /// <summary> /// Search mode /// </summary> public FullTextSearchMode SearchMode { get { return _mode; } } #region Implementation of ISearchExpression /// <summary> /// Delegates to <see cref="Adapdev.Text.Indexing.FullText.FullTextSearchIndex.Search"/>. /// </summary> /// <param name="index">index</param> /// <returns></returns> /// <exception cref="ArgumentException">if the /// index argument is not of the correct type</exception> public Adapdev.Text.Indexing.SearchResult Evaluate(Adapdev.Text.Indexing.IIndex index) { FullTextSearchIndex ftindex = index as FullTextSearchIndex; if (null == ftindex) { throw new ArgumentException("FullTextSearchExpression objects can be evaluated against FullTextSearchIndex objects only!"); } return ftindex.Search(this); } #endregion } } --- NEW FILE: IndexedFieldCollection.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.FullText { /// <summary> /// Definition of the fields that will be used /// to compose a <see cref="FullTextSearchIndex"/>. /// </summary> [Serializable] public class IndexedFieldCollection : CollectionBase { /// <summary> /// Creates an empty collection. /// </summary> public IndexedFieldCollection() { } /// <summary> /// Adds a new IndexedField to the collection /// for the field with name passed as argument. /// </summary> /// <param name="field">name of the /// record field to be indexed</param> public void Add(string field) { InnerList.Add(new IndexedField(field)); } } } --- NEW FILE: TermOccurenceCollection.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.Text; namespace Adapdev.Text.Indexing.FullText { /// <summary> /// A collection of TermOccurrence objects. /// </summary> [Serializable] public class TermOccurrenceCollection : CollectionBase { /// <summary> /// Creates an empty collection. /// </summary> public TermOccurrenceCollection() { } /// <summary> /// Adds the information related to the new /// occurrence of the term in the field and /// position passed as argument. If a TermOccurrence /// object for the specified field /// is already in the collection, the new position /// information is simply added to the existing /// TermOccurrence object. Otherwise a new TermOccurrence /// object will be created and added to the /// collection. /// </summary> /// <param name="field">field where the term /// was found</param> /// <param name="position"> /// position in the field where the term was found</param> public void Add(IndexedField field, int position) { foreach (TermOccurrence to in InnerList) { if (to.Field == field) { to.Add(position); return; } } InnerList.Add(new TermOccurrence(field, position)); } /// <summary> /// Builds a readable representation of this object. /// </summary> /// <returns></returns> public override string ToString() { StringBuilder builder = new StringBuilder(); builder.Append("["); foreach (TermOccurrence to in InnerList) { builder.Append(to.ToString()); builder.Append(", "); } builder.Append("]"); return builder.ToString(); } } } --- NEW FILE: IndexedField.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.FullText { /// <summary> /// Metadata for a field that should be indexed /// for full text searching. /// </summary> [Serializable] public class IndexedField { string _name; /// <summary> /// Creates a new IndexedField. /// </summary> /// <param name="name">name of the record field /// to be indexed</param> public IndexedField(string name) { _name = name; } /// <summary> /// Record's field name /// </summary> public string Name { get { return _name; } } /// <summary> /// Builds a more friendly representation of this object. /// </summary> /// <returns></returns> public override string ToString() { return "<IndexedField \"" + _name + "\">"; } } } --- NEW FILE: Token.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.FullText { /// <summary> /// A token. /// </summary> [Serializable] public class Token { int _position; string _value; /// <summary> /// Creates a new token. /// </summary> /// <param name="value">token image</param> /// <param name="position">absolute position of the /// image in the original text</param> public Token(string value, int position) { if (null == value) { throw new ArgumentNullException("value"); } if (position < 0) { throw new ArgumentOutOfRangeException("occurrences", "position must be a positive number"); } _value = value; _position = position; } /// <summary> /// Token image /// </summary> public string Value { get { return _value; } set { if (null == value) { throw new ArgumentNullException("value"); } _value = value; } } /// <summary> /// Absolute position in the original text from /// which this token was extracted. /// </summary> public int Position { get { return _position; } } /// <summary> /// Tokens are equal if both properties, /// Value and Position, are considered /// equal. /// </summary> /// <param name="other">object to test equality for</param> /// <returns>true if the objects are considered equal</returns> public override bool Equals(object other) { Token token = other as Token; if (null == token) { return false; } return _position == token._position && _value == token._value; } /// <summary> /// Calculates a hashcode based on the properties /// Value and Position. /// </summary> /// <returns>the combined hashcode of both properties</returns> public override int GetHashCode() { return _position.GetHashCode() ^ _value.GetHashCode(); } /// <summary> /// Builds a more human friendly representation of the token. /// </summary> /// <returns>a readable representation of the token</returns> public override string ToString() { return "<\"" + _value + "\" at " + _position + ">"; } } } |
From: Sean M. <int...@us...> - 2005-11-16 05:33:37
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.Data.Tests/CategoriesExample In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv19977/src/Adapdev.Data.Tests/CategoriesExample Added Files: CategoriesDAO.cs CategoriesDAOBase.cs CategoriesEntity.cs CategoriesEntityBase.cs CategoriesEntityCollection.cs CategoriesEntityDictionary.cs CategoriesEntityEnumerator.cs DbConstants.cs MockCategories.cs Log Message: Reposting to the repository after it got hosed --- NEW FILE: CategoriesDAO.cs --- /****************************************** * Auto-generated by Codus * 9/30/2005 5:18:20 PM ******************************************/ using System; using System.Data; using System.Data.Common; using Adapdev.Data; using Adapdev.Data.Sql; namespace Test { /// <summary> /// Data Access Object for the Categories table. /// </summary> /// <remarks> /// All generated functionality is part of the CategoriesDAOBase class. All /// custom implementations should be done in this class. /// </remarks> public class CategoriesDAO : Test.CategoriesDAOBase { } } --- NEW FILE: CategoriesDAOBase.cs --- /****************************************** * Auto-generated by Codus * 9/30/2005 5:18:20 PM ******************************************/ using System; using System.Collections; using System.Data; using System.Data.Common; using Adapdev.Data; using Adapdev.Data.Sql; namespace Test { /// <summary> /// Base Data Access Object for the Categories table. /// </summary> public abstract class CategoriesDAOBase : Adapdev.Data.AbstractDAO { /// <summary> /// A static representation of column CategoryID /// </summary> public static readonly string COLUMN_CATEGORYID = "CategoryID"; /// <summary> /// A static representation of column CategoryName /// </summary> public static readonly string COLUMN_CATEGORYNAME = "CategoryName"; /// <summary> /// A static representation of column Description /// </summary> public static readonly string COLUMN_DESCRIPTION = "Description"; /// <summary> /// A static representation of column Picture /// </summary> public static readonly string COLUMN_PICTURE = "Picture"; /// <summary> /// Provides access to the name of the primary key column (CategoryID) /// </summary> public static readonly string TABLE_PRIMARYKEY = "CategoryID"; /// <summary> /// Provides access to the name of the table /// </summary> public static readonly string TABLE_NAME = "Categories"; /// <summary> /// Provides access to the name of the database /// </summary> public static readonly string DATABASE_NAME = "Northwind"; /// <summary> /// Constructor /// </summary> public CategoriesDAOBase() : base(DbConstants.DatabaseProviderType, DbConstants.DatabaseType, "Categories", DbConstants.ConnectionString) { } /// <summary> /// Maps the IDataReader values to a CategoriesEntity object /// </summary> /// <param name="r">The IDataReader to map</param> /// <returns>CategoriesEntity</returns> protected override object MapObject(System.Data.IDataReader r) { CategoriesEntity entity = new CategoriesEntity(); try{ int ordinal = r.GetOrdinal("CategoryID"); if (!r.IsDBNull(ordinal)) entity.CategoryID = ((System.Int32)(r.GetValue(ordinal))); } catch(Exception){} try{ int ordinal = r.GetOrdinal("CategoryName"); if (!r.IsDBNull(ordinal)) entity.CategoryName = ((System.String)(r.GetValue(ordinal))); } catch(Exception){} try{ int ordinal = r.GetOrdinal("Description"); if (!r.IsDBNull(ordinal)) entity.Description = ((System.String)(r.GetValue(ordinal))); } catch(Exception){} try{ int ordinal = r.GetOrdinal("Picture"); if (!r.IsDBNull(ordinal)) entity.Picture = ((System.Byte[])(r.GetValue(ordinal))); } catch(Exception){} return entity; } /// <summary> /// Creates the sql insert command, using the values from the passed /// in CategoriesEntity object /// </summary> /// <param name="o">A CategoriesEntity object, from which the insert values are pulled</param> /// <returns>An IDbCommand</returns> protected override System.Data.IDbCommand CreateInsertCommand(object o) { CategoriesEntity entity = ((CategoriesEntity)(o)); System.Data.IDbCommand cmd = this.CreateCommand("INSERT INTO [Categories] ( [CategoryName], [Description], [Picture] ) VALUES ( @CategoryName, @Description, @Picture ) "); IDataParameterCollection cmdParams = cmd.Parameters; System.Data.IDbDataParameter parCategoryName = cmd.CreateParameter(); parCategoryName.ParameterName = "@CategoryName"; parCategoryName.Value = entity.CategoryName; cmdParams.Add(parCategoryName); System.Data.IDbDataParameter parDescription = cmd.CreateParameter(); parDescription.ParameterName = "@Description"; parDescription.Value = entity.Description; cmdParams.Add(parDescription); System.Data.IDbDataParameter parPicture = cmd.CreateParameter(); parPicture.ParameterName = "@Picture"; parPicture.Value = entity.Picture; cmdParams.Add(parPicture); return cmd; } /// <summary> /// Creates the sql update command, using the values from the passed /// in CategoriesEntity object /// </summary> /// <param name="o">A CategoriesEntity object, from which the update values are pulled</param> /// <returns>An IDbCommand</returns> protected override System.Data.IDbCommand CreateUpdateCommand(object o) { CategoriesEntity entity = ((CategoriesEntity)(o)); System.Data.IDbCommand cmd = this.CreateCommand("UPDATE [Categories] SET [CategoryName] = @CategoryName, [Description] = @Description, [Picture] = @Picture WHERE [CategoryID] = @CategoryID "); IDataParameterCollection cmdParams = cmd.Parameters; System.Data.IDbDataParameter parCategoryName = cmd.CreateParameter(); parCategoryName.ParameterName = "@CategoryName"; parCategoryName.Value = entity.CategoryName; cmdParams.Add(parCategoryName); System.Data.IDbDataParameter parDescription = cmd.CreateParameter(); parDescription.ParameterName = "@Description"; parDescription.Value = entity.Description; cmdParams.Add(parDescription); System.Data.IDbDataParameter parPicture = cmd.CreateParameter(); parPicture.ParameterName = "@Picture"; parPicture.Value = entity.Picture; cmdParams.Add(parPicture); System.Data.IDbDataParameter pkparCategoryID = cmd.CreateParameter(); pkparCategoryID.ParameterName = "@CategoryID"; pkparCategoryID.Value = entity.CategoryID; cmdParams.Add(pkparCategoryID); return cmd; } /// <summary> /// Creates the sql delete command, using the passed in primary key /// </summary> /// <param name="id">The primary key of the object to delete</param> /// <returns>An IDbCommand</returns> protected override System.Data.IDbCommand CreateDeleteOneCommand(object id) { System.Data.IDbCommand cmd = this.CreateCommand("DELETE FROM [Categories] WHERE [CategoryID] = @CategoryID "); IDataParameterCollection cmdParams = cmd.Parameters; System.Data.IDbDataParameter par = cmd.CreateParameter(); par.ParameterName = "@CategoryID"; par.Value = id; cmdParams.Add(par); return cmd; } /// <summary> /// Creates the sql select command, using the passed in primary key /// </summary> /// <param name="o">The primary key of the object to select</param> /// <returns>An IDbCommand</returns> protected override System.Data.IDbCommand CreateSelectOneCommand(object id) { System.Data.IDbCommand cmd = this.CreateCommand("SELECT [CategoryID], [CategoryName], [Description], [Picture] FROM [Categories] WHERE [CategoryID] = @CategoryID "); IDataParameterCollection cmdParams = cmd.Parameters; System.Data.IDbDataParameter par = cmd.CreateParameter(); par.ParameterName = "@CategoryID"; par.Value = id; cmdParams.Add(par); return cmd; } protected override void CustomSave(object o, IDbConnection connection){ string query = QueryHelper.GetSqlServerLastInsertedScopeCommand(); //string query = QueryHelper.GetSqlServerLastInsertedCommand(CategoriesDAO.TABLE_NAME); IDbCommand cmd = DbProviderFactory.CreateCommand(DbConstants.DatabaseProviderType); cmd.CommandText = query; cmd.Connection = connection; object id = cmd.ExecuteScalar(); this.MapIdentity(o as CategoriesEntity, id); } protected override void CustomSave(object o, IDbConnection connection, IDbTransaction transaction){ string query = QueryHelper.GetSqlServerLastInsertedScopeCommand(); //string query = QueryHelper.GetSqlServerLastInsertedCommand(CategoriesDAO.TABLE_NAME); IDbCommand cmd = DbProviderFactory.CreateCommand(DbConstants.DatabaseProviderType); cmd.CommandText = query; cmd.Transaction = transaction; cmd.Connection = connection; object id = cmd.ExecuteScalar(); this.MapIdentity(o as CategoriesEntity, id); } private void MapIdentity(CategoriesEntity entity, object id){ entity.CategoryID = Convert.ToInt32(id); } } } --- NEW FILE: CategoriesEntity.cs --- /****************************************** * Auto-generated by Codus * 9/30/2005 5:18:19 PM ******************************************/ using System; using Test.Collections; using Adapdev.Text; namespace Test { /// <summary> /// An object representation of the Northwind Categories table /// </summary> [Serializable] public class CategoriesEntity : CategoriesEntityBase{ } } --- NEW FILE: CategoriesEntityBase.cs --- /****************************************** * Auto-generated by Codus * 9/30/2005 5:18:19 PM ******************************************/ using System; using System.Xml.Serialization; using Test.Collections; using Adapdev.Text; namespace Test { /// <summary> /// An object representation of the Northwind Categories table /// </summary> [Serializable] public abstract class CategoriesEntityBase{ private System.Int32 _CategoryID = 0; private System.String _CategoryName = ""; private System.String _Description = ""; private System.Byte[] _Picture = null; [XmlElement(ElementName = "CategoryID")] public System.Int32 CategoryID { get { return this._CategoryID; } set { this._CategoryID = value; } } [XmlElement(ElementName = "CategoryName")] public System.String CategoryName { get { return this._CategoryName; } set { this._CategoryName = value; } } [XmlElement(ElementName = "Description")] public System.String Description { get { return this._Description; } set { this._Description = value; } } [XmlElement(ElementName = "Picture")] public System.Byte[] Picture { get { return this._Picture; } set { this._Picture = 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); } // public ProductsEntityCollection ProductsByCategoryID{ // get{return new ProductsEntityCollection(new ProductsDAO().SelectAllByCategoryID(this._CategoryID));} // } } } --- NEW FILE: CategoriesEntityCollection.cs --- /****************************************** * Auto-generated by Codus * 9/30/2005 5:18:19 PM ******************************************/ using System; using System.Collections; using Adapdev.Collections; using Test; namespace Test.Collections { [Serializable()] public class CategoriesEntityCollection : SortableCollectionBase { public CategoriesEntityCollection() { } public CategoriesEntityCollection(IList value) { this.AddRange(value); } public CategoriesEntityCollection(CategoriesEntity[] value) { this.AddRange(value); } public CategoriesEntity this[int index] { get { return ((CategoriesEntity)(List[index])); } set { List[index] = value; } } public int Add(CategoriesEntity value) { return List.Add(value); } public void AddRange(CategoriesEntity[] value) { for (int i = 0; (i < value.Length); i = (i + 1)) { this.Add(value[i]); } } public void AddRange(IList value) { for (int i = 0; (i < value.Count); i = (i + 1)) { this.Add((CategoriesEntity)value[i]); } } public bool Contains(CategoriesEntity value) { return List.Contains(value); } public void CopyTo(CategoriesEntity[] array, int index) { List.CopyTo(array, index); } public int IndexOf(CategoriesEntity value) { return List.IndexOf(value); } public void Insert(int index, CategoriesEntity value) { List.Insert(index, value); } public new CategoriesEntityEnumerator GetEnumerator() { return new CategoriesEntityEnumerator(this); } public void Remove(CategoriesEntity value) { List.Remove(value); } } } --- NEW FILE: DbConstants.cs --- /****************************************** * Auto-generated by Codus * 9/30/2005 5:18:21 PM ******************************************/ using System; using Adapdev.Data; namespace Test { public class DbConstants { public static readonly Adapdev.Data.DbProviderType DatabaseProviderType = Adapdev.Data.DbProviderType.SQLSERVER; public static readonly Adapdev.Data.DbType DatabaseType = Adapdev.Data.DbType.SQLSERVER; public static readonly string ConnectionString = @"Data Source=localhost; Initial Catalog=northwind; User ID=sa; Password=; Trusted_Connection=false;"; } } --- NEW FILE: MockCategories.cs --- /****************************************** * Auto-generated by Codus * 9/30/2005 5:18:20 PM ******************************************/ using System; using Adapdev.Text; namespace Test.Mock { /// <summary> /// Represents a test instance of a CategoriesEntity object /// </summary> [Serializable] public class MockCategoriesEntity : CategoriesEntity { public MockCategoriesEntity() : base(){ this.CategoryID = 2; this.CategoryName = "test"; this.Description = "test"; this.Picture = System.Text.Encoding.ASCII.GetBytes("Test String2"); } } } --- NEW FILE: CategoriesEntityEnumerator.cs --- /****************************************** * Auto-generated by Codus * 9/30/2005 5:18:20 PM ******************************************/ using System; using System.Collections; using Test; namespace Test.Collections { public class CategoriesEntityEnumerator : IEnumerator { private IEnumerator baseEnumerator; private IEnumerable temp; public CategoriesEntityEnumerator(CategoriesEntityCollection mappings) { this.temp = ((IEnumerable)(mappings)); this.baseEnumerator = temp.GetEnumerator(); } public CategoriesEntityEnumerator(CategoriesEntityDictionary mappings) { this.temp = ((IEnumerable)(mappings)); this.baseEnumerator = temp.GetEnumerator(); } public CategoriesEntity Current { get { return ((CategoriesEntity)(baseEnumerator.Current)); } } object IEnumerator.Current { get { return baseEnumerator.Current; } } public bool MoveNext() { return baseEnumerator.MoveNext(); } bool IEnumerator.MoveNext() { return baseEnumerator.MoveNext(); } public void Reset() { baseEnumerator.Reset(); } void IEnumerator.Reset() { baseEnumerator.Reset(); } } } --- NEW FILE: CategoriesEntityDictionary.cs --- /****************************************** * Auto-generated by Codus * 9/30/2005 5:18:19 PM ******************************************/ using System; using System.Collections; using Test; namespace Test.Collections { public class CategoriesEntityDictionary : DictionaryBase { public CategoriesEntity this[ object key ] { get { return( (CategoriesEntity) Dictionary[key] ); } set { Dictionary[key] = value; } } public ICollection Keys { get { return( Dictionary.Keys ); } } public ICollection Values { get { return( Dictionary.Values ); } } public void Add( String key, String value ) { Dictionary.Add( key, value ); } public bool Contains( String key ) { return( Dictionary.Contains( key ) ); } public void Remove( String key ) { Dictionary.Remove( key ); } } } |
Update of /cvsroot/adapdev/Adapdev/src/Adapdev/Cryptography In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv19977/src/Adapdev/Cryptography Added Files: Crypto.cs DecryptTransformer.cs Decryptor.cs EncryptTransformer.cs EncryptionAlgorithm.cs Encryptor.cs Hasher.cs Log Message: Reposting to the repository after it got hosed --- 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 05:33:37
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev/Text/Indexing/Records In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv19977/src/Adapdev/Text/Indexing/Records Added Files: HashtableRecord.cs Log Message: Reposting to the repository after it got hosed --- NEW FILE: HashtableRecord.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.Records { /// <summary> /// An IRecord implementation over a Hashtable. /// </summary> [Serializable] public class HashtableRecord : Adapdev.Text.Indexing.IRecord { /// <summary> /// The hashtable. /// </summary> protected Hashtable _hashtable; /// <summary> /// Creates an empty record. /// </summary> public HashtableRecord() { _hashtable = new Hashtable(); } /// <summary> /// Sets/Gets a hashtable field. /// </summary> public object this[string name] { get { return _hashtable[name]; } set { _hashtable[name] = value; } } /// <summary> /// Delegates to the internal hashtable. /// </summary> /// <returns></returns> public override int GetHashCode() { return _hashtable.GetHashCode(); } /// <summary> /// Delegates to the internal hashtable. /// </summary> /// <param name="rhs"></param> /// <returns></returns> public override bool Equals(object rhs) { HashtableRecord other = rhs as HashtableRecord; if (null == other) { return false; } return other._hashtable.Equals(_hashtable); } } } |
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.Data/Sql In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv19977/src/Adapdev.Data/Sql Added Files: AccessCriteria.cs AccessDeleteQuery.cs AccessInsertQuery.cs AccessSelectQuery.cs AccessUpdateQuery.cs Criteria.cs CriteriaFactory.cs DeleteQuery.cs DialectConstants.cs ICriteria.cs IDeleteQuery.cs IInsertQuery.cs INonSelectQuery.cs IQuery.cs ISelectQuery.cs IUpdateQuery.cs InsertQuery.cs MySqlCriteria.cs MySqlDeleteQuery.cs MySqlInsertQuery.cs MySqlSelectQuery.cs MySqlUpdateQuery.cs OracleCriteria.cs OracleDeleteQuery.cs OracleInsertQuery.cs OracleSelectQuery.cs OracleUpdateQuery.cs QueryConstants.cs QueryFactory.cs QueryHelper.cs SelectQuery.cs SqlDeleteQuery.cs SqlInsertQuery.cs SqlSelectQuery.cs SqlServerCriteria.cs SqlUpdateQuery.cs UpdateQuery.cs Log Message: Reposting to the repository after it got hosed --- NEW FILE: ICriteria.cs --- namespace Adapdev.Data.Sql { using System.Collections; /// <summary> /// Summary description for ICriteria. /// </summary> public interface ICriteria { void AddAnd(); void AddAndCriteria(ICriteria pc); void AddCriteriaSeparator(CriteriaType ct); void AddBetween(string columnName, object value1, object value2); void AddEqualTo(string columnName, object columnValue); void AddEqualTo(string tableName, string columnName, object columnValue); void AddEqualTo(string columnName); void AddExists(IQuery subQuery); void AddGreaterThanOrEqualTo(string columnName, object columnValue); void AddGreaterThan(string columnName, object columnValue); void AddIn(string columnName, IQuery subQuery); void AddIn(string columnName, ICollection values); void AddIsNull(string columnName); void AddLessThanOrEqualTo(string columnName, object columnValue); void AddLessThan(string columnName, object columnValue); void AddLike(string columnName, object columnValue); void AddNotBetween(string columnName, object value1, object value2); void AddNotEqualTo(string columnName, object columnValue); void AddNotExists(IQuery subQuery); void AddNotIn(string columnName, ICollection values); void AddNotIn(string columnName, IQuery subQuery); void AddNotLike(string columnName, object columnValue); void AddNotNull(string columnName); void AddOr(); void AddOrCriteria(ICriteria pc); void AddSql(string sql); string GetText(); DbProviderType DbProviderType { get; set; } } } --- NEW FILE: OracleCriteria.cs --- namespace Adapdev.Data.Sql { using System.Collections; using System.Text; using Adapdev.Text; /// <summary> /// Summary description for ICriteria. /// </summary> public class OracleCriteria : Criteria { public OracleCriteria() : base(DbType.ORACLE, DbProviderType.ORACLE) { } public OracleCriteria(string sql) : base(DbType.ORACLE, DbProviderType.ORACLE, sql) { } } } --- NEW FILE: QueryHelper.cs --- namespace Adapdev.Data.Sql { using System; using System.Data; using Adapdev.Text; /// <summary> /// Provides common routines for building queries /// </summary> public class QueryHelper { /// <summary> /// Surrounds the object with the proper, datastore-specific markup. /// </summary> /// <param name="o"></param> /// <param name="type"></param> /// <returns></returns> /// <example> /// If the passed in object is a date, and the DbType is Access, then the returned value would be #date#. /// In contrast, if the DbType is SqlServer, then the returned value would be 'date'. /// </example> public static string DressUp(object o, Adapdev.Data.DbType type) { string ro = ""; if (Util.IsNumeric(o)) { ro = o.ToString(); } else if (Util.IsDateTime(o)) { ro = QueryHelper.GetDateDelimeter(type) + o.ToString() + QueryHelper.GetDateDelimeter(type); } // else if(o is Boolean) // { // ro = o.ToString().ToLower(); // } else { ro = QueryHelper.GetStringDelimeter(type) + o.ToString() + QueryHelper.GetStringDelimeter(type); } return ro; } /// <summary> /// Gets the proper date delimiter for the specified DbType /// </summary> /// <param name="type"></param> /// <returns></returns> public static char GetDateDelimeter(Adapdev.Data.DbType type) { switch (type) { case Adapdev.Data.DbType.ACCESS: return DialectConstants.ACCESS_DATE; case Adapdev.Data.DbType.SQLSERVER: return DialectConstants.SQLSERVER_DATE; case Adapdev.Data.DbType.ORACLE: return DialectConstants.ORACLE_DATE; case Adapdev.Data.DbType.MYSQL: return DialectConstants.MYSQL_DATE; default: throw new Exception("DbType " + type + " not supported currently."); } } /// <summary> /// Gets the specified /// </summary> /// <param name="type"></param> /// <returns></returns> public static char GetPreDelimeter(Adapdev.Data.DbType type) { switch (type) { case Adapdev.Data.DbType.ACCESS: return DialectConstants.ACCESS_PREDELIM; case Adapdev.Data.DbType.SQLSERVER: return DialectConstants.SQLSERVER_PREDELIM; case Adapdev.Data.DbType.ORACLE: return DialectConstants.ORACLE_PREDELIM; case Adapdev.Data.DbType.MYSQL: return DialectConstants.MYSQL_PREDELIM; default: throw new Exception("DbType " + type + " not supported currently."); } } /// <summary> /// /// </summary> /// <param name="type"></param> /// <returns></returns> public static char GetPostDelimeter(Adapdev.Data.DbType type) { switch (type) { case Adapdev.Data.DbType.ACCESS: return DialectConstants.ACCESS_POSTDELIM; case Adapdev.Data.DbType.SQLSERVER: return DialectConstants.SQLSERVER_POSTDELIM; case Adapdev.Data.DbType.ORACLE: return DialectConstants.ORACLE_POSTDELIM; case Adapdev.Data.DbType.MYSQL: return DialectConstants.MYSQL_POSTDELIM; default: throw new Exception("DbType " + type + " not supported currently."); } } /// <summary> /// Gets the datastore-specific string delimiter /// </summary> /// <param name="type"></param> /// <returns></returns> public static char GetStringDelimeter(Adapdev.Data.DbType type) { switch (type) { case Adapdev.Data.DbType.ACCESS: return DialectConstants.ACCESS_STRING; case Adapdev.Data.DbType.SQLSERVER: return DialectConstants.SQLSERVER_STRING; case Adapdev.Data.DbType.ORACLE: return DialectConstants.ORACLE_STRING; case Adapdev.Data.DbType.MYSQL: return DialectConstants.MYSQL_STRING; default: throw new Exception("DbType " + type + " not supported currently."); } } /// <summary> /// Gets the provider type specific parameter name /// </summary> /// <param name="columnName"></param> /// <param name="provider"></param> /// <returns></returns> public static string GetParameterName(string columnName, DbProviderType provider) { switch (provider) { case DbProviderType.SQLSERVER: columnName = StringUtil.RemoveSpaces(columnName); return "@" + columnName; case DbProviderType.ORACLE: columnName = StringUtil.RemoveSpaces(columnName); return ":" + columnName; case DbProviderType.OLEDB: return "?"; case DbProviderType.MYSQL: columnName = StringUtil.RemoveSpaces(columnName); return "?" + columnName; default: throw new Exception("DbProviderType " + provider + " is not currently supported."); } } public static string GetSqlServerLastInsertedCommand(string table) { return "SELECT IDENT_CURRENT('" + table + "');"; } public static string GetSqlServerLastInsertedScopeCommand() { return "SELECT SCOPE_IDENTITY();"; } public static string GetAccessLastInsertedCommand(string table, string column) { string s = "SELECT MAX([" + column + "]) FROM [" + table + "];"; Console.WriteLine(s); return s; } public static string GetOracleLastInsertedCommand(string table, string column) { string s = "SELECT MAX(" + column + ") FROM " + table + ";"; Console.WriteLine(s); return s; } public static string GetMySqlLastInsertedCommand(string table, string column) { string s = "SELECT `" + column + "` FROM `" + table + "` ORDER BY `" + column + "` DESC LIMIT 1"; Console.WriteLine(s); return s; } } } --- NEW FILE: DeleteQuery.cs --- namespace Adapdev.Data.Sql { using System.Text; public abstract class DeleteQuery : IDeleteQuery { protected string _table = ""; protected StringBuilder sb = new StringBuilder(); protected ICriteria criteria = null; protected DbType type = DbType.SQLSERVER; protected DbProviderType provider = DbProviderType.SQLSERVER; public DeleteQuery(DbType type, DbProviderType provider) { this.type = type; this.provider = provider; } public DeleteQuery(DbType type, DbProviderType provider, string tableName) : this(type, provider) { this.SetTable(tableName); } public void SetCriteria(ICriteria c) { criteria = c; } public void SetTable(string tableName) { this._table = QueryHelper.GetPreDelimeter(this.type) + tableName + QueryHelper.GetPostDelimeter(this.type); } public ICriteria CreateCriteria() { return CriteriaFactory.CreateCriteria(this.type); } public virtual string GetText() { return "DELETE FROM " + this._table + this.GetCriteria(); } protected string GetCriteria() { if (this.criteria == null) return ""; else return criteria.GetText(); } public DbProviderType DbProviderType { get { return this.provider; } set { this.provider = value; } } } } --- NEW FILE: SqlInsertQuery.cs --- namespace Adapdev.Data.Sql { /// <summary> /// Summary description for SqlInsertQuery. /// </summary> public class SqlInsertQuery : InsertQuery { public SqlInsertQuery() : base(DbType.SQLSERVER, DbProviderType.SQLSERVER) { } public SqlInsertQuery(string tableName) : base(DbType.SQLSERVER, DbProviderType.SQLSERVER, tableName) { } } } --- NEW FILE: MySqlSelectQuery.cs --- using System; namespace Adapdev.Data.Sql { /// <summary> /// Summary description for MySqlSelectQuery. /// </summary> public class MySqlSelectQuery : SelectQuery { public MySqlSelectQuery():base(DbType.MYSQL, DbProviderType.MYSQL){} public MySqlSelectQuery(string table):base(DbType.MYSQL, DbProviderType.MYSQL, table){} protected override string GetLimit() { if (maxRecords > 0) { return " LIMIT " + maxRecords; } return ""; } public override string GetText() { return "SELECT " + this.GetColumns() + " FROM " + this._table + this._join + this.GetCriteria() + this.GetOrderBy() + this.GetGroupBy() + this.GetLimit(); } } } --- NEW FILE: SqlUpdateQuery.cs --- namespace Adapdev.Data.Sql { /// <summary> /// Summary description for UpdateQuery. /// </summary> public class SqlUpdateQuery : UpdateQuery { public SqlUpdateQuery() : base(DbType.SQLSERVER, DbProviderType.SQLSERVER) { } public SqlUpdateQuery(string tableName) : base(DbType.SQLSERVER, DbProviderType.SQLSERVER, tableName) { } } } --- NEW FILE: OracleDeleteQuery.cs --- namespace Adapdev.Data.Sql { /// <summary> /// Summary description for SqlDeleteQuery. /// </summary> public class OracleDeleteQuery : DeleteQuery { public OracleDeleteQuery() : base(DbType.ORACLE, DbProviderType.ORACLE) { } public OracleDeleteQuery(string tableName) : base(DbType.ORACLE, DbProviderType.ORACLE, tableName) { } } } --- NEW FILE: ISelectQuery.cs --- namespace Adapdev.Data.Sql { /// <summary> /// Summary description for ISelectQuery. /// </summary> public interface ISelectQuery : IQuery { /// <summary> /// Adds the specified column /// </summary> /// <param name="columnName">The name of the column</param> void Add(string columnName); /// <summary> /// Adds the specified table.column /// </summary> /// <param name="tableName">Name of the table.</param> /// <param name="columnName">Name of the column.</param> void Add(string tableName, string columnName); /// <summary> /// Adds the column alias. /// </summary> /// <param name="tableName">Name of the table.</param> /// <param name="columnName">Name of the column.</param> /// <param name="alias">Alias.</param> void AddColumnAlias(string tableName, string columnName, string alias); /// <summary> /// Adds the column alias. /// </summary> /// <param name="columnName">Name of the column.</param> /// <param name="alias">Alias.</param> void AddColumnAlias(string columnName, string alias); /// <summary> /// Creates a SELECT * FROM statement, so that individual column names /// don't have to be added /// </summary> void AddAll(); /// <summary> /// Adds a COUNT([columnName]) statement in the datastore specific format /// </summary> /// <param name="columnName"></param> void AddCount(string columnName); /// <summary> /// Adds a COUNT(*) statement in the datastore specific format /// </summary> void AddCountAll(); /// <summary> /// Adds a ORDER BY [columnName] statement in the datastore specific format /// </summary> /// <param name="columnName"></param> void AddOrderBy(string columnName); /// <summary> /// Adds a ORDER BY [table].[column] statement in the datastore specific format /// </summary> /// <param name="tableName"></param> /// <param name="columnName"></param> void AddOrderBy(string tableName, string columnName); /// <summary> /// Adds a ORDER BY [column1], [column2]... statement in the datastore specific format /// </summary> /// <param name="columns"></param> void AddOrderBy(params string[] columns); /// <summary> /// Adds a GROUP BY [columnName] statement in the datastore specific format /// </summary> /// <param name="columnName"></param> void AddGroupBy(string columnName); /// <summary> /// Adds a GROUP BY [column1], [column2]... statement in the datastore specific format /// </summary> /// <param name="columns"></param> void AddGroupBy(params string[] columns); /// <summary> /// Adds a SELECT ... FROM [table] [JoinType] [secondTable] ON [firstTableColumn] = [secondTableColumn] /// </summary> /// <param name="secondTable">The name of the second table to join on</param> /// <param name="firstTableColumn">The name of the first table's join column</param> /// <param name="secondTableColumn">The name of the second table's join column</param> /// <param name="type">The join type</param> void AddJoin(string secondTable, string firstTableColumn, string secondTableColumn, JoinType type); /// <summary> /// Set's the maximum number of records to retrieve /// </summary> /// <param name="maxRecords"></param> void SetLimit(int maxRecords); OrderBy OrderBy { get; set; } } public enum OrderBy { ASCENDING, DESCENDING } public enum JoinType { LEFT, RIGHT, INNER } } --- NEW FILE: AccessUpdateQuery.cs --- using System; namespace Adapdev.Data.Sql { /// <summary> /// Summary description for AccessUpdateQuery. /// </summary> public class AccessUpdateQuery : UpdateQuery { public AccessUpdateQuery():base(DbType.ACCESS, DbProviderType.OLEDB){} public AccessUpdateQuery(string table):base(DbType.ACCESS, DbProviderType.OLEDB, table){} } } --- NEW FILE: SqlSelectQuery.cs --- namespace Adapdev.Data.Sql { public class SqlSelectQuery : SelectQuery { public SqlSelectQuery() : base(DbType.SQLSERVER, DbProviderType.SQLSERVER) { } public SqlSelectQuery(string tableName) : base(DbType.SQLSERVER, DbProviderType.SQLSERVER, tableName) { } } } --- NEW FILE: OracleUpdateQuery.cs --- namespace Adapdev.Data.Sql { /// <summary> /// Summary description for UpdateQuery. /// </summary> public class OracleUpdateQuery : UpdateQuery { public OracleUpdateQuery() : base(DbType.ORACLE, DbProviderType.ORACLE) { } public OracleUpdateQuery(string tableName) : base(DbType.ORACLE, DbProviderType.ORACLE, tableName) { } } } --- NEW FILE: AccessCriteria.cs --- namespace Adapdev.Data.Sql { /// <summary> /// Summary description for AccessCriteria. /// </summary> public class AccessCriteria : Criteria { public AccessCriteria() : base(DbType.ACCESS, DbProviderType.OLEDB) { } public AccessCriteria(string sql) : base(DbType.ACCESS, DbProviderType.OLEDB, sql) { } } } --- NEW FILE: CriteriaFactory.cs --- namespace Adapdev.Data.Sql { using System; /// <summary> /// Summary description for CriteriaFactory. /// </summary> public class CriteriaFactory { public static ICriteria CreateCriteria(DbType type) { switch (type) { case DbType.ACCESS: return new AccessCriteria(); case DbType.SQLSERVER: return new SqlServerCriteria(); case DbType.ORACLE: return new OracleCriteria(); case DbType.MYSQL: return new MySqlCriteria(); default: throw new Exception("DbType " + type + " not supported currently."); } } } } --- NEW FILE: INonSelectQuery.cs --- namespace Adapdev.Data.Sql { /// <summary> /// Represents a query that does not return records /// </summary> public interface INonSelectQuery : IQuery { } } --- NEW FILE: SqlDeleteQuery.cs --- namespace Adapdev.Data.Sql { /// <summary> /// Summary description for SqlDeleteQuery. /// </summary> public class SqlDeleteQuery : DeleteQuery { public SqlDeleteQuery() : base(DbType.SQLSERVER, DbProviderType.SQLSERVER) { } public SqlDeleteQuery(string tableName) : base(DbType.SQLSERVER, DbProviderType.SQLSERVER, tableName) { } } } --- NEW FILE: IUpdateQuery.cs --- namespace Adapdev.Data.Sql { /// <summary> /// Summary description for IUpdateQuery. /// </summary> public interface IUpdateQuery : INonSelectQuery { /// <summary> /// Adds the columnName to the update query /// </summary> /// <param name="columnName"></param> /// <remarks>Since no value is passed in, the datastore specific parameter representation /// will be added</remarks> void Add(string columnName); /// <summary> /// Adds the column name and value to the update query /// </summary> /// <param name="columnName"></param> /// <param name="columnValue"></param> void Add(string columnName, object columnValue); } } --- NEW FILE: InsertQuery.cs --- namespace Adapdev.Data.Sql { using System.Text; using Adapdev.Text; /// <summary> /// Summary description for UpdateQuery. /// </summary> public abstract class InsertQuery : IInsertQuery { protected string _table = ""; protected StringBuilder sbn = new StringBuilder(); protected StringBuilder sbv = new StringBuilder(); protected string[] cnames = new string[100]; protected string[] cvalues = new string[100]; protected int cindex = 0; protected ICriteria criteria = null; protected DbType type = DbType.SQLSERVER; protected DbProviderType provider = DbProviderType.SQLSERVER; public InsertQuery(DbType type, DbProviderType provider) { this.type = type; this.provider = provider; } public InsertQuery(DbType type, DbProviderType provider, string tableName) : this(type, provider) { this.SetTable(tableName); } public void SetCriteria(ICriteria c) { criteria = c; } public void Add(string columnName) { cnames[cindex] = columnName; cvalues[cindex] = QueryHelper.GetParameterName(columnName, this.provider); cindex++; } public void Add(string columnName, object columnValue) { cnames[cindex] = columnName; cvalues[cindex] = QueryHelper.DressUp(columnValue, this.type); cindex++; } public void SetTable(string tableName) { this._table = QueryHelper.GetPreDelimeter(this.type) + tableName + QueryHelper.GetPostDelimeter(this.type); } public ICriteria CreateCriteria() { return CriteriaFactory.CreateCriteria(this.type); } public virtual string GetText() { return "INSERT INTO " + this._table + " ( " + this.GetColumnNames() + " ) VALUES ( " + this.GetColumnValues() + " ) " + this.GetCriteria(); } protected string GetColumnNames() { sbn.Remove(0, sbn.Length); for (int i = 0; i <= cindex; i++) { if (cnames[i] != null && cnames[i].Length > 0) { sbn.Append(QueryHelper.GetPreDelimeter(this.type) + cnames[i] + QueryHelper.GetPostDelimeter(this.type) + ", "); } } return StringUtil.RemoveFinalComma(this.sbn.ToString()); } protected string GetColumnValues() { sbv.Remove(0, sbv.Length); for (int i = 0; i <= cindex; i++) { if (cnames[i] != null && cnames[i].Length > 0) { sbv.Append(cvalues[i] + ", "); } } return StringUtil.RemoveFinalComma(this.sbv.ToString()); } protected string GetCriteria() { if (this.criteria == null) return ""; else return criteria.GetText(); } public DbProviderType DbProviderType { get { return this.provider; } set { this.provider = value; } } } } --- NEW FILE: SelectQuery.cs --- namespace Adapdev.Data.Sql { using System; using System.Collections; using System.Text; using Adapdev.Text; public abstract class SelectQuery : ISelectQuery { protected string _table = ""; protected StringBuilder sb = new StringBuilder(); protected Queue order = new Queue(); protected Queue group = new Queue(); protected OrderBy ob = OrderBy.ASCENDING; protected ICriteria criteria = null; protected DbType type = DbType.SQLSERVER; protected DbProviderType provider = DbProviderType.SQLSERVER; protected int maxRecords = 0; protected string _join = ""; public SelectQuery(DbType type, DbProviderType provider) { this.type = type; this.provider = provider; } public SelectQuery(DbType type, DbProviderType provider, string tableName): this(type, provider) { this.SetTable(tableName); } public void SetCriteria(ICriteria c) { criteria = c; } public void Add(string columnName) { sb.Append(" "); sb.Append(QueryHelper.GetPreDelimeter(this.type)); sb.Append(columnName); sb.Append(QueryHelper.GetPostDelimeter(this.type)); sb.Append(","); } public void Add(string tableName, string columnName) { sb.Append(" "); sb.Append(QueryHelper.GetPreDelimeter(this.type)); sb.Append(tableName); sb.Append(QueryHelper.GetPostDelimeter(this.type)); sb.Append("."); sb.Append(QueryHelper.GetPreDelimeter(this.type)); sb.Append(columnName); sb.Append(QueryHelper.GetPostDelimeter(this.type)); sb.Append(","); } public void AddColumnAlias(string columnName, string alias) { sb.Append(" "); sb.Append(QueryHelper.GetPreDelimeter(this.type)); sb.Append(columnName); sb.Append(QueryHelper.GetPostDelimeter(this.type)); sb.Append(" AS "); sb.Append(alias); sb.Append(","); } public void AddColumnAlias(string tableName, string columnName, string alias) { sb.Append(" "); sb.Append(QueryHelper.GetPreDelimeter(this.type)); sb.Append(tableName); sb.Append(QueryHelper.GetPostDelimeter(this.type)); sb.Append("."); sb.Append(QueryHelper.GetPreDelimeter(this.type)); sb.Append(columnName); sb.Append(QueryHelper.GetPostDelimeter(this.type)); sb.Append(" AS "); sb.Append(alias); sb.Append(","); } public void AddAll() { sb.Append(" * "); } public virtual void AddCount(string columnName) { sb.Append(" COUNT(" + QueryHelper.GetPreDelimeter(this.type) + columnName + QueryHelper.GetPostDelimeter(this.type) + ") "); } public virtual void AddCountAll() { sb.Append(" COUNT(*) "); } public void AddOrderBy(string columnName) { order.Enqueue(QueryHelper.GetPreDelimeter(this.type) + columnName + QueryHelper.GetPostDelimeter(this.type)); } public void AddOrderBy(string tableName, string columnName) { order.Enqueue(QueryHelper.GetPreDelimeter(this.type) + tableName + QueryHelper.GetPostDelimeter(this.type) + "." + QueryHelper.GetPreDelimeter(this.type) + columnName + QueryHelper.GetPostDelimeter(this.type)); } public void AddOrderBy(string tableName, params string[] columns) { foreach (string s in columns) { this.AddOrderBy(tableName, s); } } public void AddOrderBy(params string[] columns) { foreach (string s in columns) { this.AddOrderBy(s); } } public void AddGroupBy(string columnName) { group.Enqueue(QueryHelper.GetPreDelimeter(this.type) + columnName + QueryHelper.GetPostDelimeter(this.type)); } public void AddGroupBy(params string[] columns) { foreach (string s in columns) { this.AddGroupBy(s); } } public virtual void AddJoin(string secondTable, string firstTableColumn, string secondTableColumn, JoinType type) { this._join = String.Format(" {0} {1} ON {2}.{3} = {4}.{5} ", this.GetJoinType(type), QueryHelper.GetPreDelimeter(this.type) + secondTable + QueryHelper.GetPostDelimeter(this.type), QueryHelper.GetPreDelimeter(this.type) + this._table + QueryHelper.GetPostDelimeter(this.type), QueryHelper.GetPreDelimeter(this.type) + firstTableColumn + QueryHelper.GetPostDelimeter(this.type), QueryHelper.GetPreDelimeter(this.type) + secondTable + QueryHelper.GetPostDelimeter(this.type), QueryHelper.GetPreDelimeter(this.type) + secondTableColumn + QueryHelper.GetPostDelimeter(this.type)); } public void SetTable(string tableName) { this._table = QueryHelper.GetPreDelimeter(this.type) + tableName + QueryHelper.GetPostDelimeter(this.type); } public virtual string GetText() { return "SELECT " + this.GetLimit() + this.GetColumns() + " FROM " + this._table + this._join + this.GetCriteria() + this.GetOrderBy() + this.GetGroupBy(); } /// <summary> /// The DbProviderType for this query. Necessary to determine how to /// represent dates, parameters, etc. /// </summary> public DbProviderType DbProviderType { get { return this.provider; } set { this.provider = value; } } public OrderBy OrderBy { get { return this.ob; } set { this.ob = value; } } public void SetLimit(int maxRecords) { this.maxRecords = maxRecords; } public ICriteria CreateCriteria() { return CriteriaFactory.CreateCriteria(this.type); } protected string GetColumns() { return StringUtil.RemoveFinalComma(this.sb.ToString()); } protected virtual string GetOrderBy() { StringBuilder sbo = new StringBuilder(); if (order.Count > 0) { sbo.Append(" ORDER BY "); IEnumerator enumerator = order.GetEnumerator(); while (enumerator.MoveNext()) { sbo.Append(enumerator.Current + ", "); } string s = StringUtil.RemoveFinalComma(sbo.ToString()); s += this.TranslateOrderBy(); return s; } return ""; } protected virtual string GetGroupBy() { StringBuilder sbo = new StringBuilder(); if (group.Count > 0) { sbo.Append(" GROUP BY "); IEnumerator enumerator = group.GetEnumerator(); while (enumerator.MoveNext()) { sbo.Append(enumerator.Current + ", "); } return StringUtil.RemoveFinalComma(sbo.ToString()); } return ""; } protected virtual string GetLimit() { if (this.maxRecords > 0) { return " TOP " + this.maxRecords; } return ""; } protected string GetCriteria() { if (this.criteria == null) return ""; else return criteria.GetText(); } protected string GetJoinType(JoinType type) { switch (type) { case JoinType.INNER: return "INNER JOIN"; case JoinType.LEFT: return "LEFT OUTER JOIN"; case JoinType.RIGHT: return "RIGHT OUTER JOIN"; default: throw new Exception("JoinType " + type + " not supported."); } } protected virtual string TranslateOrderBy() { if (this.ob == OrderBy.DESCENDING) { return " DESC "; } else { return " ASC "; } } } } --- NEW FILE: QueryFactory.cs --- namespace Adapdev.Data.Sql { using System; /// <summary> /// Creates datastore specific query implementations /// </summary> public class QueryFactory { public QueryFactory() { } public static IUpdateQuery CreateUpdateQuery(string db) { return CreateUpdateQuery(DbTypeConverter.Convert(db)); } public static IUpdateQuery CreateUpdateQuery(string db, DbProviderType provider) { IUpdateQuery query = QueryFactory.CreateUpdateQuery(db); query.DbProviderType = provider; return query; } public static IUpdateQuery CreateUpdateQuery(DbType db) { switch (db) { case DbType.ACCESS: return new AccessUpdateQuery(); case DbType.SQLSERVER: return new SqlUpdateQuery(); case DbType.ORACLE: return new OracleUpdateQuery(); case DbType.MYSQL: return new MySqlUpdateQuery(); default: throw new System.NotImplementedException("DbType " + db + " not supported currently."); } } public static IUpdateQuery CreateUpdateQuery(DbType db, DbProviderType provider) { IUpdateQuery query = QueryFactory.CreateUpdateQuery(db); query.DbProviderType = provider; return query; } public static ISelectQuery CreateSelectQuery(string db) { return CreateSelectQuery(DbTypeConverter.Convert(db)); } public static ISelectQuery CreateSelectQuery(DbType db) { switch (db) { case DbType.ACCESS: return new AccessSelectQuery(); case DbType.SQLSERVER: return new SqlSelectQuery(); case DbType.ORACLE: return new OracleSelectQuery(); case DbType.MYSQL: return new MySqlSelectQuery(); default: throw new System.NotImplementedException("DbType " + db + " not supported currently."); } } public static ISelectQuery CreateSelectQuery(DbType db, DbProviderType provider) { ISelectQuery query = QueryFactory.CreateSelectQuery(db); query.DbProviderType = provider; return query; } public static IDeleteQuery CreateDeleteQuery(string db) { return CreateDeleteQuery(DbTypeConverter.Convert(db)); } public static IDeleteQuery CreateDeleteQuery(string db, DbProviderType provider) { IDeleteQuery query = QueryFactory.CreateDeleteQuery(db); query.DbProviderType = provider; return query; } public static IDeleteQuery CreateDeleteQuery(DbType db) { switch (db) { case DbType.ACCESS: return new AccessDeleteQuery(); case DbType.SQLSERVER: return new SqlDeleteQuery(); case DbType.ORACLE: return new OracleDeleteQuery(); case DbType.MYSQL: return new MySqlDeleteQuery(); default: throw new System.NotImplementedException("DbType " + db + " not supported currently."); } } public static IDeleteQuery CreateDeleteQuery(DbType db, DbProviderType provider) { IDeleteQuery query = QueryFactory.CreateDeleteQuery(db); query.DbProviderType = provider; return query; } public static IInsertQuery CreateInsertQuery(string db) { return CreateInsertQuery(DbTypeConverter.Convert(db)); } public static IInsertQuery CreateInsertQuery(string db, DbProviderType provider) { IInsertQuery query = QueryFactory.CreateInsertQuery(db); query.DbProviderType = provider; return query; } public static IInsertQuery CreateInsertQuery(DbType db) { switch (db) { case DbType.ACCESS: return new AccessInsertQuery(); case DbType.SQLSERVER: return new SqlInsertQuery(); case DbType.ORACLE: return new OracleInsertQuery(); case DbType.MYSQL: return new MySqlInsertQuery(); default: throw new System.NotImplementedException("DbType " + db + " not supported currently."); } } public static IInsertQuery CreateInsertQuery(DbType db, DbProviderType provider) { IInsertQuery query = QueryFactory.CreateInsertQuery(db); query.DbProviderType = provider; return query; } } } --- NEW FILE: MySqlCriteria.cs --- namespace Adapdev.Data.Sql { using System.Collections; using System.Text; using Adapdev.Text; /// <summary> /// Summary description for MySqlCriteria. /// </summary> public class MySqlCriteria : Criteria { public MySqlCriteria() : base(DbType.MYSQL, DbProviderType.MYSQL) { } public MySqlCriteria(string sql) : base(DbType.MYSQL, DbProviderType.MYSQL, sql) { } } } --- NEW FILE: MySqlInsertQuery.cs --- using System; namespace Adapdev.Data.Sql { /// <summary> /// Summary description for MySqlInsertQuery. /// </summary> public class MySqlInsertQuery : InsertQuery { public MySqlInsertQuery():base(DbType.MYSQL, DbProviderType.MYSQL){} public MySqlInsertQuery(string table):base(DbType.MYSQL, DbProviderType.MYSQL, table){} } } --- NEW FILE: AccessInsertQuery.cs --- using System; namespace Adapdev.Data.Sql { /// <summary> /// Summary description for AccessInsertQuery. /// </summary> public class AccessInsertQuery : InsertQuery { public AccessInsertQuery():base(DbType.ACCESS, DbProviderType.OLEDB){} public AccessInsertQuery(string table):base(DbType.ACCESS, DbProviderType.OLEDB, table){} } } --- NEW FILE: Criteria.cs --- namespace Adapdev.Data.Sql { using System.Collections; using System.Text; using Adapdev.Text; /// <summary> /// Summary description for Criteria. /// </summary> public abstract class Criteria : ICriteria { protected StringBuilder sb = new StringBuilder(); protected DbType type = DbType.SQLSERVER; protected DbProviderType provider = DbProviderType.SQLSERVER; public Criteria(DbType type, DbProviderType provider) { this.type = type; this.provider = provider; } public Criteria(DbType type, DbProviderType provider, string sql): this(type, provider) { sql = sql.Replace("WHERE", ""); this.AddSql(sql); } public void AddAnd() { this.AddCriteriaSeparator(CriteriaType.AND); } public virtual void AddAndCriteria(ICriteria c) { this.AddAnd(); sb.Append("("); sb.Append(c.GetText()); sb.Append(") "); } public virtual void AddCriteriaSeparator(CriteriaType ct) { if (ct == CriteriaType.AND) sb.Append(" AND "); else sb.Append(" OR "); } public virtual void AddBetween(string columnName, object value1, object value2) { sb.Append(" "); sb.Append(QueryHelper.GetPreDelimeter(this.type)); sb.Append(columnName); sb.Append(QueryHelper.GetPostDelimeter(this.type)); sb.Append(" BETWEEN "); sb.Append(QueryHelper.DressUp(value1,this.type)); sb.Append(" AND "); sb.Append(QueryHelper.DressUp(value2,this.type)); sb.Append(" "); } public virtual void AddEqualTo(string columnName, object columnValue) { sb.Append(" "); sb.Append(QueryHelper.GetPreDelimeter(this.type)); sb.Append(columnName); sb.Append(QueryHelper.GetPostDelimeter(this.type)); sb.Append(" = "); sb.Append(QueryHelper.DressUp(columnValue,this.type)); sb.Append(" "); } public virtual void AddEqualTo(string tableName, string columnName, object columnValue) { sb.Append(" "); sb.Append(QueryHelper.GetPreDelimeter(this.type)); sb.Append(tableName); sb.Append(QueryHelper.GetPostDelimeter(this.type)); sb.Append("."); sb.Append(QueryHelper.GetPreDelimeter(this.type)); sb.Append(columnName); sb.Append(QueryHelper.GetPostDelimeter(this.type)); sb.Append(" = "); sb.Append(QueryHelper.DressUp(columnValue,this.type)); sb.Append(" "); } public void AddEqualTo(string columnName) { sb.Append(" "); sb.Append(QueryHelper.GetPreDelimeter(this.type)); sb.Append(columnName); sb.Append(QueryHelper.GetPostDelimeter(this.type)); sb.Append(" = "); sb.Append(QueryHelper.GetParameterName(columnName, this.DbProviderType)); sb.Append(" "); } public virtual void AddExists(IQuery subQuery) { } public virtual void AddGreaterThanOrEqualTo(string columnName, object columnValue) { sb.Append(" "); sb.Append(QueryHelper.GetPreDelimeter(this.type)); sb.Append(columnName); sb.Append(QueryHelper.GetPostDelimeter(this.type)); sb.Append(" >= "); sb.Append(QueryHelper.DressUp(columnValue,this.type)); sb.Append(" "); } public virtual void AddGreaterThan(string columnName, object columnValue) { sb.Append(" "); sb.Append(QueryHelper.GetPreDelimeter(this.type)); sb.Append(columnName); sb.Append(QueryHelper.GetPostDelimeter(this.type)); sb.Append(" > "); sb.Append(QueryHelper.DressUp(columnValue,this.type)); sb.Append(" "); } public virtual void AddIn(string columnName, IQuery subQuery) { sb.Append(" IN ("); sb.Append(subQuery.GetText()); sb.Append(") "); } public virtual void AddIn(string columnName, ICollection values) { StringBuilder sbo = new StringBuilder(); sb.Append(columnName); sb.Append(" IN ("); IEnumerator enumerator = values.GetEnumerator(); while (enumerator.MoveNext()) { sbo.Append(QueryHelper.DressUp(enumerator.Current, this.type) + ", "); } sb.Append(StringUtil.RemoveFinalComma(sbo.ToString())); sb.Append(") "); } public virtual void AddIsNull(string columnName) { sb.Append(" "); sb.Append(QueryHelper.GetPreDelimeter(this.type)); sb.Append(columnName); sb.Append(QueryHelper.GetPostDelimeter(this.type)); sb.Append(" IS NULL "); } public virtual void AddLessThanOrEqualTo(string columnName, object columnValue) { sb.Append(" "); sb.Append(QueryHelper.GetPreDelimeter(this.type)); sb.Append(columnName); sb.Append(QueryHelper.GetPostDelimeter(this.type)); sb.Append(" <= "); sb.Append(QueryHelper.DressUp(columnValue,this.type)); sb.Append(" "); } public virtual void AddLessThan(string columnName, object columnValue) { sb.Append(" "); sb.Append(QueryHelper.GetPreDelimeter(this.type)); sb.Append(columnName); sb.Append(QueryHelper.GetPostDelimeter(this.type)); sb.Append(" < "); sb.Append(QueryHelper.DressUp(columnValue,this.type)); sb.Append(" "); } public virtual void AddLike(string columnName, object columnValue) { sb.Append(" "); sb.Append(QueryHelper.GetPreDelimeter(this.type)); sb.Append(columnName); sb.Append(QueryHelper.GetPostDelimeter(this.type)); sb.Append(" LIKE "); sb.Append(QueryHelper.DressUp(columnValue,this.type)); sb.Append(" "); } public virtual void AddNotBetween(string columnName, object value1, object value2) { sb.Append(" "); sb.Append(QueryHelper.GetPreDelimeter(this.type)); sb.Append(columnName); sb.Append(QueryHelper.GetPostDelimeter(this.type)); sb.Append(" NOT BETWEEN "); sb.Append(QueryHelper.DressUp(value1, this.type)); sb.Append(" AND "); sb.Append(QueryHelper.DressUp(value2, this.type)); sb.Append(" "); } public virtual void AddNotEqualTo(string columnName, object columnValue) { sb.Append(" "); sb.Append(QueryHelper.GetPreDelimeter(this.type)); sb.Append(columnName); sb.Append(QueryHelper.GetPostDelimeter(this.type)); sb.Append(" <> "); sb.Append(QueryHelper.DressUp(columnValue,this.type)); sb.Append(" "); } public virtual void AddNotExists(IQuery subQuery) { sb.Append(" EXISTS (" + subQuery.GetText() + ") "); } public virtual void AddNotIn(string columnName, ICollection values) { StringBuilder sbo = new StringBuilder(); sb.Append(" NOT IN ("); IEnumerator enumerator = values.GetEnumerator(); while (enumerator.MoveNext()) { sbo.Append(QueryHelper.DressUp(enumerator.Current, this.type) + ", "); } sb.Append(StringUtil.RemoveFinalComma(sbo.ToString())); sb.Append(")"); } public virtual void AddNotIn(string columnName, IQuery subQuery) { sb.Append(" NOT IN (" + subQuery.GetText() + ") "); } public virtual void AddNotLike(string columnName, object columnValue) { sb.Append(" "); sb.Append(QueryHelper.GetPreDelimeter(this.type)); sb.Append(columnName); sb.Append(QueryHelper.GetPostDelimeter(this.type)); sb.Append(" NOT LIKE "); sb.Append(QueryHelper.DressUp(columnValue,this.type)); sb.Append(" "); } public virtual void AddNotNull(string columnName) { sb.Append(" "); sb.Append(QueryHelper.GetPreDelimeter(this.type)); sb.Append(columnName); sb.Append(QueryHelper.GetPostDelimeter(this.type)); sb.Append(" NOT IS NULL "); } public void AddOr() { this.AddCriteriaSeparator(CriteriaType.OR); } public void AddOrCriteria(ICriteria c) { this.AddOr(); sb.Append("(" + c.GetText() + ")"); } public virtual void AddSql(string sql) { sb.Append(sql); } public virtual string GetText() { if (sb.Length > 2) { return " WHERE " + sb.ToString(); } else { return ""; } } public DbProviderType DbProviderType { get { return this.provider; } set { this.provider = value; } } } public enum CriteriaType { AND, OR } } --- NEW FILE: IQuery.cs --- namespace Adapdev.Data.Sql { using System; /// <summary> /// Represents a query /// </summary> public interface IQuery { /// <summary> /// Sets the criteria to use for the query /// </summary> /// <param name="c"></param> void SetCriteria(ICriteria c); /// <summary> /// Specifies the table to use for the query /// </summary> /// <param name="tableName"></param> void SetTable(string tableName); /// <summary> /// Returns a datastore specific ICriteria implementation /// </summary> /// <returns></returns> ICriteria CreateCriteria(); /// <summary> /// Returns the text form of the query /// </summary> /// <returns></returns> string GetText(); /// <summary> /// The DbProviderType for this query. Necessary to determine how to /// represent dates, parameters, etc. /// </summary> DbProviderType DbProviderType { get; set; } } } --- NEW FILE: AccessSelectQuery.cs --- using System; namespace Adapdev.Data.Sql { /// <summary> /// Summary description for AccessSelectQuery. /// </summary> public class AccessSelectQuery : SelectQuery { public AccessSelectQuery():base(DbType.ACCESS, DbProviderType.OLEDB){} public AccessSelectQuery(string table):base(DbType.ACCESS, DbProviderType.OLEDB, table){} } } --- NEW FILE: QueryConstants.cs --- namespace Adapdev.Data.Sql { /// <summary> /// Summary description for Constants. /// </summary> public class Constants { private Constants() { } public const char SQLSERVER_STRING = '\''; public const char SQLSERVER_DATE = '\''; public const char ACCESS_STRING = '\''; public const char ACCESS_DATE = '#'; public const char ORACLE_STRING = '\''; public const char ORACLE_DATE = '\''; public const char MYSQL_STRING = '\''; public const char MYSQL_DATE = '\''; } } --- NEW FILE: AccessDeleteQuery.cs --- using System; namespace Adapdev.Data.Sql { /// <summary> /// Summary description for AccessDeleteQuery. /// </summary> public class AccessDeleteQuery : DeleteQuery { public AccessDeleteQuery():base(DbType.ACCESS, DbProviderType.OLEDB){} public AccessDeleteQuery(string table):base(DbType.ACCESS, DbProviderType.OLEDB, table){} } } --- NEW FILE: UpdateQuery.cs --- namespace Adapdev.Data.Sql { using System.Text; using Adapdev.Text; /// <summary> /// Summary description for UpdateQuery. /// </summary> public abstract class UpdateQuery : IUpdateQuery { protected string _table = ""; protected StringBuilder sb = new StringBuilder(); protected ICriteria criteria = null; protected DbType type = DbType.SQLSERVER; protected DbProviderType provider = DbProviderType.SQLSERVER; public UpdateQuery(DbType type, DbProviderType provider) { this.type = type; this.provider = provider; } public UpdateQuery(DbType type, DbProviderType provider, string tableName) : this(type, provider) { this.SetTable(tableName); } public void SetCriteria(ICriteria c) { criteria = c; } public void Add(string columnName) { sb.Append(" " + QueryHelper.GetPreDelimeter(this.type) + columnName + QueryHelper.GetPostDelimeter(this.type) + " = " + QueryHelper.GetParameterName(columnName, this.provider) + ","); } public void Add(string columnName, object columnValue) { sb.Append(" " + QueryHelper.GetPreDelimeter(this.type) + columnName + QueryHelper.GetPostDelimeter(this.type) + " = " + QueryHelper.DressUp(columnValue, this.type) + ","); } public void SetTable(string tableName) { this._table = QueryHelper.GetPreDelimeter(this.type) + tableName + QueryHelper.GetPostDelimeter(this.type); } public ICriteria CreateCriteria() { return CriteriaFactory.CreateCriteria(this.type); } public virtual string GetText() { return "UPDATE " + this._table + " SET " + this.GetColumns() + this.GetCriteria(); } protected string GetColumns() { return StringUtil.RemoveFinalComma(this.sb.ToString()); } protected string GetCriteria() { if (this.criteria == null) return ""; else return criteria.GetText(); } public DbProviderType DbProviderType { get { return this.provider; } set { this.provider = value; } } } } --- NEW FILE: MySqlUpdateQuery.cs --- using System; namespace Adapdev.Data.Sql { /// <summary> /// Summary description for MySqlUpdateQuery. /// </summary> public class MySqlUpdateQuery : UpdateQuery { public MySqlUpdateQuery():base(DbType.MYSQL, DbProviderType.MYSQL){} public MySqlUpdateQuery(string table):base(DbType.MYSQL, DbProviderType.MYSQL, table){} } } --- NEW FILE: SqlServerCriteria.cs --- namespace Adapdev.Data.Sql { using System.Collections; using System.Text; using Adapdev.Text; /// <summary> /// Summary description for ICriteria. /// </summary> public class SqlServerCriteria : Criteria { public SqlServerCriteria() : base(DbType.SQLSERVER, DbProviderType.SQLSERVER) { } public SqlServerCriteria(string sql) : base(DbType.SQLSERVER, DbProviderType.SQLSERVER, sql) { } } } --- NEW FILE: IInsertQuery.cs --- namespace Adapdev.Data.Sql { /// <summary> /// Summary description for IInsertQuery. /// </summary> public interface IInsertQuery : INonSelectQuery { /// <summary> /// Adds the columnName to the insert query /// </summary> /// <param name="columnName"></param> /// <remarks>Since no value is passed in, the datastore specific parameter representation /// will be added</remarks> void Add(string columnName); /// <summary> /// Adds the column name and value to the insert query /// </summary> /// <param name="columnName"></param> /// <param name="columnValue"></param> void Add(string columnName, object columnValue); } } --- NEW FILE: IDeleteQuery.cs --- namespace Adapdev.Data.Sql { /// <summary> /// Summary description for IDeleteQuery. /// </summary> public interface IDeleteQuery : INonSelectQuery { } } --- NEW FILE: MySqlDeleteQuery.cs --- using System; namespace Adapdev.Data.Sql { /// <summary> /// Summary description for MySqlDeleteQuery. /// </summary> public class MySqlDeleteQuery : DeleteQuery { public MySqlDeleteQuery():base(DbType.MYSQL, DbProviderType.MYSQL){} public MySqlDeleteQuery(string table):base(DbType.MYSQL, DbProviderType.MYSQL, table){} } } --- NEW FILE: DialectConstants.cs --- namespace Adapdev.Data.Sql { /// <summary> /// Summary description for DialectConstants. /// </summary> public class DialectConstants { public const char ACCESS_PREDELIM = '['; public const char ACCESS_POSTDELIM = ']'; public const char ACCESS_DATE = '#'; public const char ACCESS_STRING = '\''; public const char SQLSERVER_PREDELIM = '['; public const char SQLSERVER_POSTDELIM = ']'; public const char SQLSERVER_DATE = '\''; public const char SQLSERVER_STRING = '\''; public const char ORACLE_PREDELIM = ' '; public const char ORACLE_POSTDELIM = ' '; public const char ORACLE_DATE = '\''; public const char ORACLE_STRING = '\''; public const char MYSQL_PREDELIM = '`'; public const char MYSQL_POSTDELIM = '`'; public const char MYSQL_DATE = '\''; public const char MYSQL_STRING = '\''; } } --- NEW FILE: OracleInsertQuery.cs --- namespace Adapdev.Data.Sql { /// <summary> /// Summary description for SqlInsertQuery. /// </summary> public class OracleInsertQuery : InsertQuery { public OracleInsertQuery() : base(DbType.ORACLE, DbProviderType.ORACLE) { } public OracleInsertQuery(string tableName) : base(DbType.ORACLE, DbProviderType.ORACLE, tableName) { } } } --- NEW FILE: OracleSelectQuery.cs --- namespace Adapdev.Data.Sql { public class OracleSelectQuery : SelectQuery { public OracleSelectQuery() : base(DbType.ORACLE, DbProviderType.ORACLE) { } public OracleSelectQuery(string tableName) : base(DbType.ORACLE, DbProviderType.ORACLE, tableName) { } protected override string GetLimit() { if(this.maxRecords > 0) { return " ROWNUM <= " + this.maxRecords; } return ""; } public override string GetText() { string sql = "SELECT " + this.GetColumns() + " FROM " + this._table + this._join + this.GetCriteria(); if(this.maxRecords > 0) { if(sql.ToLower().IndexOf("where") < 1) sql+= " WHERE "; else sql += " AND "; sql += this.GetLimit(); } sql += this.GetOrderBy() + this.GetGroupBy(); return sql; } } } |
Update of /cvsroot/adapdev/Adapdev/src/Adapdev In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv19977/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: Reposting to the repository after it got hosed --- 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\IV... [truncated message content] |
From: Sean M. <int...@us...> - 2005-11-16 05:33:36
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.Data.Tests In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv19977/src/Adapdev.Data.Tests Added Files: Adapdev.Data.Tests.csproj CategoriesDAOTest.cs ProviderInfoManagerTest.cs SchemaBuilderTest.cs Log Message: Reposting to the repository after it got hosed --- NEW FILE: Adapdev.Data.Tests.csproj --- <VisualStudioProject> <CSHARP ProjectType = "Local" ProductVersion = "7.10.3077" SchemaVersion = "2.0" ProjectGuid = "{07695A4B-39A8-41CB-A21B-E61B3990C20F}" > <Build> <Settings ApplicationIcon = "" AssemblyKeyContainerName = "" AssemblyName = "Adapdev.Data.Tests" AssemblyOriginatorKeyFile = "" DefaultClientScript = "JScript" DefaultHTMLPageLayout = "Grid" DefaultTargetSchema = "IE50" DelaySign = "false" OutputType = "Library" PreBuildEvent = "" PostBuildEvent = "" RootNamespace = "Adapdev.Data.Tests" 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.Data" Project = "{08C5794D-44ED-4E75-A1C1-48A28C3D0044}" Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" /> <Reference Name = "Adapdev" Project = "{CC30A321-2569-4B1F-8E1A-781B5509B56D}" Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" /> <Reference Name = "log4net" AssemblyName = "log4net" HintPath = "..\..\lib\log4net.dll" /> <Reference Name = "nunit.framework" AssemblyName = "nunit.framework" HintPath = "..\..\lib\nunit.framework.dll" /> </References> </Build> <Files> <Include> <File RelPath = "AdapdevAssemblyInfo.cs" Link = "..\AdapdevAssemblyInfo.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "CategoriesDAOTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "ProviderInfoManagerTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "SchemaBuilderTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "CategoriesExample\CategoriesDAO.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "CategoriesExample\CategoriesDAOBase.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "CategoriesExample\CategoriesEntity.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "CategoriesExample\CategoriesEntityBase.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "CategoriesExample\CategoriesEntityCollection.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "CategoriesExample\CategoriesEntityDictionary.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "CategoriesExample\CategoriesEntityEnumerator.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "CategoriesExample\DbConstants.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "CategoriesExample\MockCategories.cs" SubType = "Code" BuildAction = "Compile" /> </Include> </Files> </CSHARP> </VisualStudioProject> --- NEW FILE: SchemaBuilderTest.cs --- using System; using NUnit.Framework; namespace Adapdev.Data.Tests { using Adapdev.Data; using Adapdev.Data.Schema; /// <summary> /// Summary description for SchemaBuilderTest. /// </summary> /// [TestFixture] public class SchemaBuilderTest { private string _oledbConnectionString = "Provider=sqloledb;Data Source=localhost;Initial Catalog=northwind;User Id=sa;Password=;"; private string _sqlserverConnectionString = "Data Source=localhost; Initial Catalog=northwind; User ID=sa; Password=; Trusted_Connection=false;"; private string _mysqlConnectionString = "Data Source=localhost;Database=codus_test;User ID=;Password=;"; [Test] public void BuildSqlServerOleDbSchema() { DatabaseSchema ds = SchemaBuilder.CreateDatabaseSchema(this._oledbConnectionString, Adapdev.Data.DbType.SQLSERVER, Adapdev.Data.DbProviderType.OLEDB); Assert.AreEqual(29, ds.Tables.Count, "Northwind should have 29 tables / views."); Assert.IsTrue(ds.Tables.Contains("Orders")); Assert.AreEqual(Adapdev.Data.DbProviderType.OLEDB, ds.DatabaseProviderType, "ProviderTypes don't match."); Assert.AreEqual(Adapdev.Data.DbType.SQLSERVER, ds.DatabaseType, "DataTypes don't match."); foreach(ColumnSchema column in ds.GetTable("Orders").Columns.Values) { Console.WriteLine("{0} : {1}", column.Name, column.DataType); } } [Test] public void BuildSqlServerSqlSchema() { DatabaseSchema ds = SchemaBuilder.CreateDatabaseSchema(this._oledbConnectionString, Adapdev.Data.DbType.SQLSERVER, Adapdev.Data.DbProviderType.SQLSERVER); Assert.AreEqual(29, ds.Tables.Count, "Northwind should have 29 tables / views."); Assert.IsTrue(ds.Tables.Contains("Orders")); Assert.AreEqual(Adapdev.Data.DbProviderType.SQLSERVER, ds.DatabaseProviderType, "ProviderTypes don't match."); Assert.AreEqual(Adapdev.Data.DbType.SQLSERVER, ds.DatabaseType, "DataTypes don't match."); foreach(ColumnSchema column in ds.GetTable("Orders").Columns.Values) { Console.WriteLine("{0} : {1}", column.Name, column.DataType); } } [Test] public void BuildMySqlSchema() { DatabaseSchema ds = SchemaBuilder.CreateDatabaseSchema(this._mysqlConnectionString, Adapdev.Data.DbType.MYSQL, Adapdev.Data.DbProviderType.MYSQL); Assert.AreEqual(4, ds.Tables.Count, "codus_test should have 4 tables"); Assert.IsTrue(ds.Tables.Contains("alldatatypes")); Assert.AreEqual(Adapdev.Data.DbProviderType.MYSQL, ds.DatabaseProviderType, "ProviderTypes don't match."); Assert.AreEqual(Adapdev.Data.DbType.MYSQL, ds.DatabaseType, "DataTypes don't match."); } [Test,Ignore("")] public void PrintMySqlSchema() { int i = 0; Console.WriteLine(new MySqlSchemaBuilder(null, ref i).PrintReaderSchema(this._mysqlConnectionString, "alldatatypes")); } [Test] public void ProviderConfig() { ProviderConfig pc = new ProviderConfig(); Assert.AreEqual(5 ,pc.ConnectionTypes.Count, "Should have 5 Connection Types in the ProviderConfig collection"); Assert.IsTrue(pc.ConnectionTypes.Contains("Microsoft Access"),"Could not find Microsoft Access"); Assert.IsTrue(pc.ConnectionTypes.Contains("SQL Server"),"Could not find SQL Server"); Assert.IsTrue(pc.ConnectionTypes.Contains("SQL Server - Trusted"), "Could not find SQL Server - Trusted"); Assert.IsTrue(pc.ConnectionTypes.Contains("Oracle"), "Could not find Oracle"); Assert.IsTrue(pc.ConnectionTypes.Contains("Oracle - Trusted"), "Could not find Oracle -Trusted"); } [Test] public void ConnectionTypes() { DbConnectionTypes ct = new DbConnectionTypes(); Assert.AreEqual(0, ct.Count, "Should be zero items"); ct.Add("test", new DbConnectionType()); Assert.AreEqual(1, ct.Count, "Should be one item"); Assert.IsTrue(ct.Contains("test"),"Should contain test"); ct.Remove("test"); Assert.AreEqual(0, ct.Count, "Should be zero items after deleting the item"); ct.Add(new DbConnectionType("zarniwoop",DbType.SQLSERVER, "OLEDB",true, true, true, true, false)); ct.Add(new DbConnectionType("beeblebrox",DbType.SQLSERVER, "OLEDB",true, true, true, true, false)); ct.Add(new DbConnectionType("magrathea",DbType.SQLSERVER, "OLEDB",true, true, true, true, false)); ct.Add(new DbConnectionType("marvin",DbType.SQLSERVER, "OLEDB",true, true, true, true, false)); ct.Add(new DbConnectionType("vogon",DbType.SQLSERVER, "OLEDB",true, true, true, true, false)); Assert.AreEqual("beeblebrox", ct.GetByIndex(0).Name); Assert.AreEqual("magrathea", ct.GetByIndex(1).Name); Assert.AreEqual("marvin", ct.GetByIndex(2).Name); Assert.AreEqual("vogon", ct.GetByIndex(3).Name); Assert.AreEqual("zarniwoop", ct.GetByIndex(4).Name); ct.Clear(); Assert.AreEqual(0, ct.Count, "Should be zero items after clearing the collection"); } [Test] public void ConnectionType() { DbConnectionType ct = new DbConnectionType(); Assert.IsNotNull(ct); ct = new DbConnectionType("TestType",DbType.SQLSERVER, "OLEDB", true, true, true, true, false); Assert.IsFalse(ct.SupportsFile); Assert.IsTrue(ct.SupportsServer); ct.SupportsServer = false; Assert.IsTrue(ct.SupportsFile); Assert.IsFalse(ct.SupportsServer); ct.DbType = DbType.ACCESS; Assert.AreEqual("ACCESS", ct.DbTypeName); } [Test] [ExpectedException(typeof(ApplicationException))] public void ConnectionTypeInternalFails() { DbConnectionType ct = new DbConnectionType("TestType",DbType.SQLSERVER, "OLEDB", true, true, true, true, false); Assert.AreEqual("OLEDB", ct.InternalProviderName); Assert.IsNull(ct.InternalProvider); } [Test] public void ConnectionProviders() { DbConnectionProviders cp = new DbConnectionProviders(); Assert.AreEqual(0, cp.Count, "Should be zero items"); cp.Add("test", new DbConnectionProvider()); Assert.AreEqual(1, cp.Count, "Should be one item"); Assert.IsTrue(cp.Contains("test"),"Should contain test"); cp.Remove("test"); Assert.AreEqual(0, cp.Count, "Should be zero items after deleting the item"); DbConnectionType ct = new DbConnectionType("TestType",DbType.SQLSERVER,"OLEDB", true, true, true, true, false); ct.Providers = cp; cp.Add(new DbConnectionProvider("zarniwoop","SQLSERVER", "provider=mssqlserver", ct)); cp.Add(new DbConnectionProvider("beeblebrox","SQLSERVER", "provider=mssqlserver", ct)); cp.Add(new DbConnectionProvider("magrathea","SQLSERVER", "provider=mssqlserver", ct)); cp.Add(new DbConnectionProvider("marvin","SQLSERVER", "provider=mssqlserver", ct)); cp.Add(new DbConnectionProvider("vogon","SQLSERVER", "provider=mssqlserver", ct)); Assert.AreEqual("beeblebrox", cp.GetByIndex(0).Name, "Items out of order"); Assert.AreEqual("magrathea", cp.GetByIndex(1).Name, "Items out of order"); Assert.AreEqual("marvin", cp.GetByIndex(2).Name, "Items out of order"); Assert.AreEqual("vogon", cp.GetByIndex(3).Name, "Items out of order"); Assert.AreEqual("zarniwoop", cp.GetByIndex(4).Name, "Items out of order"); cp.Clear(); Assert.AreEqual(0, cp.Count, "Should be zero items after clearing the collection"); } [Test] public void ConnectionProvider() { DbConnectionType ct = new DbConnectionType("TestType",DbType.SQLSERVER,"OLEDB", true, true, true, true, false); DbConnectionProvider cp = new DbConnectionProvider(); Assert.IsNotNull(cp); cp = new DbConnectionProvider("TestProvider1", "SQLSERVER", "provider=mssqlserver", ct); ct.Providers.Add(cp); cp = new DbConnectionProvider("TestProvider2", "OLEDB", "provider=mssqlserver", ct); ct.Providers.Add(cp); Assert.AreEqual(2, ct.Providers.Count, "Should be two providers."); cp.DbType = DbType.ACCESS; Assert.AreEqual("ACCESS", cp.DbTypeName); cp.ProviderType = DbProviderType.OLEDB; Assert.AreEqual("OLEDB", cp.ProviderTypeName); ct.InternalProviderName = "TestProvider2"; Assert.AreEqual("TestProvider2", ct.InternalProvider.Name, "Internal Provider should be 'TestProvider2'"); Assert.IsNotNull(cp.Parent,"Parent should not be Null. Should be 'TestType'"); Assert.IsNotNull(cp.Parent.InternalProvider,"Internal provider should be defined"); Assert.AreEqual(cp.Parent.InternalProvider.ConnectionString("TestServer"), cp.ConnectionString("TestServer")); cp = new DbConnectionProvider("TestProvider","OLEDB", "{0},{1},{2},{3}", ct); Assert.AreEqual("A,B,C,D", cp.ConnectionString("A","B","C","D")); } } } --- NEW FILE: CategoriesDAOTest.cs --- /****************************************** * Auto-generated by Codus * 9/30/2005 5:18:20 PM ******************************************/ using System; using System.Collections; using System.Data; using Test; using Test.Mock; using Adapdev.Serialization; using Adapdev.Transactions; using NUnit.Framework; namespace Test.Tests.NUnit { /// <summary> /// Summary description for ShippersDAOTest. /// </summary> /// [TestFixture] public class CategoriesDAOTest { CategoriesDAO dao = null; int total = 0; bool inserted = false; [TestFixtureSetUp] public void TestFixtureSetup() { dao = new CategoriesDAO(); total = dao.GetCount(); } [Test] public void Insert() { this.inserted = false; int count = dao.GetCount(); MockCategoriesEntity e = new MockCategoriesEntity(); dao.Save(e); Console.WriteLine("Inserted record: " + Environment.NewLine + e.ToString()); int count2 = dao.GetCount(); Assert.IsTrue(count == (count2 - 1), "Record was not inserted."); Assert.AreNotEqual(2, e.CategoryID, "CategoryId is an autoincrement and should be db assigned."); this.inserted = true; } [Test] public void InsertDistributedTransaction() { using(TransactionScope transaction = new TransactionScope()) { this.inserted = false; int count = dao.GetCount(); MockCategoriesEntity e = new MockCategoriesEntity(); dao.Save(e); Console.WriteLine("Inserted record: " + Environment.NewLine + e.ToString()); int count2 = dao.GetCount(); Assert.IsTrue(count == (count2 - 1), "Record was not inserted."); Assert.AreNotEqual(2, e.CategoryID, "CategoryId is an autoincrement and should be db assigned."); transaction.Abort(); } } [Test] public void InsertLocalTransaction() { int start = dao.GetCount(); using(IDbConnection c= dao.CreateConnection()) { c.Open(); Assert.IsTrue(c.State == ConnectionState.Open, "Connection is not open."); IDbTransaction t= c.BeginTransaction(); MockCategoriesEntity e = new MockCategoriesEntity(); dao.Save(e, c, t); Console.WriteLine("Inserted record: " + Environment.NewLine + e.ToString()); Assert.AreNotEqual(2, e.CategoryID, "CategoryId is an autoincrement and should be db assigned."); t.Rollback(); } int end = dao.GetCount(); Assert.AreEqual(start, end, "No record should have been inserted."); } [Test] public void SelectAll() { ICollection c = dao.SelectAll(); if(total > 0){ Assert.IsTrue(c.Count > 0, "No records returned."); //foreach(CategoriesEntity e in c) //{ // Console.WriteLine(e.ToString()); //} } } [Test] [Ignore("")] public void TestToString(){ ArrayList al = new ArrayList(dao.SelectAllWithLimit(1)); CategoriesEntity s = (CategoriesEntity)al[0]; Console.WriteLine(s.ToString()); } [Test] [Ignore("")] public void TestSerialize(){ ArrayList al = new ArrayList(dao.SelectAllWithLimit(1)); CategoriesEntity s = (CategoriesEntity)al[0]; Console.WriteLine(Serializer.SerializeToXml(s)); } [Test,Ignore("Only use this on a development database.")] public void Update() { if(this.inserted){ ArrayList al = new ArrayList(dao.SelectAllWithLimit(1, Adapdev.Data.Sql.OrderBy.DESCENDING, new string[]{CategoriesDAO.TABLE_PRIMARYKEY})); CategoriesEntity s = (CategoriesEntity)al[0]; Console.WriteLine("Record to be updated: "); Console.WriteLine(s.ToString()); s.CategoryName = "test"; s.Description = "test"; s.Picture = System.Text.Encoding.ASCII.GetBytes("Test String2"); dao.Update(s); Console.WriteLine("Updated record:"); Console.WriteLine(s.ToString()); CategoriesEntity s2 = (CategoriesEntity)dao.SelectById(s.CategoryID); Assert.AreEqual( s.CategoryID.ToString().Trim() , s2.CategoryID.ToString().Trim(), "Objects should be equal." ); Assert.AreEqual( s.CategoryName.ToString().Trim() , s2.CategoryName.ToString().Trim(), "Objects should be equal." ); Assert.AreEqual( s.Description.ToString().Trim() , s2.Description.ToString().Trim(), "Objects should be equal." ); Assert.AreEqual( s.Picture.ToString().Trim() , s2.Picture.ToString().Trim(), "Objects should be equal." ); }else{ throw new Exception("No test record inserted, so unable to perform update."); } } [TestFixtureTearDown] public void Delete() { if(inserted){ ArrayList al = new ArrayList(dao.SelectAllWithLimit(1, Adapdev.Data.Sql.OrderBy.DESCENDING, new string[]{CategoriesDAO.TABLE_PRIMARYKEY})); int count1 = dao.GetCount(); CategoriesEntity s = (CategoriesEntity)al[0]; Console.WriteLine("Deleted Record:"); Console.WriteLine(s.ToString()); dao.Delete(s.CategoryID); int count2 = dao.GetCount(); Assert.IsTrue(count2 == (count1 - 1), "Unable to delete record."); this.inserted = false; } } } } --- NEW FILE: ProviderInfoManagerTest.cs --- using System; using Adapdev.Data; using NUnit.Framework; namespace Adapdev.Data.Tests { /// <summary> /// Summary description for ProviderInfoManagerTest. /// </summary> /// [TestFixture] public class ProviderInfoManagerTest { [Test] public void GetDefaultValue() { int oracleId = ProviderInfoManager.GetInstance().GetIdByName(DbProviderType.ORACLE,"CHAR"); Assert.AreEqual(129, oracleId, "Oracle types don't match."); int sqlId = ProviderInfoManager.GetInstance().GetIdByName(DbProviderType.SQLSERVER, "CHAR"); Assert.AreEqual(129, sqlId, "Sql Server types don't match."); } } } |
From: Sean M. <int...@us...> - 2005-11-16 05:33:36
|
Update of /cvsroot/adapdev/Adapdev/src In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv19977/src Added Files: AdapdevAssemblyInfo.cs AdapdevFramework.sln adapdev.snk Log Message: Reposting to the repository after it got hosed --- NEW FILE: AdapdevAssemblyInfo.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("Adapdev.NET")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Adapdev Technologies, LLC")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("2004 Adapdev Technologies, LLC")] [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("0.8.3")] // // 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("..\\..\\..\\adapdev.snk")] [assembly: AssemblyKeyName("")] [assembly: log4net.Config.DOMConfigurator(Watch=true)] --- NEW FILE: AdapdevFramework.sln --- Microsoft Visual Studio Solution File, Format Version 8.00 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Adapdev", "Adapdev\Adapdev.csproj", "{CC30A321-2569-4B1F-8E1A-781B5509B56D}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Adapdev.Tests", "Adapdev.Tests\Adapdev.Tests.csproj", "{6012639A-3857-46CC-80BC-32CBF1F104D7}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Adapdev.Data", "Adapdev.Data\Adapdev.Data.csproj", "{08C5794D-44ED-4E75-A1C1-48A28C3D0044}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Adapdev.Data.Tests", "Adapdev.Data.Tests\Adapdev.Data.Tests.csproj", "{07695A4B-39A8-41CB-A21B-E61B3990C20F}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Adapdev.CodeGen", "Adapdev.CodeGen\Adapdev.CodeGen.csproj", "{2D8FC662-0244-49F1-8017-DFE73B191017}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Adapdev.CodeGen.Tests", "Adapdev.CodeGen.Tests\Adapdev.CodeGen.Tests.csproj", "{FF310091-86DF-4E18-8061-7694C0A2669B}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Adapdev.Cache", "Adapdev.Cache\Adapdev.Cache.csproj", "{84F894AC-EFD7-4342-B2A5-CF3EF80E0B1C}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Adapdev.Cache.Tests", "Adapdev.Cache.Tests\Adapdev.Cache.Tests.csproj", "{D2D00D68-57F1-4CEA-B9E6-4E7FD7CE4E43}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Adapdev.Web", "Adapdev.Web\Adapdev.Web.csproj", "{49455A1D-1BBB-4356-AB83-E5690726C681}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Adapdev.Web.Tests", "Adapdev.Web.Tests\Adapdev.Web.Tests.csproj", "{5174127E-DD36-4C32-AB42-9ADD34260BB2}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Adapdev.NVelocity", "Adapdev.NVelocity\Adapdev.NVelocity.csproj", "{75D57D5C-250A-447C-80BC-2FF9DC8A14D2}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Adapdev.Windows.Forms", "Adapdev.Windows.Forms\Adapdev.Windows.Forms.csproj", "{0BE602B6-D67E-414E-B852-A2AC61305E8E}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Adapdev.Windows.Forms.Tests", "Adapdev.Windows.Forms.Tests\Adapdev.Windows.Forms.Tests.csproj", "{D51D807A-D70C-445A-B1D9-062D61463AB7}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Adapdev.UnitTest", "Adapdev.UnitTest\Adapdev.UnitTest.csproj", "{D450E7B3-CF48-421E-8B5E-9526E77E24C6}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Adapdev.UnitTest.Core", "Adapdev.UnitTest.Core\Adapdev.UnitTest.Core.csproj", "{B8592DE8-C10B-4ACB-A422-919C02C04B05}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FullBuild", "FullBuild\FullBuild.csproj", "{250B6F4B-3256-4DEB-84B6-8C919058FDDC}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Adapdev.UnitTest.Tests", "Adapdev.UnitTest.Tests\Adapdev.UnitTest.Tests.csproj", "{7DC72EED-57C5-43A3-AB03-D456816A6F1A}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Adapdev.UnitTest.Core.Tests", "Adapdev.UnitTest.Core.Tests\Adapdev.UnitTest.Core.Tests.csproj", "{D0F97D76-E7A6-4059-B902-F792626A29A8}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Adapdev.UnitTest.TestRunner", "Adapdev.UnitTest.TestRunner\Adapdev.UnitTest.TestRunner.csproj", "{2D0C35AA-CC64-4513-947D-F67C035D2B71}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Adapdev.UnitTest.TestRunner.Tests", "Adapdev.UnitTest.TestRunner.Tests\Adapdev.UnitTest.TestRunner.Tests.csproj", "{59AFE252-CBC0-434A-8350-0A4722654CDA}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Adapdev.UnitTest.Core.AdapdevTests", "Adapdev.UnitTest.Core.AdapdevTests\Adapdev.UnitTest.Core.AdapdevTests.csproj", "{3085922A-8F7B-4C5F-8C31-41BD7CCC0D05}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Global GlobalSection(SolutionConfiguration) = preSolution Debug = Debug Release = Release EndGlobalSection GlobalSection(ProjectConfiguration) = postSolution {CC30A321-2569-4B1F-8E1A-781B5509B56D}.Debug.ActiveCfg = Debug|.NET {CC30A321-2569-4B1F-8E1A-781B5509B56D}.Debug.Build.0 = Debug|.NET {CC30A321-2569-4B1F-8E1A-781B5509B56D}.Release.ActiveCfg = Release|.NET {CC30A321-2569-4B1F-8E1A-781B5509B56D}.Release.Build.0 = Release|.NET {6012639A-3857-46CC-80BC-32CBF1F104D7}.Debug.ActiveCfg = Debug|.NET {6012639A-3857-46CC-80BC-32CBF1F104D7}.Debug.Build.0 = Debug|.NET {6012639A-3857-46CC-80BC-32CBF1F104D7}.Release.ActiveCfg = Release|.NET {6012639A-3857-46CC-80BC-32CBF1F104D7}.Release.Build.0 = Release|.NET {08C5794D-44ED-4E75-A1C1-48A28C3D0044}.Debug.ActiveCfg = Debug|.NET {08C5794D-44ED-4E75-A1C1-48A28C3D0044}.Debug.Build.0 = Debug|.NET {08C5794D-44ED-4E75-A1C1-48A28C3D0044}.Release.ActiveCfg = Release|.NET {08C5794D-44ED-4E75-A1C1-48A28C3D0044}.Release.Build.0 = Release|.NET {07695A4B-39A8-41CB-A21B-E61B3990C20F}.Debug.ActiveCfg = Debug|.NET {07695A4B-39A8-41CB-A21B-E61B3990C20F}.Debug.Build.0 = Debug|.NET {07695A4B-39A8-41CB-A21B-E61B3990C20F}.Release.ActiveCfg = Release|.NET {07695A4B-39A8-41CB-A21B-E61B3990C20F}.Release.Build.0 = Release|.NET {2D8FC662-0244-49F1-8017-DFE73B191017}.Debug.ActiveCfg = Debug|.NET {2D8FC662-0244-49F1-8017-DFE73B191017}.Debug.Build.0 = Debug|.NET {2D8FC662-0244-49F1-8017-DFE73B191017}.Release.ActiveCfg = Release|.NET {2D8FC662-0244-49F1-8017-DFE73B191017}.Release.Build.0 = Release|.NET {FF310091-86DF-4E18-8061-7694C0A2669B}.Debug.ActiveCfg = Debug|.NET {FF310091-86DF-4E18-8061-7694C0A2669B}.Debug.Build.0 = Debug|.NET {FF310091-86DF-4E18-8061-7694C0A2669B}.Release.ActiveCfg = Release|.NET {FF310091-86DF-4E18-8061-7694C0A2669B}.Release.Build.0 = Release|.NET {84F894AC-EFD7-4342-B2A5-CF3EF80E0B1C}.Debug.ActiveCfg = Debug|.NET {84F894AC-EFD7-4342-B2A5-CF3EF80E0B1C}.Debug.Build.0 = Debug|.NET {84F894AC-EFD7-4342-B2A5-CF3EF80E0B1C}.Release.ActiveCfg = Release|.NET {84F894AC-EFD7-4342-B2A5-CF3EF80E0B1C}.Release.Build.0 = Release|.NET {D2D00D68-57F1-4CEA-B9E6-4E7FD7CE4E43}.Debug.ActiveCfg = Debug|.NET {D2D00D68-57F1-4CEA-B9E6-4E7FD7CE4E43}.Debug.Build.0 = Debug|.NET {D2D00D68-57F1-4CEA-B9E6-4E7FD7CE4E43}.Release.ActiveCfg = Release|.NET {D2D00D68-57F1-4CEA-B9E6-4E7FD7CE4E43}.Release.Build.0 = Release|.NET {49455A1D-1BBB-4356-AB83-E5690726C681}.Debug.ActiveCfg = Debug|.NET {49455A1D-1BBB-4356-AB83-E5690726C681}.Debug.Build.0 = Debug|.NET {49455A1D-1BBB-4356-AB83-E5690726C681}.Release.ActiveCfg = Release|.NET {49455A1D-1BBB-4356-AB83-E5690726C681}.Release.Build.0 = Release|.NET {5174127E-DD36-4C32-AB42-9ADD34260BB2}.Debug.ActiveCfg = Debug|.NET {5174127E-DD36-4C32-AB42-9ADD34260BB2}.Debug.Build.0 = Debug|.NET {5174127E-DD36-4C32-AB42-9ADD34260BB2}.Release.ActiveCfg = Release|.NET {5174127E-DD36-4C32-AB42-9ADD34260BB2}.Release.Build.0 = Release|.NET {75D57D5C-250A-447C-80BC-2FF9DC8A14D2}.Debug.ActiveCfg = Debug|.NET {75D57D5C-250A-447C-80BC-2FF9DC8A14D2}.Debug.Build.0 = Debug|.NET {75D57D5C-250A-447C-80BC-2FF9DC8A14D2}.Release.ActiveCfg = Release|.NET {75D57D5C-250A-447C-80BC-2FF9DC8A14D2}.Release.Build.0 = Release|.NET {0BE602B6-D67E-414E-B852-A2AC61305E8E}.Debug.ActiveCfg = Debug|.NET {0BE602B6-D67E-414E-B852-A2AC61305E8E}.Debug.Build.0 = Debug|.NET {0BE602B6-D67E-414E-B852-A2AC61305E8E}.Release.ActiveCfg = Release|.NET {0BE602B6-D67E-414E-B852-A2AC61305E8E}.Release.Build.0 = Release|.NET {D51D807A-D70C-445A-B1D9-062D61463AB7}.Debug.ActiveCfg = Debug|.NET {D51D807A-D70C-445A-B1D9-062D61463AB7}.Debug.Build.0 = Debug|.NET {D51D807A-D70C-445A-B1D9-062D61463AB7}.Release.ActiveCfg = Release|.NET {D51D807A-D70C-445A-B1D9-062D61463AB7}.Release.Build.0 = Release|.NET {D450E7B3-CF48-421E-8B5E-9526E77E24C6}.Debug.ActiveCfg = Debug|.NET {D450E7B3-CF48-421E-8B5E-9526E77E24C6}.Debug.Build.0 = Debug|.NET {D450E7B3-CF48-421E-8B5E-9526E77E24C6}.Release.ActiveCfg = Release|.NET {D450E7B3-CF48-421E-8B5E-9526E77E24C6}.Release.Build.0 = Release|.NET {B8592DE8-C10B-4ACB-A422-919C02C04B05}.Debug.ActiveCfg = Debug|.NET {B8592DE8-C10B-4ACB-A422-919C02C04B05}.Debug.Build.0 = Debug|.NET {B8592DE8-C10B-4ACB-A422-919C02C04B05}.Release.ActiveCfg = Release|.NET {B8592DE8-C10B-4ACB-A422-919C02C04B05}.Release.Build.0 = Release|.NET {250B6F4B-3256-4DEB-84B6-8C919058FDDC}.Debug.ActiveCfg = Debug|.NET {250B6F4B-3256-4DEB-84B6-8C919058FDDC}.Debug.Build.0 = Debug|.NET {250B6F4B-3256-4DEB-84B6-8C919058FDDC}.Release.ActiveCfg = Release|.NET {250B6F4B-3256-4DEB-84B6-8C919058FDDC}.Release.Build.0 = Release|.NET {7DC72EED-57C5-43A3-AB03-D456816A6F1A}.Debug.ActiveCfg = Debug|.NET {7DC72EED-57C5-43A3-AB03-D456816A6F1A}.Debug.Build.0 = Debug|.NET {7DC72EED-57C5-43A3-AB03-D456816A6F1A}.Release.ActiveCfg = Release|.NET {7DC72EED-57C5-43A3-AB03-D456816A6F1A}.Release.Build.0 = Release|.NET {D0F97D76-E7A6-4059-B902-F792626A29A8}.Debug.ActiveCfg = Debug|.NET {D0F97D76-E7A6-4059-B902-F792626A29A8}.Debug.Build.0 = Debug|.NET {D0F97D76-E7A6-4059-B902-F792626A29A8}.Release.ActiveCfg = Release|.NET {D0F97D76-E7A6-4059-B902-F792626A29A8}.Release.Build.0 = Release|.NET {2D0C35AA-CC64-4513-947D-F67C035D2B71}.Debug.ActiveCfg = Debug|.NET {2D0C35AA-CC64-4513-947D-F67C035D2B71}.Debug.Build.0 = Debug|.NET {2D0C35AA-CC64-4513-947D-F67C035D2B71}.Release.ActiveCfg = Release|.NET {2D0C35AA-CC64-4513-947D-F67C035D2B71}.Release.Build.0 = Release|.NET {59AFE252-CBC0-434A-8350-0A4722654CDA}.Debug.ActiveCfg = Debug|.NET {59AFE252-CBC0-434A-8350-0A4722654CDA}.Debug.Build.0 = Debug|.NET {59AFE252-CBC0-434A-8350-0A4722654CDA}.Release.ActiveCfg = Release|.NET {59AFE252-CBC0-434A-8350-0A4722654CDA}.Release.Build.0 = Release|.NET {3085922A-8F7B-4C5F-8C31-41BD7CCC0D05}.Debug.ActiveCfg = Debug|.NET {3085922A-8F7B-4C5F-8C31-41BD7CCC0D05}.Debug.Build.0 = Debug|.NET {3085922A-8F7B-4C5F-8C31-41BD7CCC0D05}.Release.ActiveCfg = Release|.NET {3085922A-8F7B-4C5F-8C31-41BD7CCC0D05}.Release.Build.0 = Release|.NET EndGlobalSection GlobalSection(SolutionItems) = postSolution adapdev.snk = adapdev.snk AdapdevAssemblyInfo.cs = AdapdevAssemblyInfo.cs EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution EndGlobalSection GlobalSection(ExtensibilityAddIns) = postSolution EndGlobalSection EndGlobal --- NEW FILE: adapdev.snk --- (This appears to be a binary file; contents omitted.) |
From: Sean M. <int...@us...> - 2005-11-16 05:33:36
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev/Attributes In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv19977/src/Adapdev/Attributes Added Files: SchemaDataRewritableAttribute.cs Log Message: Reposting to the repository after it got hosed --- 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;} } } } |
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.Cache.Tests/Scavengers In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv19977/src/Adapdev.Cache.Tests/Scavengers Added Files: AbsoluteExpirationScavengerTest.cs BaseScavengerTest.cs GreaterThanOrdinalScavengerTest.cs SlidingExpirationScavengerTest.cs Log Message: Reposting to the repository after it got hosed --- NEW FILE: SlidingExpirationScavengerTest.cs --- using System; using Adapdev.Cache; using Adapdev.Cache.Scavengers; using Adapdev.Mock; using NUnit.Framework; namespace Adapdev.Cache.Scavengers.Tests { /// <summary> /// Summary description for DateScavenger. /// </summary> /// [TestFixture] public class SlidingExpirationScavengerTest : BaseScavengerTest { public override ICache GetCache() { return new MutableInMemoryCache(); } [Test] public void ScavengeAndRemove() { IScavenger scavenger = new SlidingExpirationScavenger(new TimeSpan(0,0,0,1)); Assert.AreEqual(100, this.cache.Count); System.Threading.Thread.Sleep(2000); this.cache.Scavenge(scavenger); Assert.AreEqual(0, this.cache.Count, "All entries should have been removed"); } [Test] public void ScavengeAndLeave() { IScavenger scavenger = new SlidingExpirationScavenger(new TimeSpan(1,0,0,0)); Assert.AreEqual(100, this.cache.Count); this.cache.Scavenge(scavenger); Assert.AreEqual(100, this.cache.Count, "No entries should have been removed"); } } } --- NEW FILE: GreaterThanOrdinalScavengerTest.cs --- using System; using Adapdev.Cache; using Adapdev.Cache.Scavengers; using Adapdev.Mock; using NUnit.Framework; namespace Adapdev.Cache.Scavengers.Tests { /// <summary> /// Summary description for DateScavenger. /// </summary> /// [TestFixture] public class GreaterThanOrdinalScavengerTest : BaseScavengerTest { public override ICache GetCache() { return new MutableInMemoryCache(); } [Test] public void ScavengeAndRemove() { IScavenger scavenger = new GreaterThanOrdinalScavenger(80); Assert.AreEqual(100, this.cache.Count); this.cache.Scavenge(scavenger); Assert.AreEqual(80, this.cache.Count, "All entries should have been removed"); } [Test] public void ScavengeAndLeave() { IScavenger scavenger = new GreaterThanOrdinalScavenger(100); Assert.AreEqual(100, this.cache.Count); this.cache.Scavenge(scavenger); Assert.AreEqual(100, this.cache.Count, "All entries should have been removed"); } } } --- NEW FILE: AbsoluteExpirationScavengerTest.cs --- using System; using Adapdev.Cache; using Adapdev.Cache.Scavengers; using Adapdev.Mock; using NUnit.Framework; namespace Adapdev.Cache.Scavengers.Tests { /// <summary> /// Summary description for DateScavenger. /// </summary> /// [TestFixture] public class AbsoluteExpirationScavengerTest : BaseScavengerTest { public override ICache GetCache() { return new MutableInMemoryCache(); } [Test] public void ScavengeAndRemove() { IScavenger scavenger = new AbsoluteExpirationScavenger(DateTime.Today.AddDays(1)); Assert.AreEqual(100, this.cache.Count); this.cache.Scavenge(scavenger); Assert.AreEqual(0, this.cache.Count, "All entries should have been removed"); } [Test] public void ScavengeAndLeave() { IScavenger scavenger = new AbsoluteExpirationScavenger(DateTime.Today); Assert.AreEqual(100, this.cache.Count); this.cache.Scavenge(scavenger); Assert.AreEqual(100, this.cache.Count, "All entries should have been removed"); } } } --- NEW FILE: BaseScavengerTest.cs --- using System; using Adapdev.Cache; using Adapdev.Cache.Scavengers; using Adapdev.Mock; using NUnit.Framework; namespace Adapdev.Cache.Scavengers.Tests { /// <summary> /// Summary description for BaseScavengerTest. /// </summary> public abstract class BaseScavengerTest { protected ICache cache = null; public abstract ICache GetCache(); [SetUp] public void SetUp() { this.cache = this.GetCache(); this.PopulateCache(); } [TearDown] public void TearDown() { this.cache.Clear(); } public void PopulateCache() { for(int i = 0; i < 100; i++) { SuppliersEntity e = new SuppliersEntity(); e.SupplierID = i; e.Fax = "12345"; e.CompanyName = "Test"; e.ContactName = "Test"; this.cache.Add(e.SupplierID, e); } } } } |
Update of /cvsroot/adapdev/Adapdev/src/Adapdev/Text/Indexing/FullText/Filters In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv19977/src/Adapdev/Text/Indexing/FullText/Filters Added Files: AbstractFilter.cs ConditionalFilter.cs RegexTokenFilter.cs SpecialCharactersFilter.cs TokenLengthFilter.cs WordFilter.cs Log Message: Reposting to the repository after it got hosed --- NEW FILE: RegexTokenFilter.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.Text.RegularExpressions; using Adapdev.Text.Indexing.FullText; namespace Adapdev.Text.Indexing.FullText.Filters { /// <summary> /// Filters off tokens based on a regular expression. /// </summary> /// <remarks>This filter will filter off /// any tokens that <b>match</b> the regular /// expression (and not the ones that don't)</remarks> [Serializable] public class RegexTokenFilter : ConditionalFilter { Regex _regex; /// <summary> /// Creates a new filter that will filter off any /// tokens that match the regular expression passed /// as argument. /// </summary> /// <param name="regex">the regular expression</param> public RegexTokenFilter(string regex) : this(null, regex) { } /// <summary> /// Creates a new filter that will filter off any /// tokens that match the regular expression passed /// as argument. /// </summary> /// <param name="previous">the previous tokenizer in the chain</param> /// <param name="regex">the regular expression</param> public RegexTokenFilter(ITokenizer previous, string regex) : base(previous) { if (null == regex) { throw new ArgumentNullException("regex", "regex can't be null!"); } _regex = new Regex(regex); } /// <summary> /// Creates a new filter that will filter off any /// tokens that match the regular expression passed /// as argument. /// </summary> /// <param name="regex">the regular expression</param> public RegexTokenFilter(Regex regex) : this(null, regex) { } /// <summary> /// Creates a new filter that will filter off any /// tokens that match the regular expression passed /// as argument. /// </summary> /// <param name="previous">the previous tokenizer in the chain</param> /// <param name="regex">the regular expression</param> public RegexTokenFilter(ITokenizer previous, Regex regex) : base(previous) { if (null == regex) { throw new ArgumentNullException("regex", "regex can't be null!"); } _regex = regex; } /// <summary> /// See <see cref="ConditionalFilter.IsValidToken"/> for details. /// </summary> /// <param name="token"></param> /// <returns></returns> protected override bool IsValidToken(Token token) { return !_regex.IsMatch(token.Value); } } } --- NEW FILE: AbstractFilter.cs --- #region license // Bamboo.Prevalence - a .NET object prevalence engine // Copyright (C) 2004 Rodrigo B. de Oliveira // // Based on the original concept and implementation of Prevayler (TM) // by Klaus Wuestefeld. Visit http://www.prevayler.org for details. // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, // and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE // OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // Contact Information // // http://bbooprevalence.sourceforge.net // mailto:rod...@us... #endregion using System; using Adapdev.Text.Indexing.FullText; namespace Adapdev.Text.Indexing.FullText.Filters { /// <summary> /// Basic implementation for ITokenFilter with /// support for tokenizer chaining. /// </summary> [Serializable] public abstract class AbstractFilter : ITokenFilter { /// <summary> /// the previous tokenizer in the chain /// </summary> protected ITokenizer _previous; /// <summary> /// Creates a new filter with no previous /// tokenizer. /// </summary> protected AbstractFilter() { _previous = null; } /// <summary> /// Creates a new filter with a previous /// tokenizer in a tokenizer chain. /// </summary> /// <param name="previous">the previous tokenizer /// in the chain</param> protected AbstractFilter(ITokenizer previous) { _previous = previous; } /// <summary> /// Gets/sets the previous tokenizer /// in the chain. /// </summary> public ITokenizer Previous { get { return _previous; } set { _previous = value; } } /// <summary> /// Returns a MemberwiseClone of this object /// with the guarantee that the tail argument /// will be the last tokenizer in the new /// tokenizer chain. /// </summary> /// <param name="tail">the last tokenizer for the /// new chain</param> /// <returns>cloned chain with tail as the /// last tokenizer in the chain</returns> public ITokenizer Clone(ITokenizer tail) { AbstractFilter clone = MemberwiseClone() as AbstractFilter; if (null == _previous) { clone._previous = tail; } else { clone._previous = _previous.Clone(tail); } return clone; } /// <summary> /// Must be supplied by derived classes. /// </summary> /// <returns></returns> public abstract Token NextToken(); } } --- NEW FILE: WordFilter.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 Adapdev.Text.Indexing.FullText; namespace Adapdev.Text.Indexing.FullText.Filters { /// <summary> /// Filters off tokens by word. /// </summary> [Serializable] public class WordFilter : ConditionalFilter { Hashtable _words; /// <summary> /// See <see cref="WordFilter(string[])"/>. /// </summary> /// <param name="previous">the previous tokenizer in the chain</param> /// <param name="words">list of words that should be filtered /// off the chain</param> public WordFilter(ITokenizer previous, params string[] words) : base(previous) { if (null == words) { throw new ArgumentNullException("words"); } _words = new Hashtable(words.Length); foreach (string word in words) { _words[word] = null; } } /// <summary> /// Creates a new filter that will not allow /// any words in the list represented by the words /// argument to pass through the chain. /// </summary> /// <param name="words">list of words that should be filtered /// off the chain</param> public WordFilter(params string[] words) : this(null, words) { } /// <summary> /// See <see cref="ConditionalFilter.IsValidToken"/> for details. /// </summary> /// <param name="token"></param> /// <returns></returns> protected override bool IsValidToken(Token token) { return !_words.ContainsKey(token.Value); } } } --- NEW FILE: SpecialCharactersFilter.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.Globalization; using System.Text; using Adapdev.Text.Indexing.FullText; namespace Adapdev.Text.Indexing.FullText.Filters { /// <summary> /// A filter that replaces special characters by /// their simpler ASCII counterparts. /// </summary> [Serializable] public class SpecialCharactersFilter : AbstractFilter { /// <summary> /// Creates a new filter. /// </summary> public SpecialCharactersFilter() { } /// <summary> /// Creates a new filter in a tokenizer chain. /// </summary> /// <param name="previous">previous tokenizer in the chain</param> public SpecialCharactersFilter(ITokenizer previous) : base(previous) { } /// <summary> /// Gets the token from the previous tokenizer in the /// chain and replaces every "complex" character /// in the token by its simpler counterpart. /// </summary> /// <returns>the new token or null</returns> public override Token NextToken() { Token token = _previous.NextToken(); if (null != token) { token.Value = Filter(token.Value); } return token; } public static string Filter(string value) { char[] mapped = new char[value.Length]; for (int i=0; i<value.Length; ++i) { char c = char.ToLower(value[i]); switch (c) { case 'á': c = 'a'; break; case 'ã': c = 'a'; break; case 'â': c = 'a'; break; case 'à ': c = 'a'; break; case 'é': c = 'e'; break; case 'ê': c = 'e'; break; case 'Ã': c = 'i'; break; case 'ó': c = 'o'; break; case 'õ': c = 'o'; break; case 'ô': c = 'o'; break; case 'ú': c = 'u'; break; case 'ü': c = 'u'; break; case 'ç': c = 'c'; break; } mapped[i] = c; } return new string(mapped); } } } --- NEW FILE: ConditionalFilter.cs --- #region license // Bamboo.Prevalence - a .NET object prevalence engine // Copyright (C) 2004 Rodrigo B. de Oliveira // // Based on the original concept and implementation of Prevayler (TM) // by Klaus Wuestefeld. Visit http://www.prevayler.org for details. // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, // and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE // OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // Contact Information // // http://bbooprevalence.sourceforge.net // mailto:rod...@us... #endregion using System; using Adapdev.Text.Indexing.FullText; namespace Adapdev.Text.Indexing.FullText.Filters { /// <summary> /// Base class for filter implementations that /// exclude tokens from the stream based on /// a condition. /// </summary> [Serializable] public abstract class ConditionalFilter : AbstractFilter { /// <summary> /// Creates a standalone filter (with no previous /// tokenizer). /// </summary> protected ConditionalFilter() { } /// <summary> /// Creates a filter in a filter chain. /// </summary> /// <param name="previous">the previous token in the chain</param> protected ConditionalFilter(ITokenizer previous) : base(previous) { } /// <summary> /// Gets a token from the previous tokenizer in the chain /// and checks the condition implemented by IsValidToken, /// when IsValidToken returns false the token is discarded /// and a new one is tried. This process is repeated until /// IsValidToken returns true or the previous tokenizer /// returns null. /// </summary> /// <returns>the next token for which IsValidToken returns true or /// null when the previous tokenizer runs out of tokens</returns> public override Adapdev.Text.Indexing.FullText.Token NextToken() { Token token = _previous.NextToken(); while (null != token) { if (IsValidToken(token)) { break; } token = _previous.NextToken(); } return token; } /// <summary> /// Test if the token is a valid token and /// as such should be returned to the /// caller of <see cref="NextToken" />. /// </summary> /// <param name="token">token to be tested</param> /// <returns>true if the token is valid, false otherwise</returns> protected abstract bool IsValidToken(Token token); } } --- NEW FILE: TokenLengthFilter.cs --- #region license // Bamboo.Prevalence - a .NET object prevalence engine // Copyright (C) 2004 Rodrigo B. de Oliveira // // Based on the original concept and implementation of Prevayler (TM) // by Klaus Wuestefeld. Visit http://www.prevayler.org for details. // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, // and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE // OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // Contact Information // // http://bbooprevalence.sourceforge.net // mailto:rod...@us... #endregion using System; using Adapdev.Text.Indexing.FullText; namespace Adapdev.Text.Indexing.FullText.Filters { /// <summary> /// Filters off tokens by length. /// </summary> [Serializable] public class TokenLengthFilter : ConditionalFilter { int _minTokenLength; /// <summary> /// Creates a new filter that will only allow /// tokens with at least minTokenLength /// characters to pass. /// </summary> /// <param name="minTokenLength">minimum token length</param> public TokenLengthFilter(int minTokenLength) { _minTokenLength = minTokenLength; } /// <summary> /// See <see cref="TokenLengthFilter(int)"/>. /// </summary> /// <param name="previous">previous tokenizer in the chain</param> /// <param name="minTokenLength">minimum token length</param> public TokenLengthFilter(ITokenizer previous, int minTokenLength) : base(previous) { _minTokenLength = minTokenLength; } /// <summary> /// See <see cref="ConditionalFilter.IsValidToken"/> for details. /// </summary> /// <param name="token"></param> /// <returns></returns> protected override bool IsValidToken(Token token) { return (token.Value.Length >= _minTokenLength); } } } |
From: Sean M. <int...@us...> - 2005-11-16 05:33:35
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev/Text/Indexing In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv19977/src/Adapdev/Text/Indexing Added Files: IIndex.cs IRecord.cs ISearchExpression.cs ISearchHitFilter.cs SearchResult.cs Log Message: Reposting to the repository after it got hosed --- 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 05:33:35
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.Cache.Tests In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv19977/src/Adapdev.Cache.Tests Added Files: AbstractICacheTest.cs Adapdev.Cache.Tests.csproj CacheManagerTest.cs CacheStatsTest.cs CacheUtilTest.cs FileCacheTest.cs ImmutableInMemoryCache.cs MutableInMemoryCacheTest.cs Log Message: Reposting to the repository after it got hosed --- NEW FILE: AbstractICacheTest.cs --- using System; using NUnit.Framework; using Adapdev.Cache; using Adapdev.Mock; namespace Adapdev.Tests.Cache { /// <summary> /// Summary description for MutableInMemoryCache. /// </summary> /// public abstract class AbstractICacheTest { protected ICache cache = null; public abstract ICache GetCache(); [SetUp] public void Setup() { this.cache = this.GetCache(); } [TearDown] public void TearDown() { cache.Clear(); cache = null; } [Test] public void Add() { SuppliersEntity e = new SuppliersEntity(); e.SupplierID = 12; cache.Add(12, e); Assert.IsTrue(cache.Count == 1, "Cache count should be 1."); } [Test] public void Get() { SuppliersEntity e = new SuppliersEntity(); e.SupplierID = 12; e.ContactName = "Joe Schmoe"; cache.Add(12, e); Assert.IsTrue(cache.Count == 1, "Cache count should be 1."); Assert.AreEqual(e.ContactName, (cache.Get(typeof(SuppliersEntity), 12) as SuppliersEntity).ContactName); } [Test] public void Clear() { SuppliersEntity e = new SuppliersEntity(); e.SupplierID = 12; cache.Add(12, e); Assert.IsTrue(cache.Count == 1, "Cache count should be 1."); cache.Clear(); Assert.IsTrue(cache.Count == 0, "Cache count should be 0."); } [Test] public void Remove() { SuppliersEntity e = new SuppliersEntity(); e.SupplierID = 12; cache.Add(12, e); Assert.IsTrue(cache.Count == 1, "Cache count should be 1."); cache.Remove(e.GetType(), e.SupplierID); Assert.IsTrue(cache.Count == 0, "Cache count should be 0."); } [Test] public void Entries() { SuppliersEntity e1 = new SuppliersEntity(); e1.SupplierID = 12; SuppliersEntity e2 = new SuppliersEntity(); e2.SupplierID = 13; cache.Add(e1.SupplierID, e1); cache.Add(e2.SupplierID, e2); Assert.IsTrue(cache.Count == 2, "Cache count should be 2."); int i = 0; foreach(CacheItem c in cache.Entries) { i++; Assert.IsNotNull(c.Object); } Assert.AreEqual(cache.Count, i); } [Test] public void Ordinal() { SuppliersEntity e1 = new SuppliersEntity(); e1.SupplierID = 12; SuppliersEntity e2 = new SuppliersEntity(); e2.SupplierID = 13; cache.Add(e1.SupplierID, e1); cache.Add(e2.SupplierID, e2); Assert.IsTrue(cache.Count == 2, "Cache count should be 2."); CacheItem c1 = cache.GetCacheItem(typeof(SuppliersEntity), e1.SupplierID); CacheItem c2 = cache.GetCacheItem(typeof(SuppliersEntity), e2.SupplierID); Assert.IsTrue(c1.Ordinal != c2.Ordinal, "Ordinals should be different."); Assert.IsTrue(c2.Ordinal == c1.Ordinal + 1, "Ordinals should only be 1 number apart."); } [Test] public void Contains() { SuppliersEntity e1 = new SuppliersEntity(); e1.SupplierID = 12; cache.Add(e1.SupplierID, e1); Assert.IsTrue(cache.Contains(e1.GetType(), e1.SupplierID), "Cache should return true for .Contains"); } [Test] public void CacheItem() { SuppliersEntity e1 = new SuppliersEntity(); e1.SupplierID = 12; cache.Add(e1.SupplierID, e1); CacheItem c = cache.GetCacheItem(e1.GetType(), e1.SupplierID); Assert.AreEqual(e1.GetType(), c.ObjectType, "Object Types aren't equal."); Assert.AreEqual(1, c.Ordinal, "Ordinal should be 1"); Assert.AreEqual(e1.SupplierID.ToString(), c.Key, "Keys are not equal."); Console.WriteLine(c); } [Test] public virtual void Copy() { ICache source = this.GetCache(); this.cache.Add(1, new SuppliersEntity()); source.Add(2, new SuppliersEntity()); Assert.AreEqual(1, this.cache.Count); Assert.AreEqual(1, source.Count); this.cache.Copy(source); Assert.AreEqual(2, this.cache.Count); } } } --- NEW FILE: FileCacheTest.cs --- using System; using NUnit.Framework; using Adapdev.Cache; using Adapdev.Mock; namespace Adapdev.Tests.Cache { /// <summary> /// Summary description for MutableInMemoryCache. /// </summary> /// [TestFixture] public class FileCacheTest : AbstractICacheTest { public override ICache GetCache() { return new FileCache(); } [Test] public void Immutable() { SuppliersEntity e1 = new SuppliersEntity(); e1.SupplierID = 12; cache.Add(e1.SupplierID, e1); SuppliersEntity e2 = cache.Get(typeof(SuppliersEntity), 12) as SuppliersEntity; e2.SupplierID = 13; Assert.IsTrue(cache.Contains(e1.GetType(), 12), "Cache key should not change."); SuppliersEntity e3 = cache.Get(typeof(SuppliersEntity), 12) as SuppliersEntity; Assert.IsFalse(13 == e3.SupplierID, "Object in cache should NOT have been updated."); } } } --- NEW FILE: MutableInMemoryCacheTest.cs --- using System; using NUnit.Framework; using Adapdev.Cache; using Adapdev.Mock; namespace Adapdev.Tests.Cache { /// <summary> /// Summary description for MutableInMemoryCache. /// </summary> /// [TestFixture] public class MutableInMemoryCacheTest : AbstractICacheTest { public override ICache GetCache() { return new MutableInMemoryCache(); } [Test] public void Mutable() { SuppliersEntity e1 = new SuppliersEntity(); e1.SupplierID = 12; cache.Add(e1.SupplierID, e1); SuppliersEntity e2 = cache.Get(typeof(SuppliersEntity), 12) as SuppliersEntity; e2.SupplierID = 13; Assert.IsTrue(cache.Contains(e1.GetType(), 12), "Cache key should not change."); SuppliersEntity e3 = cache.Get(typeof(SuppliersEntity), 12) as SuppliersEntity; Assert.AreEqual(13, e3.SupplierID, "Object in cache should have been updated."); } } } --- NEW FILE: CacheManagerTest.cs --- using System; using NUnit.Framework; using Adapdev.Cache; using Adapdev.Mock; namespace Adapdev.Tests.Cache { /// <summary> /// Summary description for CacheManagerTest. /// </summary> /// [TestFixture] public class CacheManagerTest { [Test] public void Cache() { Assert.AreEqual(typeof(ImmutableInMemoryCache), CacheManager.Cache.GetType()); CacheManager.Cache.Add(1, new SuppliersEntity()); Assert.AreEqual(1, CacheManager.Cache.Count); CacheManager.Cache = new MutableInMemoryCache(); Assert.AreEqual(0, CacheManager.Cache.Count, "Cache has switched, so count should be 0."); } [Test] public void SetCache() { Assert.AreEqual(typeof(ImmutableInMemoryCache), CacheManager.Cache.GetType()); CacheManager.Cache.Add(1, new SuppliersEntity()); Assert.AreEqual(1, CacheManager.Cache.Count); CacheManager.SetCache(CacheType.MutableInMemory); Assert.AreEqual(1, CacheManager.Cache.Count, "Cache has switched BUT should have been copied, so count should be 1."); CacheManager.SetCache(CacheType.ImmutableInMemory, false); Assert.AreEqual(0, CacheManager.Cache.Count, "Cache has switched BUT should not have been copied, so count should be 0."); } } } --- NEW FILE: CacheStatsTest.cs --- using System; namespace Adapdev.Cache.Tests { using Adapdev.Mock; using Adapdev.Tests.Cache; using NUnit.Framework; /// <summary> /// Summary description for CacheStatsTest. /// </summary> /// [TestFixture] public class CacheStatsTest : AbstractICacheTest { public override ICache GetCache() { return new CacheStats(new ImmutableInMemoryCache()); } [Test] public void Stats() { this.cache.Add(1, new SuppliersEntity()); object o = this.cache.Get(typeof(SuppliersEntity), 1); Assert.IsNotNull(o, "Object came back as null"); CacheStats stats = this.cache as CacheStats; Assert.AreEqual(1, stats.HitCount, "HitCount is incorrect."); Assert.AreEqual(0, stats.MissCount, "MissCount is incorrect"); Assert.IsTrue(stats.InsertTime > 0, "InsertTime is incorrect."); Assert.IsTrue(stats.RetrieveTime > 0, "RetrieveTime is incorrect."); Console.WriteLine(stats); } } } --- NEW FILE: CacheUtilTest.cs --- using System; using NUnit.Framework; using Adapdev.Cache; using Adapdev.Mock; namespace Adapdev.Tests.Cache { /// <summary> /// Summary description for CacheManagerTest. /// </summary> /// [TestFixture] public class CacheUtilTest { [Test] public void Copy() { ICache source = new MutableInMemoryCache(); ICache target = new FileCache(); for(int i = 0; i < 100; i++) { source.Add(i, new SuppliersEntity()); } CacheUtil.Copy(source, target); Assert.AreEqual(100, source.Count); Assert.AreEqual(100, target.Count, "Cache items were not copied over."); } } } --- NEW FILE: Adapdev.Cache.Tests.csproj --- <VisualStudioProject> <CSHARP ProjectType = "Local" ProductVersion = "7.10.3077" SchemaVersion = "2.0" ProjectGuid = "{D2D00D68-57F1-4CEA-B9E6-4E7FD7CE4E43}" > <Build> <Settings ApplicationIcon = "" AssemblyKeyContainerName = "" AssemblyName = "Adapdev.Cache.Tests" AssemblyOriginatorKeyFile = "" DefaultClientScript = "JScript" DefaultHTMLPageLayout = "Grid" DefaultTargetSchema = "IE50" DelaySign = "false" OutputType = "Library" PreBuildEvent = "" PostBuildEvent = "" RootNamespace = "Adapdev.Cache.Tests" 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 = "nunit.framework" AssemblyName = "nunit.framework" HintPath = "..\..\lib\nunit.framework.dll" /> <Reference Name = "Adapdev.Cache" Project = "{84F894AC-EFD7-4342-B2A5-CF3EF80E0B1C}" Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" /> <Reference Name = "log4net" AssemblyName = "log4net" HintPath = "..\..\lib\log4net.dll" /> <Reference Name = "Adapdev" Project = "{CC30A321-2569-4B1F-8E1A-781B5509B56D}" Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" /> </References> </Build> <Files> <Include> <File RelPath = "AbstractICacheTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "AdapdevAssemblyInfo.cs" Link = "..\AdapdevAssemblyInfo.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "CacheManagerTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "CacheStatsTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "CacheUtilTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "FileCacheTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "ImmutableInMemoryCache.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "MutableInMemoryCacheTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Scavengers\AbsoluteExpirationScavengerTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Scavengers\BaseScavengerTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Scavengers\GreaterThanOrdinalScavengerTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Scavengers\SlidingExpirationScavengerTest.cs" SubType = "Code" BuildAction = "Compile" /> </Include> </Files> </CSHARP> </VisualStudioProject> --- NEW FILE: ImmutableInMemoryCache.cs --- using System; using NUnit.Framework; using Adapdev.Cache; using Adapdev.Mock; namespace Adapdev.Tests.Cache { /// <summary> /// Summary description for MutableInMemoryCache. /// </summary> /// [TestFixture] public class ImmutableInMemoryCacheTest : AbstractICacheTest { public override ICache GetCache() { return new ImmutableInMemoryCache(); } [Test] public void Immutable() { SuppliersEntity e1 = new SuppliersEntity(); e1.SupplierID = 12; cache.Add(e1.SupplierID, e1); SuppliersEntity e2 = cache.Get(typeof(SuppliersEntity), 12) as SuppliersEntity; e2.SupplierID = 13; Assert.IsTrue(cache.Contains(e1.GetType(), 12), "Cache key should not change."); SuppliersEntity e3 = cache.Get(typeof(SuppliersEntity), 12) as SuppliersEntity; Assert.IsFalse(13 == e3.SupplierID, "Object in cache should NOT have been updated."); } } } |
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.Cache/Scavengers In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv19977/src/Adapdev.Cache/Scavengers Added Files: AbsoluteExpirationScavenger.cs GreaterThanOrdinalScavenger.cs IScavenger.cs LIFONumberScavenger.cs SlidingExpirationScavenger.cs Log Message: Reposting to the repository after it got hosed --- NEW FILE: IScavenger.cs --- using System; namespace Adapdev.Cache.Scavengers { /// <summary> /// Summary description for IScavenger. /// </summary> public interface IScavenger { void Scavenge(ICache cache); } } --- NEW FILE: LIFONumberScavenger.cs --- using System; namespace Adapdev.Cache.Scavengers { /// <summary> /// Summary description for LIFOScavenger. /// </summary> public class LIFONumberScavenger : IScavenger { private int _num = 0; private LIFONumberScavenger(){} public LIFONumberScavenger(int numberOfItems) { this._num = numberOfItems; } #region IScavenger Members public void Scavenge(ICache cache) { CacheItem[] entries = cache.Entries; for(int i = entries.Length; i>= _num; i--) { CacheItem c = entries[i] as CacheItem; cache.Remove(c.ObjectType, c.Key); } } #endregion } } --- NEW FILE: SlidingExpirationScavenger.cs --- using System; namespace Adapdev.Cache.Scavengers { /// <summary> /// Summary description for DateScavenger. /// </summary> public class SlidingExpirationScavenger : IScavenger { private TimeSpan _timespan; private SlidingExpirationScavenger(){} public SlidingExpirationScavenger(TimeSpan timespan) { this._timespan = timespan; } #region IScavenger Members public void Scavenge(ICache cache) { DateTime span = DateTime.Now.Subtract(this._timespan); foreach(CacheItem item in cache.Entries) { if(item.Created < span) cache.Remove(item.ObjectType, item.Key); } } #endregion } } --- NEW FILE: AbsoluteExpirationScavenger.cs --- using System; namespace Adapdev.Cache.Scavengers { /// <summary> /// Summary description for DateScavenger. /// </summary> public class AbsoluteExpirationScavenger : IScavenger { private DateTime _date; private AbsoluteExpirationScavenger(){} public AbsoluteExpirationScavenger(DateTime dateTime) { this._date = dateTime; } #region IScavenger Members public void Scavenge(ICache cache) { foreach(CacheItem item in cache.Entries) { if(item.Created < this._date) cache.Remove(item.ObjectType, item.Key); } } #endregion } } --- NEW FILE: GreaterThanOrdinalScavenger.cs --- using System; namespace Adapdev.Cache.Scavengers { /// <summary> /// Summary description for GreaterThanOrdinalScavenger. /// </summary> public class GreaterThanOrdinalScavenger : IScavenger { private int _greaterThan = 0; private GreaterThanOrdinalScavenger(){} public GreaterThanOrdinalScavenger(int greaterThan) { _greaterThan = greaterThan; } #region IScavenger Members public void Scavenge(ICache cache) { foreach(CacheItem c in cache.Entries) { if(c.Ordinal > this._greaterThan) { cache.Remove(c.ObjectType, c.Key); } } } #endregion } } |
From: Sean M. <int...@us...> - 2005-11-16 05:33:35
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.CodeGen.Tests In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv19977/src/Adapdev.CodeGen.Tests Added Files: Adapdev.CodeGen.Tests.csproj Log Message: Reposting to the repository after it got hosed --- NEW FILE: Adapdev.CodeGen.Tests.csproj --- <VisualStudioProject> <CSHARP ProjectType = "Local" ProductVersion = "7.10.3077" SchemaVersion = "2.0" ProjectGuid = "{FF310091-86DF-4E18-8061-7694C0A2669B}" > <Build> <Settings ApplicationIcon = "" AssemblyKeyContainerName = "" AssemblyName = "Adapdev.CodeGen.Tests" AssemblyOriginatorKeyFile = "" DefaultClientScript = "JScript" DefaultHTMLPageLayout = "Grid" DefaultTargetSchema = "IE50" DelaySign = "false" OutputType = "Library" PreBuildEvent = "" PostBuildEvent = "" RootNamespace = "Adapdev.CodeGen.Tests" 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 = "nunit.framework" AssemblyName = "nunit.framework" HintPath = "..\..\lib\nunit.framework.dll" /> <Reference Name = "Adapdev.CodeGen" Project = "{2D8FC662-0244-49F1-8017-DFE73B191017}" 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" /> </Include> </Files> </CSHARP> </VisualStudioProject> |
From: Sean M. <int...@us...> - 2005-11-16 05:33:35
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.Data/Xml In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv19977/src/Adapdev.Data/Xml Added Files: ProviderConfig.cs ProviderConfig.xml ProviderConfig.xsd ProviderConfig.xsx ProviderInfo.cs ProviderInfo.xml ProviderInfo.xsd ProviderInfo.xsx Log Message: Reposting to the repository after it got hosed --- NEW FILE: ProviderConfig.cs --- using System; using System.Reflection; using System.Xml; using System.Data; using System.IO; using System.Text.RegularExpressions; namespace Adapdev.Data { /// <summary> /// DBConnectionManager manages the loading of the ADAPDEV.XML file into the DBConnection* classes /// </summary> [System.ComponentModel.DesignerCategoryAttribute("code")] public class ProviderConfig : DataSet { private DbConnectionTypes _connectionTypes = null; public ProviderConfig() : this( FindConfigFile() ) { } public ProviderConfig( string config ) { _connectionTypes = LoadConfig ( config ); } // Provides Get Access the the COnnection Types Instance public DbConnectionTypes ConnectionTypes { get { return _connectionTypes; } } /// <summary> /// Loads a config file into a XMLDocument and populates a DBConnectionTypes collection of the /// database connection details found in the config file. /// </summary> /// <param name="config">The name (and path) of a config file containing <connection> elements</param> /// <returns>A Collection of Connection Types</returns> private DbConnectionTypes LoadConfig ( string config ) { try { this.ReadXml(config); DbConnectionTypes connectionTypes = new DbConnectionTypes(); DataRow connectionsRow = this.Tables["connections"].Rows[0]; // Read the available connections from the connections collection // -------------------------------------------------------------- foreach (DataRow connectionRow in connectionsRow.GetChildRows("connections_connection")) { DbConnectionType connectionType = new DbConnectionType(); connectionType.Name = connectionRow["name"].ToString(); connectionType.DbTypeName = connectionRow["type"].ToString(); connectionType.InternalProviderName = connectionRow["internalProvider"].ToString(); // Read the Settings for this connection type // -------------------------------------------------------------- foreach (DataRow settingsRow in connectionRow.GetChildRows("connection_settings")) { if (settingsRow.Table.Columns.Contains("file")) { connectionType.SupportsFile = GetSettingState(settingsRow["file"].ToString(),false); connectionType.PromptFile = GetSettingValue(settingsRow["file"].ToString()); } if (settingsRow.Table.Columns.Contains("server")) { connectionType.SupportsServer = GetSettingState(settingsRow["server"].ToString(),true); connectionType.PromptServer = GetSettingValue(settingsRow["server"].ToString()); } if (settingsRow.Table.Columns.Contains("name")) { connectionType.SupportsName = GetSettingState(settingsRow["name"].ToString(),true); connectionType.PromptName = GetSettingValue(settingsRow["name"].ToString()); } if (settingsRow.Table.Columns.Contains("userid")) { connectionType.SupportsUserID = GetSettingState(settingsRow["userid"].ToString(),true); connectionType.PromptUserID = GetSettingValue(settingsRow["userid"].ToString()); } if (settingsRow.Table.Columns.Contains("password")) { connectionType.SupportsPassword = GetSettingState(settingsRow["password"].ToString(),true); connectionType.PromptPassword = GetSettingValue(settingsRow["password"].ToString()); } if (settingsRow.Table.Columns.Contains("filter")) { connectionType.SupportsFilter = GetSettingState(settingsRow["filter"].ToString(),false); connectionType.PromptFilter = GetSettingValue(settingsRow["filter"].ToString()); } } // Read each of the Providers Details // -------------------------------------------------------------- foreach (DataRow providersRow in connectionRow.GetChildRows("connection_providers")) { foreach (DataRow providerRow in providersRow.GetChildRows("providers_provider")) { DbConnectionProvider connectionProvider = new DbConnectionProvider(); connectionProvider.Name = providerRow["name"].ToString(); connectionProvider.ProviderTypeName = providerRow["type"].ToString(); connectionProvider.Parent = connectionType; connectionProvider.Template = Regex.Replace(providerRow["provider_Text"].ToString(), @"[\r\t\n]", ""); if (providerRow.Table.Columns.Contains("allowEmptyParameters")) connectionProvider.AllowEmptyParameters = GetSettingState(providerRow["allowEmptyParameters"].ToString(), true); if (providerRow.Table.Columns.Contains("enabled")) connectionProvider.Enabled = GetSettingState(providerRow["enabled"].ToString(),true); if (providerRow.Table.Columns.Contains("fileMask")) connectionProvider.FileMask = providerRow["fileMask"].ToString(); connectionType.Providers.Add(connectionProvider); } } connectionTypes.Add(connectionType); } return connectionTypes; } catch (Exception ex) { throw new ApplicationException(String.Format("Could not reference the ProviderConfig.xml configuration file: {0}\n{1}", config, ex.Message)); } } /// <summary> /// Returns the State if defined for a property. If it is false, return false /// otherwise return true. /// </summary> /// <param name="setting"></param> /// <returns></returns> private bool GetSettingState(string setting, bool defaultFlag) { if (setting == null) return defaultFlag; if (setting.Equals(string.Empty)) return defaultFlag; try { return Convert.ToBoolean(setting); } catch { return true; } } /// <summary> /// Return the setting for a property. If the property was "false" return a empty string /// or if the property was "true" return a empty string, otherwise return the contents. /// </summary> /// <param name="setting"></param> /// <returns></returns> private string GetSettingValue(string setting) { if (setting == null) return string.Empty; if (setting.Equals(string.Empty)) return string.Empty; try { bool flag = Convert.ToBoolean(setting); return string.Empty; } catch { return setting.Trim(); } } /// <summary> /// Determine the location and allow overriding of the ConfigFile /// </summary> /// <returns></returns> public static string FindConfigFile () { string configFile = String.Empty; string possibleConfig = String.Empty; // Look in the current application folder for the file if (configFile == String.Empty) { possibleConfig = AppDomain.CurrentDomain.BaseDirectory + @"ProviderConfig.XML"; if (System.IO.File.Exists(possibleConfig)) { configFile = possibleConfig; } } // If not found there, then override with a hardcoded default // TODO: Allow this to be overriden with the commandline if (configFile == String.Empty) { possibleConfig = @"..\..\..\..\..\Adapdev\src\Adapdev.Data\Xml\ProviderConfig.xml"; if (System.IO.File.Exists(possibleConfig)) { configFile = possibleConfig; } } if (configFile == String.Empty) { throw new ApplicationException(String.Format("Could not find the ProviderConfig.xml configuration file.\n It should exist in {0}", AppDomain.CurrentDomain.BaseDirectory)); } return configFile; } } } --- NEW FILE: ProviderInfo.xsd --- <?xml version="1.0"?> <xs:schema id="ProvidersInfo" targetNamespace="http://tempuri.org/ProviderInfo.xsd" xmlns:mstns="http://tempuri.org/ProviderInfo.xsd" xmlns="http://tempuri.org/ProviderInfo.xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" attributeFormDefault="qualified" elementFormDefault="qualified"> <xs:element name="ProvidersInfo" msdata:IsDataSet="true" msdata:EnforceConstraints="False"> <xs:complexType> <xs:choice maxOccurs="unbounded"> <xs:element name="ProviderInfo"> <xs:complexType> <xs:sequence> <xs:element name="Type" minOccurs="0" maxOccurs="unbounded"> <xs:complexType> <xs:sequence> <xs:element name="Id" type="xs:string" minOccurs="0" /> <xs:element name="Name" type="xs:string" minOccurs="0" /> <xs:element name="Object" type="xs:string" minOccurs="0" /> <xs:element name="Prefix" type="xs:string" minOccurs="0" /> <xs:element name="Postfix" type="xs:string" minOccurs="0" /> <xs:element name="Default" type="xs:string" minOccurs="0" /> <xs:element name="TestDefault" type="xs:string" minOccurs="0" /> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> <xs:attribute name="Name" form="unqualified" type="xs:string" /> </xs:complexType> </xs:element> </xs:choice> </xs:complexType> </xs:element> </xs:schema> --- NEW FILE: ProviderConfig.xml --- <?xml version="1.0" encoding="utf-8"?> <adapdev xmlns="http://tempuri.org/ProviderConfig.xsd"> <connections> <!-- You MUST specify a OLEDB connecion type as a minimum for a provider and specifiy it in the internalProvider attribute. Defining a connection string, use the following field replacement tokens: {0} Server Name or file location {1} Data Source or Initial Catalog Name {2} User Name or UserID to connect as {3} Password Available Settings are: <server file="true">Prompt</server> <name>Prompt<name> <userid>Prompt</userid> <password>Prompt</password> Note: When specifying a Driver={name} you must specify using {{ eg: Driver={{SQL Server}} --> <connection name="SQL Server" type="SQLSERVER" internalProvider="OLEDB"> <settings file="false" server="true" name="true" userid="true" password="true"/> <providers> <provider name="Sql Connect" type="SQLSERVER" allowEmptyParameters="true"> Data Source={0}; Initial Catalog={1}; User ID={2}; Password={3}; Trusted_Connection=false; </provider> <provider name="OLEDB" type="OLEDB"> Provider=sqloledb;Data Source={0}; Initial Catalog={1}; User ID={2}; Password={3}; </provider> <provider name="ODBC" type="ODBC" enabled="false"> Driver={{SQL Server}};Server={0}; Database={1}; Uid={2}; Pwd={3}; </provider> </providers> </connection> <connection name="SQL Server - Trusted" type="SQLSERVER" internalProvider="OLEDB"> <settings file="false" server="true" name="true" userid="false" password="false"/> <providers> <provider name="Sql Connect" type="SQLSERVER"> Data Source={0}; Initial Catalog={1}; Integrated Security=SSPI; </provider> <provider name="OLEDB" type="OLEDB"> Provider=sqloledb;Data Source={0}; Initial Catalog={1}; Integrated Security=SSPI </provider> <provider name="ODBC" type="ODBC" enabled="false"> Driver={{SQL Server}};Server={0}; Database={1}; Trusted_Connection=yes; </provider> </providers> </connection> <connection name="Microsoft Access" type="ACCESS" internalProvider="OLEDB"> <settings file="true" server="false" name="false" userid="true" password="true"/> <providers> <provider name="ODBC" type="ODBC" enabled="false"> Driver={{Microsoft Access Driver (*.mdb)}}; Dbq={0}; Uid={2}; Pwd={3}; </provider> <provider name="OLEDB" type="OLEDB" fileMask="Access Database (*.mdb)|*.mdb"> Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0}; User ID={2}; Password={3}; </provider> <provider name="OLEDB (DNS)" type="OLEDB" fileMask="File Data Sources (*.dsn)|*.dsn"> DSN={0};Uid={2};Pwd={3}; </provider> </providers> </connection> <connection name="Oracle" type="ORACLE" internalProvider="OLEDB (Microsoft)"> <settings file="false" server="true" name="false" userid="true" password="true" filter="Schema"/> <providers> <provider name="Oracle Connect" type="ORACLE" enabled="true"> Data Source={0}; User ID={2}; Password={3}; Integrated Security=no; </provider> <provider name="OLEDB (Microsoft)" type="OLEDB" enabled="true"> Provider=msdaora; Data Source={0}; Database={1}; User ID={2}; Password={3}; </provider> <provider name="OLEDB (Oracle)" type="OLEDB" enabled="false"> Provider=OraOLEDB; Data Source={0}; User ID={2}; Password={3}; </provider> <provider name="ODBC" type="ODBC" enabled="false"> Driver={{Microsoft ODBC for Oracle}}; Server={0}; Uid={2}; Pwd={3} </provider> </providers> </connection> <connection name="Oracle - Trusted" type="ORACLE" internalProvider="OLEDB (Oracle)"> <settings file="false" server="true" name="Schema" userid="true" password="true"/> <providers> <provider name="Oracle Connect" type="ORACLE" enabled="false"> Data Source={0}; Integrated Security=yes; </provider> <provider name="OLEDB (Oracle)" type="OLEDB" enabled="false"> Provider=OraOLEDB; Data Source={0}; OSAuthent=1; </provider> </providers> </connection> <connection name="MySql" type="MYSQL" internalProvider="MySql Native"> <settings file="false" server="true" name="true" userid="true" password="true"/> <providers> <provider name="MySql Native" type="MYSQL" enabled="true"> Data Source={0};Database={1};User ID={2};Password={3}; </provider> <provider name="ODBC" type="ODBC" enabled="false"> DRIVER={{MySQL ODBC 3.51 Driver}};SERVER={0};DATABASE={1};USER={2};PASSWORD={3}; </provider> </providers> </connection> </connections> </adapdev> --- NEW FILE: ProviderConfig.xsx --- <?xml version="1.0" encoding="utf-8"?> <!--This file is auto-generated by the XML Schema Designer. It holds layout information for components on the designer surface.--> <XSDDesignerLayout /> --- NEW FILE: ProviderConfig.xsd --- <?xml version="1.0"?> <xs:schema id="adapdev" targetNamespace="http://tempuri.org/ProviderConfig.xsd" xmlns:mstns="http://tempuri.org/ProviderConfig.xsd" xmlns="http://tempuri.org/ProviderConfig.xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" attributeFormDefault="qualified" elementFormDefault="qualified"> <xs:element name="adapdev" msdata:IsDataSet="true" msdata:Locale="en-NZ" msdata:EnforceConstraints="False"> <xs:complexType> <xs:choice maxOccurs="unbounded"> <xs:element name="connections"> <xs:complexType> <xs:sequence> <xs:element name="connection" minOccurs="0" maxOccurs="unbounded"> <xs:complexType> <xs:sequence> <xs:element name="settings" minOccurs="0" maxOccurs="unbounded"> <xs:complexType> <xs:attribute name="file" form="unqualified" type="xs:string" /> <xs:attribute name="server" form="unqualified" type="xs:string" /> <xs:attribute name="name" form="unqualified" type="xs:string" /> <xs:attribute name="userid" form="unqualified" type="xs:string" /> <xs:attribute name="password" form="unqualified" type="xs:string" /> <xs:attribute name="filter" form="unqualified" type="xs:string" /> </xs:complexType> </xs:element> <xs:element name="providers" minOccurs="0" maxOccurs="unbounded"> <xs:complexType> <xs:sequence> <xs:element name="provider" nillable="true" minOccurs="0" maxOccurs="unbounded"> <xs:complexType> <xs:simpleContent msdata:ColumnName="provider_Text" msdata:Ordinal="3"> <xs:extension base="xs:string"> <xs:attribute name="name" form="unqualified" type="xs:string" /> <xs:attribute name="type" form="unqualified" type="xs:string" /> <xs:attribute name="allowEmptyParameters" form="unqualified" type="xs:string" /> <xs:attribute name="enabled" form="unqualified" type="xs:string" /> <xs:attribute name="fileMask" form="unqualified" type="xs:string" /> </xs:extension> </xs:simpleContent> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> <xs:attribute name="name" form="unqualified" type="xs:string" /> <xs:attribute name="type" form="unqualified" type="xs:string" /> <xs:attribute name="internalProvider" form="unqualified" type="xs:string" /> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:choice> </xs:complexType> </xs:element> </xs:schema> --- NEW FILE: ProviderInfo.cs --- (This appears to be a binary file; contents omitted.) --- NEW FILE: ProviderInfo.xml --- <?xml version="1.0" encoding="utf-8" ?> <ProvidersInfo xmlns="http://tempuri.org/ProviderInfo.xsd"> <ProviderInfo Name="oledb"> <Type> <Id>20</Id> <Name>BigInt</Name> <Object>Int64</Object> <Prefix></Prefix> <Postfix></Postfix> <Default>0</Default> <TestDefault>2</TestDefault> </Type> <Type> <Id>128</Id> <Name>Binary</Name> <Object>Byte[]</Object> <Prefix></Prefix> <Postfix></Postfix> <Default>null</Default> [...1486 lines suppressed...] <Type> <Id>252</Id> <Name>longtext</Name> <Object>Byte[]</Object> <Prefix>'</Prefix> <Postfix>'</Postfix> <Default></Default> <TestDefault></TestDefault> </Type>--> <Type> <Id>254</Id> <Name>uint</Name> <Object>Int32</Object> <Prefix></Prefix> <Postfix></Postfix> <Default>0</Default> <TestDefault>1</TestDefault> </Type> </ProviderInfo> </ProvidersInfo> --- NEW FILE: ProviderInfo.xsx --- <?xml version="1.0" encoding="utf-8"?> <!--This file is auto-generated by the XML Schema Designer. It holds layout information for components on the designer surface.--> <XSDDesignerLayout /> |
From: Sean M. <int...@us...> - 2005-11-16 03:21:25
|
Update of /cvsroot/adapdev/Adapdev/lib In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv32459/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 03:07:47
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/Runtime/Exception In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv30063/src/Adapdev.NVelocity/Runtime/Exception Removed Files: NodeException.cs ReferenceException.cs Log Message: --- NodeException.cs DELETED --- --- ReferenceException.cs DELETED --- |
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv30063/src/Adapdev.NVelocity Removed Files: Adapdev.NVelocity.csproj Adapdev.NVelocity.csproj.user SupportClass.cs Template.cs VelocityContext.cs readme.txt Log Message: --- Template.cs DELETED --- --- VelocityContext.cs DELETED --- --- readme.txt DELETED --- --- Adapdev.NVelocity.csproj DELETED --- --- SupportClass.cs DELETED --- --- Adapdev.NVelocity.csproj.user DELETED --- |
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/App/Events In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv30063/src/Adapdev.NVelocity/App/Events Removed Files: EventCartridge.cs EventHandler.cs MethodExceptionEventHandler.cs NullSetEventHandler.cs ReferenceInsertionEventHandler.cs Log Message: --- EventCartridge.cs DELETED --- --- EventHandler.cs DELETED --- --- MethodExceptionEventHandler.cs DELETED --- --- NullSetEventHandler.cs DELETED --- --- ReferenceInsertionEventHandler.cs DELETED --- |
From: Sean M. <int...@us...> - 2005-11-16 03:07:47
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/App/Tools In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv30063/src/Adapdev.NVelocity/App/Tools Removed Files: VelocityFormatter.cs Log Message: --- VelocityFormatter.cs DELETED --- |
From: Sean M. <int...@us...> - 2005-11-16 03:07:47
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/Runtime/Parser In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv30063/src/Adapdev.NVelocity/Runtime/Parser Removed Files: CharStream.cs JJTParserState.cs ParseException.cs Parser.cs ParserConstants.cs ParserTokenManager.cs ParserTreeConstants.cs Token.cs TokenMgrError.cs VelocityCharStream.cs Log Message: --- ParserConstants.cs DELETED --- --- ParseException.cs DELETED --- --- JJTParserState.cs DELETED --- --- ParserTokenManager.cs DELETED --- --- Parser.cs DELETED --- --- TokenMgrError.cs DELETED --- --- ParserTreeConstants.cs DELETED --- --- CharStream.cs DELETED --- --- VelocityCharStream.cs DELETED --- --- Token.cs DELETED --- |
From: Sean M. <int...@us...> - 2005-11-16 03:07:44
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/Dvsl/Resource In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv30063/src/Adapdev.NVelocity/Dvsl/Resource Removed Files: defaultroot.dvsl Log Message: --- defaultroot.dvsl DELETED --- |