adapdev-commits Mailing List for Adapdev.NET (Page 11)
Status: Beta
Brought to you by:
intesar66
You can subscribe to this list here.
2005 |
Jan
|
Feb
|
Mar
(26) |
Apr
(59) |
May
(37) |
Jun
(53) |
Jul
(13) |
Aug
(7) |
Sep
(5) |
Oct
(74) |
Nov
(404) |
Dec
(14) |
---|---|---|---|---|---|---|---|---|---|---|---|---|
2006 |
Jan
(10) |
Feb
(26) |
Mar
(64) |
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/App/Events In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.NVelocity/App/Events Added Files: EventCartridge.cs EventHandler.cs MethodExceptionEventHandler.cs NullSetEventHandler.cs ReferenceInsertionEventHandler.cs Log Message: --- NEW FILE: EventCartridge.cs --- namespace NVelocity.App.Events { /* * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ using System; using NVelocity.Context; /// <summary> 'Package' of event handlers... /// * /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <author> <a href="mailto:j_a...@ya...">Jose Alberto Fernandez</a> /// </author> /// <version> $Id: EventCartridge.cs,v 1.5 2005/11/16 07:01:48 intesar66 Exp $ /// /// </version> public class EventCartridge : ReferenceInsertionEventHandler, NullSetEventHandler, MethodExceptionEventHandler { private ReferenceInsertionEventHandler rieh = null; private NullSetEventHandler nseh = null; private MethodExceptionEventHandler meeh = null; /// <summary> Adds an event handler(s) to the Cartridge. This method /// will find all possible event handler interfaces supported /// by the passed in object. /// * /// </summary> /// <param name="ev">object impementing a valid EventHandler-derived interface /// </param> /// <returns>true if a supported interface, false otherwise or if null /// /// </returns> public virtual bool addEventHandler(EventHandler ev) { if (ev == null) { return false; } bool found = false; if (ev is ReferenceInsertionEventHandler) { rieh = (ReferenceInsertionEventHandler) ev; found = true; } if (ev is NullSetEventHandler) { nseh = (NullSetEventHandler) ev; found = true; } if (ev is MethodExceptionEventHandler) { meeh = (MethodExceptionEventHandler) ev; found = true; } return found; } /// <summary> Removes an event handler(s) from the Cartridge. This method /// will find all possible event handler interfaces supported /// by the passed in object and remove them. /// * /// </summary> /// <param name="ev">object impementing a valid EventHandler-derived interface /// </param> /// <returns>true if a supported interface, false otherwise or if null /// /// </returns> public virtual bool removeEventHandler(EventHandler ev) { if (ev == null) { return false; } bool found = false; if (ev == rieh) { rieh = null; found = true; } if (ev == nseh) { nseh = null; found = true; } if (ev == meeh) { meeh = null; found = true; } return found; } /// <summary> Implementation of ReferenceInsertionEventHandler method /// <code>referenceInsert()</code>. /// * /// Called during Velocity merge before a reference value will /// be inserted into the output stream. /// * /// </summary> /// <param name="reference">reference from template about to be inserted /// </param> /// <param name="value"> value about to be inserted (after toString() ) /// </param> /// <returns>Object on which toString() should be called for output. /// /// </returns> public virtual Object referenceInsert(String reference, Object value_Renamed) { if (rieh == null) { return value_Renamed; } return rieh.referenceInsert(reference, value_Renamed); } /// <summary> Implementation of NullSetEventHandler method /// <code>shouldLogOnNullSet()</code>. /// * /// Called during Velocity merge to determine if when /// a #set() results in a null assignment, a warning /// is logged. /// * /// </summary> /// <param name="reference">reference from template about to be inserted /// </param> /// <returns>true if to be logged, false otherwise /// /// </returns> public virtual bool shouldLogOnNullSet(String lhs, String rhs) { if (nseh == null) { return true; } return nseh.shouldLogOnNullSet(lhs, rhs); } /// <summary> Implementation of MethodExceptionEventHandler method /// <code>methodException()</code>. /// * /// Called during Velocity merge if a reference is null /// * /// </summary> /// <param name="claz"> Class that is causing the exception /// </param> /// <param name="method">method called that causes the exception /// </param> /// <param name="e">Exception thrown by the method /// </param> /// <returns>Object to return as method result /// @throws exception to be wrapped and propogated to app /// /// </returns> public virtual Object methodException(Type claz, String method, Exception e) { /* * if we don't have a handler, just throw what we were handed */ if (meeh == null) { throw e; } /* * otherwise, call it.. */ return meeh.methodException(claz, method, e); } /// <summary> Attached the EventCartridge to the context /// * /// Final because not something one should mess with lightly :) /// * /// </summary> /// <param name="context">context to attach to /// </param> /// <returns>true if successful, false otherwise /// /// </returns> public bool attachToContext(IContext context) { if (context is InternalEventContext) { InternalEventContext iec = (InternalEventContext) context; iec.AttachEventCartridge(this); return true; } else { return false; } } } } --- NEW FILE: EventHandler.cs --- namespace NVelocity.App.Events { /* * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /// <summary> Base interface for all event handlers /// * /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version> $Id: EventHandler.cs,v 1.5 2005/11/16 07:01:48 intesar66 Exp $ /// /// </version> public interface EventHandler { } } --- NEW FILE: MethodExceptionEventHandler.cs --- namespace NVelocity.App.Events { using System; /* * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /// <summary> Called when a method throws an exception. This gives the /// application a chance to deal with it and either /// return something nice, or throw. /// * /// Please return what you want rendered into the output stream. /// * /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version> $Id: MethodExceptionEventHandler.cs,v 1.5 2005/11/16 07:01:48 intesar66 Exp $ /// /// </version> public interface MethodExceptionEventHandler : EventHandler { Object methodException(Type claz, String method, Exception e); } } --- NEW FILE: NullSetEventHandler.cs --- namespace NVelocity.App.Events { using System; /* * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /// <summary> Event handler : lets an app approve / veto /// writing a log message when RHS of #set() is null. /// * /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version> $Id: NullSetEventHandler.cs,v 1.5 2005/11/16 07:01:48 intesar66 Exp $ /// /// </version> public interface NullSetEventHandler : EventHandler { /// <summary> Called when the RHS of a #set() is null, which will result /// in a null LHS. /// * /// </summary> /// <param name="lhs"> reference literal of left-hand-side of set statement /// </param> /// <param name="rhs"> reference literal of right-hand-side of set statement /// </param> /// <returns>true if log message should be written, false otherwise /// /// </returns> bool shouldLogOnNullSet(String lhs, String rhs); } } --- NEW FILE: ReferenceInsertionEventHandler.cs --- namespace NVelocity.App.Events { using System; /* * The Apache Software License, Version 1.1 * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Velocity", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact ap...@ap.... * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /// <summary> Reference 'Stream insertion' event handler. Called with object /// that will be inserted into stream via value.toString(). /// * /// Please return an Object that will toString() nicely :) /// * /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version> $Id: ReferenceInsertionEventHandler.cs,v 1.5 2005/11/16 07:01:48 intesar66 Exp $ /// /// </version> public interface ReferenceInsertionEventHandler : EventHandler { /// <summary> A call-back which is executed during Velocity merge before a /// reference value is inserted into the output stream. /// * /// </summary> /// <param name="reference">Reference from template about to be inserted. /// </param> /// <param name="value">Value about to be inserted (after its /// <code>toString()</code> method is called). /// </param> /// <returns>Object on which <code>toString()</code> should be /// called for output. /// /// </returns> Object referenceInsert(String reference, Object value_Renamed); } } |
From: Sean M. <int...@us...> - 2005-11-16 07:01:57
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/Dvsl/Directive In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.NVelocity/Dvsl/Directive Added Files: MatchDirective.cs NameDirective.cs Log Message: --- NEW FILE: NameDirective.cs --- namespace NVelocity.Dvsl.Directive { using System; using System.IO; using NVelocity.Context; using NVelocity.Runtime.Directive; using NVelocity.Runtime.Parser.Node; /// <summary> /// To implement the functionality of <xsl:template name=> /// </summary> /// <author> <a href="mailto:ge...@ap...">Geir Magnusson Jr.</a></author> public class NameDirective : Directive { public override String Name { get { return "name"; } set { throw new NotSupportedException(); } } public override Int32 Type { get { return DirectiveConstants_Fields.BLOCK; } } public override Boolean render(InternalContextAdapter context, TextWriter writer, INode node) { return true; } } } --- NEW FILE: MatchDirective.cs --- namespace NVelocity.Dvsl.Directive { using System; using System.IO; using NVelocity.Context; using NVelocity.Runtime.Directive; using NVelocity.Runtime.Parser; using NVelocity.Runtime.Parser.Node; /// <summary> /// Velocity Directive to handle template registration of /// match declarations (like the XSLT match=) /// </summary> /// <author><a href="mailto:ge...@ap...">Geir Magnusson Jr.</a></author> public class MatchDirective : Directive { public override String Name { get { return "match"; } set { throw new NotSupportedException(); } } public override int Type { get { return DirectiveConstants_Fields.BLOCK; } } public override bool render(InternalContextAdapter context, TextWriter writer, INode node) { /* * what is our arg? */ INode n = node.jjtGetChild(0); if (n.Type == ParserTreeConstants.JJTSTRINGLITERAL) { try { String element = (String) node.jjtGetChild(0).value_Renamed(context); TemplateHandler th = (TemplateHandler) rsvc.getApplicationAttribute("NVelocity.Dvsl.TemplateHandler"); th.RegisterMatch(element, (SimpleNode) node.jjtGetChild(node.jjtGetNumChildren() - 1)); } catch (Exception ee) { } } return true; } } } |
From: Sean M. <int...@us...> - 2005-11-16 07:01:57
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.Data.Tests In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.Data.Tests Added Files: Adapdev.Data.Tests.csproj CategoriesDAOTest.cs ProviderInfoManagerTest.cs SchemaBuilderTest.cs Log Message: --- 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.IsTrue(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.IsTrue(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.IsTrue(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."); } } } |
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.Data/Schema In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/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: --- 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 --- using System.Xml.Serialization; 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; } } /// <summary>... [truncated message content] |
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.Cache In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.Cache Added Files: AbstractCache.cs Adapdev.Cache.csproj CacheItem.cs CacheItemCollection.cs CacheItemDictionary.cs CacheItemEnumerator.cs CacheManager.cs CacheStats.cs CacheType.cs CacheUtil.cs FileCache.cs ICache.cs ICacheItem.cs ICacheStats.cs ImmutableInMemoryCache.cs MutableInMemoryCache.cs SerializedCacheItem.cs SqlServerCache.cs TypeKey.cs Log Message: --- NEW FILE: TypeKey.cs --- using System; namespace Adapdev.Cache { /// <summary> /// Summary description for TypeKey. /// </summary> internal class TypeKey { public static string Build(Type t, string key) { return t.FullName + Separator + key; } public static string GetTypeName(string typekey) { return typekey.Substring(0, typekey.IndexOf(Separator)); } public static Type GetType(string typekey) { return Type.GetType(GetTypeName(typekey)); } public static string GetKey(string typekey) { return typekey.Substring(typekey.IndexOf(Separator), typekey.Length); } public static string Separator { get{return "---";} } } } --- NEW FILE: AbstractCache.cs --- using System; using Adapdev; namespace Adapdev.Cache { using System.Collections; using System.Timers; using Adapdev.Cache.Scavengers; /// <summary> /// Summary description for AbstractCache. /// </summary> public abstract class AbstractCache : LongLivingMarshalByRefObject, ICache { protected ArrayList _timers = new ArrayList(); protected ArrayList _scavengers = new ArrayList(); #region ICache Members public void Add(int key, object o) { this.Add(key.ToString(), o); } public void Remove(Type t, int key) { this.Remove(t, key.ToString()); } public object Get(Type t, int key) { return this.Get(t, key.ToString()); } public CacheItem GetCacheItem(Type t, int key) { return this.GetCacheItem(t, key.ToString()); } public bool Contains(Type t, int key) { return this.Contains(t, key.ToString()); } public void Scavenge(Adapdev.Cache.Scavengers.IScavenger scavenger) { scavenger.Scavenge(this); } public void Copy(ICache cache) { CacheUtil.Copy(cache, this); } public abstract void Add(string key, object o); public abstract void Clear(); public abstract bool Contains(Type t, string key); public abstract int Count{get;} public abstract CacheItem[] Entries{get;} public abstract object Get(Type t, string key); public abstract CacheItem GetCacheItem(Type t, string key); public abstract void Populate(); public abstract void Remove(Type t, string key); #endregion } } --- NEW FILE: CacheItem.cs --- using System; using Adapdev; namespace Adapdev.Cache { /// <summary> /// Summary description for CacheItem. /// </summary> /// [Serializable] public class CacheItem : ICacheItem { protected object _object = null; protected string _key = String.Empty; protected int _ordinal = 0; protected DateTime _created; protected Type _objectType = null; public CacheItem(string key, object o) { this._key = key; this._object = o; this._created = DateTime.Now; this._objectType = o.GetType(); } public DateTime Created { get{return this._created;} } public Type ObjectType { get{return this._objectType;} } public virtual object Object { get{return this._object;} } public string Key { get{return this._key;} } public string TypeKey { get{return Adapdev.Cache.TypeKey.Build(this.ObjectType, this.Key);} } public int Ordinal { get{return this._ordinal;} set{this._ordinal = value;} } public override string ToString() { return Adapdev.Text.StringUtil.ToString(this); } } } --- NEW FILE: CacheManager.cs --- using System; namespace Adapdev.Cache { /// <summary> /// Summary description for CacheManager. /// </summary> public class CacheManager { private static ICache _cache = null; static CacheManager() { } public static ICache Cache { get { if(_cache == null) _cache = new ImmutableInMemoryCache(); return _cache; } set { if(_cache != null) { _cache.Clear(); } _cache = value; } } public static void SetCache(CacheType cacheType, bool copyExisting) { ICache cache = null; switch(cacheType) { case CacheType.File: cache = new FileCache(); if(copyExisting) cache.Copy(Cache); Cache = cache; break; case CacheType.ImmutableInMemory: cache = new ImmutableInMemoryCache(); if(copyExisting) cache.Copy(Cache); Cache = cache; break; case CacheType.MutableInMemory: cache = new MutableInMemoryCache(); if(copyExisting) cache.Copy(Cache); Cache = cache; break; default: break; } } public static void SetCache(CacheType cacheType) { SetCache(cacheType, true); } } } --- NEW FILE: ICacheStats.cs --- namespace Adapdev.Cache { /// <summary> /// Summary description for ICacheStats. /// </summary> public interface ICacheStats { int HitRate { get; } int MissRate { get; } long InsertTime { get; } long RetrieveTime { get; } } } --- NEW FILE: MutableInMemoryCache.cs --- using System; using System.Collections; using Adapdev.Serialization; namespace Adapdev.Cache { /// <summary> /// Summary description for ReadOnlyInMemoryCache. /// </summary> public class MutableInMemoryCache : AbstractCache { private CacheItemDictionary _hashtable = new CacheItemDictionary(); private int _ordinal = 0; public MutableInMemoryCache() { } #region ICache Members public override void Add(string key, object o) { CacheItem c = new CacheItem(key, o); c.Ordinal = ++this._ordinal; this._hashtable[TypeKey.Build(o.GetType(), key)] = c; } public override void Remove(Type t, string key) { this._hashtable.Remove(TypeKey.Build(t, key)); } public override object Get(Type t, string key) { return (this._hashtable[TypeKey.Build(t, key)] as CacheItem).Object; } public override CacheItem GetCacheItem(Type t, string key) { return this._hashtable[TypeKey.Build(t, key)] as CacheItem; } public override void Clear() { this._hashtable.Clear(); } public override bool Contains(Type t, string key) { return this._hashtable.Contains(TypeKey.Build(t, key)); } public override int Count { get { return this._hashtable.Count; } } public override CacheItem[] Entries { get { CacheItem[] items = new CacheItem[this._hashtable.Count]; this._hashtable.Values.CopyTo(items, 0); return items; } } public override void Populate() { } #endregion } } --- NEW FILE: CacheStats.cs --- using System; using Adapdev.Diagnostics; namespace Adapdev.Cache { using System.Text; using Adapdev.Cache.Scavengers; /// <summary> /// Summary description for CacheStats. /// </summary> public class CacheStats : ICache { private ICache _cache = null; private double _retrieveTime; private double _retrieveTimeAvg; private int _retrieved; private double _insertTimeAvg; private double _insertTime; private double _inserted; private int _hitCount; private int _missCount; private readonly IPerfTimer timer = PerfTimerFactory.GetPerfTimer(PerfTimerType.HIRESSECONDS); public CacheStats(ICache cache) { this._cache = cache; } #region ICache Members public void Add(string key, object o) { timer.Start(); this._cache.Add(key, o); timer.Stop(); this._insertTime = timer.Duration; this._insertTimeAvg += timer.Duration; this._inserted++; } public void Add(int key, object o) { this.Add(key.ToString(), o); } public void Remove(Type t, int key) { this.Remove(t, key.ToString()); } public void Remove(Type t, string key) { this._cache.Remove(t, key); } public object Get(Type t, int key) { return this.Get(t, key.ToString()); } public object Get(Type t, string key) { timer.Start(); object o = this._cache.Get(t, key); timer.Stop(); this._retrieveTime = timer.Duration; this._retrieveTimeAvg += timer.Duration; this._retrieved++; if(o == null) this._missCount++; else this._hitCount++; return o; } public CacheItem GetCacheItem(Type t, string key) { return this._cache.GetCacheItem(t, key); } public CacheItem GetCacheItem(Type t, int key) { return this._cache.GetCacheItem(t, key); } public void Clear() { this._cache.Clear(); this._hitCount = 0; this._inserted = 0; this._insertTime = 0; this._insertTimeAvg = 0; this._missCount = 0; this._retrieved = 0; this._retrieveTime = 0; this._retrieveTimeAvg = 0; } public int Count { get { return this._cache.Count; } } public bool Contains(Type t, string key) { return this._cache.Contains(t, key); } public bool Contains(Type t, int key) { return this._cache.Contains(t, key); } public void Scavenge(Adapdev.Cache.Scavengers.IScavenger scavenger) { this._cache.Scavenge(scavenger); } public CacheItem[] Entries { get { return this._cache.Entries; } } public void Populate() { this._cache.Populate(); } public void Copy(ICache cache) { this._cache.Copy(cache); } #endregion public double RetrieveTime { get{return this._retrieveTime;} } public double InsertTime { get{return this._insertTime;} } public double AverageRetrieveTime { get{return this._retrieveTimeAvg / this._retrieved;} } public double AverageInsertTime { get{return this._insertTimeAvg / this._inserted;} } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.AppendFormat("Insert Time: {0}\r\n", this.InsertTime); sb.AppendFormat("Avg. Insert Time: {0}\r\n", this.AverageInsertTime); sb.AppendFormat("Retrieve Time: {0}\r\n", this.RetrieveTime); sb.AppendFormat("Avg. Retrieve Time: {0}\r\n", this.AverageRetrieveTime); sb.AppendFormat("Hit Count: {0}\r\n", this.HitCount); sb.AppendFormat("Miss Count: {0}\r\n", this.MissCount); return sb.ToString(); } public ICache Cache { get{return this._cache;} } public int HitCount { get{return this._hitCount;} } public int MissCount { get{return this._missCount;} } public void Scavenge(IScavenger scavenger, TimeSpan timespan) { this.Scavenge(scavenger, timespan); } } } --- NEW FILE: SqlServerCache.cs --- namespace Adapdev.Cache { /// <summary> /// Summary description for SqlServerCache. /// </summary> public class SqlServerCache : ICache { public SqlServerCache() { // // TODO: Add constructor logic here // } #region ICache Members public void Add(string id, object item) { // TODO: Add SqlServerCache.Add implementation } public void Remove(string id) { // TODO: Add SqlServerCache.Remove implementation } public object Get(string id) { // TODO: Add SqlServerCache.Get implementation return null; } public CacheMetaData GetMetaData(string id) { return null; } public CacheMetaDataDictionary GetMetaData() { return null; } public void Clear() { // TODO: Add SqlServerCache.Clear implementation } public int Count { get { // TODO: Add SqlServerCache.Count getter implementation return 0; } } public void SetScavenger(IScavenger scavenger) { // TODO: Add SqlServerCache.SetScavenger implementation } public bool Contains(string id) { return false; } #endregion } } --- NEW FILE: SerializedCacheItem.cs --- using System; using Adapdev.Serialization; namespace Adapdev.Cache { /// <summary> /// Summary description for SerializedCacheItem. /// </summary> /// [Serializable] public class SerializedCacheItem : CacheItem { public SerializedCacheItem(string key, object o) : base(key, o) { this._key = key; this._object = Serializer.SerializeToBinary(o); this._created = DateTime.Now; this._objectType = o.GetType(); } public override object Object { get { return Serializer.DeserializeFromBinary(this._objectType, this._object as byte[]); } } public byte[] BinaryObject { get{return this._object as byte[];} } } } --- NEW FILE: CacheType.cs --- using System; namespace Adapdev.Cache { /// <summary> /// Summary description for CacheType. /// </summary> public enum CacheType { File, ImmutableInMemory, MutableInMemory } } --- NEW FILE: CacheItemCollection.cs --- /****************************************** * Auto-generated by Codus * 4/20/2005 11:18:21 AM ******************************************/ using System; using System.Collections; namespace Adapdev.Cache { [Serializable()] public class CacheItemCollection : CollectionBase { public CacheItemCollection() { } public CacheItemCollection(IList value) { this.AddRange(value); } public CacheItemCollection(CacheItem[] value) { this.AddRange(value); } public CacheItem this[int index] { get { return ((CacheItem)(List[index])); } set { List[index] = value; } } public int Add(CacheItem value) { return List.Add(value); } public void AddRange(CacheItem[] value) { for (int i = 0; (i < value.Length); i = (i + 1)) { this.Add(value[i]); } } public void AddRange(IList value) { for (int i = 0; (i < value.Count); i = (i + 1)) { this.Add((CacheItem)value[i]); } } public bool Contains(CacheItem value) { return List.Contains(value); } public void CopyTo(CacheItem[] array, int index) { List.CopyTo(array, index); } public int IndexOf(CacheItem value) { return List.IndexOf(value); } public void Insert(int index, CacheItem value) { List.Insert(index, value); } public new CacheItemEnumerator GetEnumerator() { return new CacheItemEnumerator(this); } public void Remove(CacheItem value) { List.Remove(value); } } } --- NEW FILE: Adapdev.Cache.csproj --- <VisualStudioProject> <CSHARP ProjectType = "Local" ProductVersion = "7.10.3077" SchemaVersion = "2.0" ProjectGuid = "{84F894AC-EFD7-4342-B2A5-CF3EF80E0B1C}" > <Build> <Settings ApplicationIcon = "" AssemblyKeyContainerName = "" AssemblyName = "Adapdev.Cache" AssemblyOriginatorKeyFile = "" DefaultClientScript = "JScript" DefaultHTMLPageLayout = "Grid" DefaultTargetSchema = "IE50" DelaySign = "false" OutputType = "Library" PreBuildEvent = "" PostBuildEvent = "" RootNamespace = "Adapdev.Cache" RunPostBuildEvent = "OnBuildSuccess" StartupObject = "" > <Config Name = "Debug" AllowUnsafeBlocks = "false" BaseAddress = "285212672" CheckForOverflowUnderflow = "false" ConfigurationOverrideFile = "" DefineConstants = "DEBUG;TRACE" DocumentationFile = "" DebugSymbols = "true" FileAlignment = "4096" IncrementalBuild = "false" NoStdLib = "false" NoWarn = "" Optimize = "false" OutputPath = "bin\Debug\" RegisterForComInterop = "false" RemoveIntegerChecks = "false" TreatWarningsAsErrors = "false" WarningLevel = "4" /> <Config Name = "Release" AllowUnsafeBlocks = "false" BaseAddress = "285212672" CheckForOverflowUnderflow = "false" ConfigurationOverrideFile = "" DefineConstants = "TRACE" DocumentationFile = "" DebugSymbols = "false" FileAlignment = "4096" IncrementalBuild = "false" NoStdLib = "false" NoWarn = "" Optimize = "true" OutputPath = "bin\Release\" RegisterForComInterop = "false" RemoveIntegerChecks = "false" TreatWarningsAsErrors = "false" WarningLevel = "4" /> </Settings> <References> <Reference Name = "System" AssemblyName = "System" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.dll" /> <Reference Name = "System.Data" AssemblyName = "System.Data" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.Data.dll" /> <Reference Name = "System.XML" AssemblyName = "System.Xml" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.XML.dll" /> <Reference Name = "Adapdev" Project = "{CC30A321-2569-4B1F-8E1A-781B5509B56D}" Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" /> <Reference Name = "log4net" AssemblyName = "log4net" HintPath = "..\..\lib\log4net.dll" /> </References> </Build> <Files> <Include> <File RelPath = "AbstractCache.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "AdapdevAssemblyInfo.cs" Link = "..\AdapdevAssemblyInfo.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "CacheItem.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "CacheItemCollection.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "CacheItemDictionary.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "CacheItemEnumerator.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "CacheManager.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "CacheStats.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "CacheType.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "CacheUtil.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "FileCache.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "ICache.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "ICacheItem.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "ImmutableInMemoryCache.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "MutableInMemoryCache.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "SerializedCacheItem.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "TypeKey.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Scavengers\AbsoluteExpirationScavenger.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Scavengers\GreaterThanOrdinalScavenger.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Scavengers\IScavenger.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Scavengers\LIFONumberScavenger.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Scavengers\SlidingExpirationScavenger.cs" SubType = "Code" BuildAction = "Compile" /> </Include> </Files> </CSHARP> </VisualStudioProject> --- NEW FILE: CacheUtil.cs --- using System; namespace Adapdev.Cache { /// <summary> /// Summary description for CacheUtil. /// </summary> public class CacheUtil { private CacheUtil(){} public static void Copy(ICache source, ICache target) { foreach(CacheItem item in source.Entries) { target.Add(item.Key, item.Object); } } } } --- NEW FILE: CacheItemEnumerator.cs --- /****************************************** * Auto-generated by Codus * 4/20/2005 11:18:21 AM ******************************************/ using System; using System.Collections; namespace Adapdev.Cache { public class CacheItemEnumerator : IEnumerator { private IEnumerator baseEnumerator; private IEnumerable temp; public CacheItemEnumerator(CacheItemCollection mappings) { this.temp = ((IEnumerable)(mappings)); this.baseEnumerator = temp.GetEnumerator(); } public CacheItemEnumerator(CacheItemDictionary mappings) { this.temp = ((IEnumerable)(mappings)); this.baseEnumerator = temp.GetEnumerator(); } public CacheItem Current { get { return ((CacheItem)(baseEnumerator.Current)); } } object IEnumerator.Current { get { return baseEnumerator.Current; } } public bool MoveNext() { return baseEnumerator.MoveNext(); } bool IEnumerator.MoveNext() { return baseEnumerator.MoveNext(); } public void Reset() { baseEnumerator.Reset(); } void IEnumerator.Reset() { baseEnumerator.Reset(); } } } --- NEW FILE: FileCache.cs --- using System; using System.Collections; using System.IO; using Adapdev.Serialization; namespace Adapdev.Cache { /// <summary> /// Summary description for FileCache. /// </summary> public class FileCache : AbstractCache { private string _folderPath = String.Empty; private CacheItemDictionary _items = new CacheItemDictionary(); private static int _ordinal = 0; public FileCache() { this._folderPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "filecache"); if(!Directory.Exists(this._folderPath)) Directory.CreateDirectory(this._folderPath); FileCache._ordinal = this.Count; } public FileCache(string folderName) { this._folderPath = folderName; this._folderPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "filecache"); if(!Directory.Exists(this._folderPath)) Directory.CreateDirectory(this._folderPath); FileCache._ordinal = this.Count; } private string GetFileName(Type t, string key) { return TypeKey.Build(t, key) + ".cache"; } private string GetFullFileName(Type t, string key) { return Path.Combine(this._folderPath, this.GetFileName(t, key)); } private string GetFileNameWithoutExtension(string fileName) { return fileName.Substring(0, fileName.LastIndexOf(".")); } #region ICache Members public override void Add(string key, object o) { SerializedCacheItem c = new SerializedCacheItem(key, o); c.Ordinal = ++FileCache._ordinal; this._items[TypeKey.Build(o.GetType(), key)] = c; Serializer.SerializeToBinary(o, Path.Combine(this._folderPath, this.GetFileName(o.GetType(), key))); } public override void Remove(Type t, string key) { File.Delete(Path.Combine(this._folderPath, this.GetFileName(t, key))); this._items.Remove(TypeKey.Build(t, key)); } public override object Get(Type t, string key) { string typekey = TypeKey.Build(t, key); if(this._items.Contains(typekey)) { return (this._items[typekey] as SerializedCacheItem).Object; } else if(this.Contains(t, key)) { return Serializer.DeserializeFromBinary(t, this.GetFileName(t, key)); } else { return null; } } public override CacheItem GetCacheItem(Type t, string key) { return this._items[TypeKey.Build(t, key)] as SerializedCacheItem; } public override void Clear() { if(Directory.Exists(this._folderPath)) { Directory.Delete(this._folderPath, true); Directory.CreateDirectory(this._folderPath); this._items.Clear(); } } public override int Count { get { return Directory.GetFiles(this._folderPath).Length; } } public override bool Contains(Type t, string key) { return File.Exists(this.GetFullFileName(t, key)); } public override CacheItem[] Entries { get { CacheItem[] items = new CacheItem[this._items.Count]; this._items.Values.CopyTo(items, 0); return items; } } public override void Populate() { foreach(FileInfo f in new DirectoryInfo(this._folderPath).GetFiles()) { string fileName = this.GetFileNameWithoutExtension(f.Name); SerializedCacheItem c = new SerializedCacheItem(TypeKey.GetKey(fileName), Serializer.DeserializeFromBinary(TypeKey.GetType(fileName), f.FullName)); c.Ordinal = FileCache._ordinal++; this._items[f.Name] = c; } } #endregion } } --- NEW FILE: ICache.cs --- using System; using System.Collections; using Adapdev.Cache.Scavengers; namespace Adapdev.Cache { /// <summary> /// Summary description for ICache. /// </summary> public interface ICache { void Add(string key, object o); void Add(int key, object o); void Remove(Type t, int key); void Remove(Type t, string key); object Get(Type t, int key); object Get(Type t, string key); CacheItem GetCacheItem(Type t, string key); CacheItem GetCacheItem(Type t, int key); void Clear(); int Count{get;} bool Contains(Type t, string key); bool Contains(Type t, int key); void Scavenge(IScavenger scavenger); CacheItem[] Entries{get;} void Populate(); void Copy(ICache cache); } } --- NEW FILE: ImmutableInMemoryCache.cs --- using System; using System.Collections; using Adapdev.Serialization; namespace Adapdev.Cache { /// <summary> /// Summary description for ReadOnlyInMemoryCache. /// </summary> public class ImmutableInMemoryCache : AbstractCache { private CacheItemDictionary _hashtable = new CacheItemDictionary(); private int _ordinal = 0; public ImmutableInMemoryCache() { } #region ICache Members public override void Add(string key, object o) { SerializedCacheItem c = new SerializedCacheItem(key, o); c.Ordinal = ++this._ordinal; this._hashtable[TypeKey.Build(o.GetType(), key)] = c; } public override void Remove(Type t, string key) { this._hashtable.Remove(TypeKey.Build(t, key)); } public override object Get(Type t, string key) { return (this._hashtable[TypeKey.Build(t, key)] as CacheItem).Object; } public override CacheItem GetCacheItem(Type t, string key) { return this._hashtable[TypeKey.Build(t, key)] as CacheItem; } public override void Clear() { this._hashtable.Clear(); } public override bool Contains(Type t, string key) { return this._hashtable.Contains(TypeKey.Build(t, key)); } public override int Count { get { return this._hashtable.Count; } } public override CacheItem[] Entries { get { CacheItem[] items = new CacheItem[this._hashtable.Count]; this._hashtable.Values.CopyTo(items, 0); return items; } } public override void Populate() { } #endregion } } --- NEW FILE: ICacheItem.cs --- using System; namespace Adapdev.Cache { /// <summary> /// Summary description for ICacheItem. /// </summary> public interface ICacheItem { DateTime Created{get;} Type ObjectType{get;} object Object{get;} string Key{get;} int Ordinal{get;set;} } } --- NEW FILE: CacheItemDictionary.cs --- using System; using System.Collections; namespace Adapdev.Cache { public class CacheItemDictionary : DictionaryBase { public CacheItem this[ object key ] { get { return( (CacheItem) Dictionary[key] ); } set { Dictionary[key] = value; } } public ICollection Keys { get { return( Dictionary.Keys ); } } public ICollection Values { get { return( Dictionary.Values ); } } public void Add( String key, String value ) { Dictionary.Add( key, value ); } public bool Contains( String key ) { return( Dictionary.Contains( key ) ); } public void Remove( String key ) { Dictionary.Remove( key ); } } } |
From: Sean M. <int...@us...> - 2005-11-16 07:01:56
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.Data.Tests/CategoriesExample In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/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: --- 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 ); } } } |
From: Sean M. <int...@us...> - 2005-11-16 07:01:56
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.Cache.Tests In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/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: --- 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.CodeGen In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.CodeGen Added Files: AbstractCodeDomTemplate.cs AbstractCodeTemplate.cs AbstractConfig.cs AbstractSchemaConfig.cs Adapdev.CodeGen.csproj CodeGenerator.cs CodeType.cs CompilerFactory.cs DataSetHelper.cs ICodeDomTemplate.cs ICodeDomTemplateEventArgs.cs ICodeTemplate.cs ICodeTemplateEventArgs.cs INVelocityTemplate.cs LanguageType.cs NVelocityCodeTemplate.cs NVelocityTableCodeTemplate.cs TableCodeDomTemplate.cs TableCodeTemplate.cs UnitTestType.cs Log Message: --- NEW FILE: DataSetHelper.cs --- using System; using System.Data; using Adapdev.Data; using Adapdev.Data.Schema; namespace Adapdev.CodeGen { public class DataHelper { private DatabaseSchema schema = null; public DataHelper(DatabaseSchema schema) { this.schema = schema; } public DataTable GetDataTable(DataSet dataset, string dataTableName) { return dataset.Tables[dataTableName]; } public DataColumn GetDataColumn(DataTable table, string dataColumnName) { return table.Columns[dataColumnName]; } public object GetColumnValue(DataRow row, string columnName) { return row[columnName]; } public DataSet GetDataSet(string query) { try { IDbCommand command = DbProviderFactory.CreateCommand(schema.DatabaseProviderType); command.CommandText = query; return DbProviderFactory.CreateDataSet(schema.ConnectionString, command, schema.DatabaseProviderType); } catch(Exception e) { Console.WriteLine(e.Message); } return null; } } } --- NEW FILE: AbstractCodeDomTemplate.cs --- namespace Adapdev.CodeGen { using System; using System.CodeDom; /// <summary> /// Summary description for AbstractTemplate. /// </summary> public abstract class AbstractCodeDomTemplate : ICodeDomTemplate { protected string fileName = String.Empty; protected string className = String.Empty; protected string outputDir = String.Empty; protected string nameSpace = String.Empty; protected bool overwrite = true; /// <summary> /// Creates a new <see cref="AbstractCodeDomTemplate"/> instance. /// </summary> /// <param name="fileName">Name of the file.</param> /// <param name="className">Name of the class.</param> /// <param name="nameSpace">Namespace.</param> public AbstractCodeDomTemplate(string fileName, string className, string nameSpace) { this.fileName = fileName; this.className = className; this.nameSpace = nameSpace; } /// <summary> /// Gets or sets the name of the file. /// </summary> /// <value></value> public string FileName { get { return this.fileName; } set { this.fileName = value; } } /// <summary> /// Gets or sets the name of the class. /// </summary> /// <value></value> public string ClassName { get { return this.className; } set { this.className = value; } } /// <summary> /// Gets or sets the output directory. /// </summary> /// <value></value> public virtual string OutputDirectory { get { return this.outputDir; } set { this.outputDir = value; } } /// <summary> /// Gets or sets the namespace. /// </summary> /// <value></value> public virtual string Namespace { get { return this.nameSpace; } set { this.nameSpace = value; } } /// <summary> /// Gets or sets a value indicating whether generated file can be overwritten /// </summary> /// <value> /// <c>true</c> if it can be overwritten; otherwise, <c>false</c>. /// </value> public virtual bool Overwrite { get { return this.overwrite; } set { this.overwrite = value; } } /// <summary> /// Processes the custom code. /// </summary> public virtual void ProcessCustomCode() { } /// <summary> /// Gets the code compile unit. /// </summary> /// <returns></returns> public abstract CodeCompileUnit GetCodeCompileUnit(); } } --- NEW FILE: INVelocityTemplate.cs --- using System; using NVelocity; namespace Adapdev.CodeGen { /// <summary> /// Summary description for INVelocityTemplate. /// </summary> public interface INVelocityTemplate { /// <summary> /// Gets the context. /// </summary> /// <value></value> VelocityContext Context{get;} } } --- NEW FILE: ICodeTemplate.cs --- namespace Adapdev.CodeGen { /// <summary> /// Summary description for ICodeTemplate. /// </summary> public interface ICodeTemplate { /// <summary> /// Gets the code. /// </summary> /// <returns></returns> string GetCode(); /// <summary> /// Gets or sets the name of the file. /// </summary> /// <value></value> string FileName { get; set; } /// <summary> /// Gets or sets the name of the class. /// </summary> /// <value></value> string ClassName { get; set; } /// <summary> /// Gets or sets the namespace. /// </summary> /// <value></value> string Namespace { get; set; } /// <summary> /// Gets or sets the file extension. /// </summary> /// <value></value> string FileExtension { get; set; } /// <summary> /// Gets or sets the output directory. /// </summary> /// <value></value> string OutputDirectory { get; set; } /// <summary> /// Gets or sets a value indicating whether the generated file can be overwritten /// </summary> /// <value> /// <c>true</c> if overwrite; otherwise, <c>false</c>. /// </value> bool Overwrite { get; set; } /// <summary> /// Processes the custom code. /// </summary> void ProcessCustomCode(); } } --- NEW FILE: AbstractCodeTemplate.cs --- namespace Adapdev.CodeGen { using System; /// <summary> /// Summary description for AbstractTemplate. /// </summary> public abstract class AbstractCodeTemplate : ICodeTemplate { protected string fileName = String.Empty; protected string className = String.Empty; protected string fileExtension = String.Empty; protected string outputDir = String.Empty; protected string nameSpace = String.Empty; protected bool overwrite = true; /// <summary> /// Creates a new <see cref="AbstractCodeTemplate"/> instance. /// </summary> /// <param name="fileName">Name of the file.</param> /// <param name="fileExtension">File extension.</param> /// <param name="className">Name of the class.</param> /// <param name="nameSpace">Namespace.</param> public AbstractCodeTemplate(string fileName, string fileExtension, string className, string nameSpace) { this.fileName = fileName; this.fileExtension = fileExtension; this.className = className; this.nameSpace = nameSpace; } /// <summary> /// Gets or sets the name of the file. /// </summary> /// <value></value> public string FileName { get { return this.fileName; } set { this.fileName = value; } } /// <summary> /// Gets or sets the file extension. /// </summary> /// <value></value> public string FileExtension { get { return this.fileExtension; } set { this.fileExtension = value; } } /// <summary> /// Gets or sets the name of the class. /// </summary> /// <value></value> public string ClassName { get { return this.className; } set { this.className = value; } } /// <summary> /// Gets or sets the output directory. /// </summary> /// <value></value> public virtual string OutputDirectory { get { return this.outputDir; } set { this.outputDir = value; } } /// <summary> /// Gets or sets the namespace. /// </summary> /// <value></value> public virtual string Namespace { get { return this.nameSpace; } set { this.nameSpace = value; } } /// <summary> /// Gets or sets a value indicating whether the generated file can be overwritten /// </summary> /// <value> /// <c>true</c> if it can be overwritten; otherwise, <c>false</c>. /// </value> public virtual bool Overwrite { get { return this.overwrite; } set { this.overwrite = value; } } /// <summary> /// Processes the custom code. /// </summary> public virtual void ProcessCustomCode() { } /// <summary> /// Gets the code. /// </summary> /// <returns></returns> public abstract string GetCode(); } } --- NEW FILE: CodeGenerator.cs --- namespace Adapdev.CodeGen { using System; using System.CodeDom; using System.CodeDom.Compiler; using System.Collections; using System.IO; public delegate void ICodeTemplateProcessedEventHandler(object sender, ICodeTemplateEventArgs e); public delegate void ICodeDomTemplateProcessedEventHandler(object sender, ICodeDomTemplateEventArgs e); /// <summary> /// Summary description for CodeGenerator. /// </summary> public class CodeGenerator { public event ICodeTemplateProcessedEventHandler ICodeTemplateProcessed; public event ICodeDomTemplateProcessedEventHandler ICodeDomTemplateProcessed; protected string outputDir = String.Empty; /// <summary> /// Creates a new <see cref="CodeGenerator"/> instance. /// </summary> /// <param name="outputDir">Output dir.</param> public CodeGenerator(string outputDir) { this.outputDir = outputDir; } /// <summary> /// Gets or sets the output dir. /// </summary> /// <value></value> public string OutputDir { get { return this.outputDir; } set { this.outputDir = value; } } /// <summary> /// Processes the <see cref="ICodeDomTemplate"/> to file. /// </summary> /// <param name="template">Template.</param> /// <param name="codeType">Code type.</param> /// <param name="refAssemblies">Reference assemblies.</param> public void ProcessICodeDomTemplateToFile(ICodeDomTemplate template, LanguageType codeType, params string[] refAssemblies) { string location = Path.Combine(this.outputDir, template.OutputDirectory); location = Path.Combine(location, codeType.ToString()); CodeCompileUnit ccu = template.GetCodeCompileUnit(); foreach(string s in refAssemblies) { ccu.ReferencedAssemblies.Add(s); } if (ccu != null) { // Obtains an ICodeGenerator from a CodeDomProvider class. CodeDomProvider provider = CodeProviderFactory.GetCodeProvider(codeType); ICodeGenerator gen = provider.CreateGenerator(); // If the directory doesn't exist, create it if (!Directory.Exists(location)) { Directory.CreateDirectory(location); } // Build path and filename string filePath = Path.Combine(location, template.FileName + "." + provider.FileExtension); if (File.Exists(filePath) && template.Overwrite) // If the filepath exists and it can be overwritten { // Creates a StreamWriter to an output file. StreamWriter sw = new StreamWriter(filePath, false); // Generates source code using the code generator. gen.GenerateCodeFromCompileUnit(ccu, sw, new CodeGeneratorOptions()); // Closes the output files. sw.Close(); } else if (!File.Exists(filePath)) // If the file path doesn't exist { // Creates a StreamWriter to an output file. StreamWriter sw = new StreamWriter(filePath, false); // Generates source code using the code generator. gen.GenerateCodeFromCompileUnit(ccu, sw, new CodeGeneratorOptions()); // Closes the output files. sw.Close(); } // Process any custom code template.ProcessCustomCode(); } this.OnICodeDomTemplateProcessed(new ICodeDomTemplateEventArgs(template)); } /// <summary> /// Processes the <see cref="ICodeTemplate"/> to a file. /// </summary> /// <param name="template">Template.</param> public void ProcessICodeTemplateToFile(ICodeTemplate template) { // Get the code string code = template.GetCode(); // Make sure it's not null or empty if (template != null && !code.Equals(String.Empty)) { // Build the output path, and create it if it doesn't exist string output = Path.Combine(this.outputDir, template.OutputDirectory); if (!Directory.Exists(output)) { Directory.CreateDirectory(output); } // Build the file path string filePath = Path.Combine(output, template.FileName + "." + template.FileExtension); if (File.Exists(filePath) && template.Overwrite) // If it exists and can be overwritten { // Creates a StreamWriter to an output file. StreamWriter sw = new StreamWriter(filePath, false); // Generates source code using the code generator. sw.Write(code); // Closes the output files. sw.Close(); } else if (!File.Exists(filePath)) // The file doesn't exist { // Creates a StreamWriter to an output file. StreamWriter sw = new StreamWriter(filePath, false); // Generates source code using the code generator. sw.Write(code); // Closes the output files. sw.Close(); } template.ProcessCustomCode(); } this.OnICodeTemplateProcessed(new ICodeTemplateEventArgs(template)); } /// <summary> /// Processes the <see cref="ICodeDomTemplate"/>s to files. /// </summary> /// <param name="templates">Templates.</param> /// <param name="codeType">Code type.</param> public void ProcessICodeDomTemplatesToFiles(ICollection templates, LanguageType codeType) { foreach (ICodeDomTemplate template in templates) { try { this.ProcessICodeDomTemplateToFile(template, codeType); } catch(Exception ex) { throw ex; } } } /// <summary> /// Processes the <see cref="ICodeTemplate"/>s to files. /// </summary> /// <param name="templates">Templates.</param> public void ProcessICodeDomTemplatesToFiles(ICollection templates) { foreach (ICodeDomTemplate template in templates) { this.ProcessICodeDomTemplateToFile(template, LanguageType.CPP); this.ProcessICodeDomTemplateToFile(template, LanguageType.CSHARP); this.ProcessICodeDomTemplateToFile(template, LanguageType.JSCRIPT); this.ProcessICodeDomTemplateToFile(template, LanguageType.JSHARP); this.ProcessICodeDomTemplateToFile(template, LanguageType.VBNET); } } public void ProcessICodeTemplatesToFiles(ICollection templates) { foreach (ICodeTemplate template in templates) { this.ProcessICodeTemplateToFile(template); } } /// <summary> /// Processes the templates to an assembly. /// </summary> /// <param name="templates">Templates.</param> /// <param name="codeType">Code type.</param> /// <param name="assembly">Assembly.</param> /// <param name="cparams">Cparams.</param> public void ProcessTemplatesToAssembly(ICollection templates, LanguageType codeType, string assembly, CompilerParameters cparams) { // Create compiler for the specified CodeDom CodeDomProvider provider = CodeProviderFactory.GetCodeProvider(codeType); ICodeCompiler gen = provider.CreateCompiler(); ArrayList files = new ArrayList(); // Generate the code foreach (ICodeDomTemplate template in templates) { this.ProcessICodeDomTemplateToFile(template, codeType); files.Add(template.FileName + "." + provider.FileExtension); } // Compile the code gen.CompileAssemblyFromFileBatch(cparams, (string[]) files.ToArray(typeof (string))); } /// <summary> /// Fires when the <see cref="ICodeTemplate"/> is processed /// </summary> /// <param name="e">E.</param> public void OnICodeTemplateProcessed(ICodeTemplateEventArgs e) { if (ICodeTemplateProcessed != null) { //Invokes the delegates. ICodeTemplateProcessed(this, e); } } /// <summary> /// Fires when the <see cref="ICodeDomTemplate"/> is processed /// </summary> /// <param name="e">E.</param> public void OnICodeDomTemplateProcessed(ICodeDomTemplateEventArgs e) { if (ICodeDomTemplateProcessed != null) { //Invokes the delegates. ICodeDomTemplateProcessed(this, e); } } // public void ProcessTemplateAssemblyToFiles(Assembly a, LanguageType codeType){} // public void ProcessTemplateAssemblyToAssembly(string assemblyToRead, string assemblyToWrite, LanguageType codeType, CompilerParameters cparams){} // // public void ProcessCodeCompileUnitToFile(CodeCompileUnit ccu, string fileName, LanguageType codeType){} // public void ProcessCodeCompileUnitsToFiles(ICollection ccus, string[] fileNames, LanguageType codeType){} // public void ProcessCodeCompileUnitsToAssembly(ICollection ccus, LanguageType codeType, string assembly, CompilerParameters cparams){} // public void ProcessCodeCompileUnitAssemblyToFiles(Assembly a, LanguageType codeType){} // public void ProcessCodeCompileUnitAssemblyToAssembly(string assemblyToRead, string assemblyToWrite, LanguageType codeType, CompilerParameters cparams){} } } --- NEW FILE: ICodeDomTemplateEventArgs.cs --- namespace Adapdev.CodeGen { using System; /// <summary> /// Summary description for ICodeDomTemplateEventArgs. /// </summary> public class ICodeDomTemplateEventArgs : EventArgs { private ICodeDomTemplate _template = null; /// <summary> /// Creates a new <see cref="ICodeDomTemplateEventArgs"/> instance. /// </summary> /// <param name="template">Template.</param> public ICodeDomTemplateEventArgs(ICodeDomTemplate template) { this._template = template; } /// <summary> /// Gets the <see cref="ICodeDomTemplate"/> /// </summary> /// <value></value> public ICodeDomTemplate ICodeDomTemplate { get { return this._template; } } } } --- NEW FILE: ICodeDomTemplate.cs --- namespace Adapdev.CodeGen { using System.CodeDom; /// <summary> /// Summary description for ICodeDomTemplate. /// </summary> public interface ICodeDomTemplate { /// <summary> /// Gets the code compile unit. /// </summary> /// <returns></returns> CodeCompileUnit GetCodeCompileUnit(); /// <summary> /// Gets or sets the name of the file. /// </summary> /// <value></value> string FileName { get; set; } /// <summary> /// Gets or sets the name of the class. /// </summary> /// <value></value> string ClassName { get; set; } /// <summary> /// Gets or sets the namespace. /// </summary> /// <value></value> string Namespace { get; set; } /// <summary> /// Gets or sets the output directory. /// </summary> /// <value></value> string OutputDirectory { get; set; } /// <summary> /// Gets or sets a value indicating whether the generated file can be overwritten /// </summary> /// <value> /// <c>true</c> if overwrite; otherwise, <c>false</c>. /// </value> bool Overwrite { get; set; } /// <summary> /// Processes the custom code. /// </summary> void ProcessCustomCode(); } } --- NEW FILE: NVelocityCodeTemplate.cs --- namespace Adapdev.CodeGen { using System; using System.IO; using NVelocity; using NVelocity.App; /// <summary> /// Summary description for NVelocityCodeTemplate. /// </summary> public class NVelocityCodeTemplate : AbstractCodeTemplate, INVelocityTemplate { protected string templateFile = String.Empty; protected VelocityContext context = null; /// <summary> /// Creates a new <see cref="NVelocityCodeTemplate"/> instance. /// </summary> /// <param name="fileName">Name of the file.</param> /// <param name="fileExtension">File extension.</param> /// <param name="overWrite">Over write.</param> /// <param name="templateFile">Template file.</param> /// <param name="outputDirectory">Output directory.</param> /// <param name="className">Name of the class.</param> /// <param name="nameSpace">Namespace.</param> public NVelocityCodeTemplate(string fileName, string fileExtension, bool overWrite, string templateFile, string outputDirectory, string className, string nameSpace) : base(fileName, fileExtension, className, nameSpace) { this.templateFile = templateFile; this.outputDir = outputDirectory; this.overwrite = overWrite; if (!File.Exists("nvelocity.properties")) File.Copy(Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "nvelocity.properties"), Path.Combine(".", "nvelocity.properties"), true); if (!File.Exists("directive.properties")) File.Copy(Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "directive.properties"), Path.Combine(".", "directive.properties"), true); Velocity.Init("nvelocity.properties"); context = new VelocityContext(); } /// <summary> /// Creates a new <see cref="NVelocityCodeTemplate"/> instance. /// </summary> /// <param name="fileName">Name of the file.</param> /// <param name="fileExtension">File extension.</param> /// <param name="templateFile">Template file.</param> /// <param name="outputDirectory">Output directory.</param> public NVelocityCodeTemplate(string fileName, string fileExtension, string templateFile, string outputDirectory) : this(fileName, fileExtension, true, templateFile, outputDirectory, String.Empty, String.Empty) { } /// <summary> /// Gets the code. /// </summary> /// <returns></returns> public override string GetCode() { if(!context.ContainsKey("namespace")) context.Put("namespace", this.nameSpace); if(!context.ContainsKey("classname")) context.Put("classname", this.className); if(!context.ContainsKey("filename")) context.Put("filename", this.fileName); context.Put("datetimenow", DateTime.Now); context.Put("template", this); StringWriter writer = new StringWriter(); Velocity.MergeTemplate(this.templateFile, context, writer); return writer.GetStringBuilder().ToString(); } /// <summary> /// Gets or sets the template file. /// </summary> /// <value></value> public string TemplateFile { get { return this.templateFile; } set { this.templateFile = value; } } public override bool Overwrite { get { return this.overwrite; } set { base.Overwrite = value; } } /// <summary> /// Gets the context. /// </summary> /// <value></value> public VelocityContext Context { get { return this.context; } } public string GetConversionExpression(string objectType) { string subt = objectType.Substring(objectType.IndexOf(".") + 1); return "Convert.To"+subt; } } } --- NEW FILE: ICodeTemplateEventArgs.cs --- namespace Adapdev.CodeGen { using System; /// <summary> /// Summary description for ICodeTemplateEventArgs. /// </summary> public class ICodeTemplateEventArgs : EventArgs { private ICodeTemplate _template = null; /// <summary> /// Creates a new <see cref="ICodeTemplateEventArgs"/> instance. /// </summary> /// <param name="template">Template.</param> public ICodeTemplateEventArgs(ICodeTemplate template) { this._template = template; } /// <summary> /// Gets the I code template. /// </summary> /// <value></value> public ICodeTemplate ICodeTemplate { get { return this._template; } } } } --- NEW FILE: LanguageType.cs --- namespace Adapdev.CodeGen { using System; /// <summary> /// Summary description for LanguageType. /// </summary> /// [Flags] public enum LanguageType { CSHARP = 1, JSHARP = 2, JSCRIPT = 4, VBNET = 8, CPP = 16, SQL = 32, OTHER = 64, JAVA = 128 } } --- NEW FILE: TableCodeDomTemplate.cs --- namespace Adapdev.CodeGen { using Adapdev.Data.Schema; public abstract class TableCodeDomTemplate : AbstractCodeDomTemplate { protected TableSchema ti; /// <summary> /// Creates a new <see cref="TableCodeDomTemplate"/> instance. /// </summary> /// <param name="ti">TableSchema.</param> /// <param name="nameSpace">Namespace.</param> /// <param name="fileName">Name of the file.</param> /// <param name="className">Name of the class.</param> public TableCodeDomTemplate(TableSchema ti, string nameSpace, string fileName, string className) : base(fileName, className, nameSpace) { this.ti = ti; } } } --- NEW FILE: Adapdev.CodeGen.csproj --- <VisualStudioProject> <CSHARP ProjectType = "Local" ProductVersion = "7.10.3077" SchemaVersion = "2.0" ProjectGuid = "{2D8FC662-0244-49F1-8017-DFE73B191017}" > <Build> <Settings ApplicationIcon = "" AssemblyKeyContainerName = "" AssemblyName = "Adapdev.CodeGen" AssemblyOriginatorKeyFile = "" DefaultClientScript = "JScript" DefaultHTMLPageLayout = "Grid" DefaultTargetSchema = "IE50" DelaySign = "false" OutputType = "Library" PreBuildEvent = "" PostBuildEvent = "" RootNamespace = "Adapdev.CodeGen" RunPostBuildEvent = "OnBuildSuccess" StartupObject = "" > <Config Name = "Debug" AllowUnsafeBlocks = "false" BaseAddress = "285212672" CheckForOverflowUnderflow = "false" ConfigurationOverrideFile = "" DefineConstants = "DEBUG;TRACE" DocumentationFile = "" DebugSymbols = "true" FileAlignment = "4096" IncrementalBuild = "false" NoStdLib = "false" NoWarn = "" Optimize = "false" OutputPath = "bin\Debug\" RegisterForComInterop = "false" RemoveIntegerChecks = "false" TreatWarningsAsErrors = "false" WarningLevel = "4" /> <Config Name = "Release" AllowUnsafeBlocks = "false" BaseAddress = "285212672" CheckForOverflowUnderflow = "false" ConfigurationOverrideFile = "" DefineConstants = "TRACE" DocumentationFile = "" DebugSymbols = "false" FileAlignment = "4096" IncrementalBuild = "false" NoStdLib = "false" NoWarn = "" Optimize = "true" OutputPath = "bin\Release\" RegisterForComInterop = "false" RemoveIntegerChecks = "false" TreatWarningsAsErrors = "false" WarningLevel = "4" /> </Settings> <References> <Reference Name = "System" AssemblyName = "System" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.dll" /> <Reference Name = "System.Data" AssemblyName = "System.Data" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.Data.dll" /> <Reference Name = "System.XML" AssemblyName = "System.Xml" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.XML.dll" /> <Reference Name = "Adapdev" Project = "{CC30A321-2569-4B1F-8E1A-781B5509B56D}" Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" /> <Reference Name = "Adapdev.Data" Project = "{08C5794D-44ED-4E75-A1C1-48A28C3D0044}" Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" /> <Reference Name = "Adapdev.NVelocity" Project = "{75D57D5C-250A-447C-80BC-2FF9DC8A14D2}" Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" /> <Reference Name = "MCppCodeDomProvider" AssemblyName = "MCppCodeDomProvider" HintPath = "C:\Program Files\Microsoft Visual Studio .NET 2003\Common7\IDE\PublicAssemblies\MCppCodeDomProvider.dll" AssemblyFolderKey = "hklm\publicassemblies" /> <Reference Name = "Microsoft.JScript" AssemblyName = "Microsoft.JScript" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\Microsoft.JScript.dll" /> <Reference Name = "Microsoft.VisualBasic" AssemblyName = "Microsoft.VisualBasic" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\Microsoft.VisualBasic.dll" /> <Reference Name = "VJSharpCodeProvider" AssemblyName = "VJSharpCodeProvider" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\VJSharpCodeProvider.DLL" /> <Reference Name = "log4net" AssemblyName = "log4net" HintPath = "..\..\lib\log4net.dll" /> </References> </Build> <Files> <Include> <File RelPath = "AbstractCodeDomTemplate.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "AbstractCodeTemplate.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "AbstractConfig.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "AbstractSchemaConfig.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "AdapdevAssemblyInfo.cs" Link = "..\AdapdevAssemblyInfo.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "CodeGenerator.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "CodeType.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "CompilerFactory.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "DataSetHelper.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "ICodeDomTemplate.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "ICodeDomTemplateEventArgs.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "ICodeTemplate.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "ICodeTemplateEventArgs.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "INVelocityTemplate.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "LanguageType.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "NVelocityCodeTemplate.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "NVelocityTableCodeTemplate.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "TableCodeDomTemplate.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "TableCodeTemplate.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "UnitTestType.cs" SubType = "Code" BuildAction = "Compile" /> </Include> </Files> </CSHARP> </VisualStudioProject> --- NEW FILE: CodeType.cs --- using System; namespace Adapdev.Data.CodeGen { /// <summary> /// Summary description for CodeType. /// </summary> /// [FlagsAttribute] public enum CodeType { CSHARP, JSHARP, JSCRIPT, VBNET, CPP } } --- NEW FILE: AbstractConfig.cs --- namespace Adapdev.CodeGen { using System; using System.Collections; using System.IO; public delegate void ProcessCustomCodeHandler(string info); /// <summary> /// Summary description for AbstractConfig. /// </summary> public abstract class AbstractConfig { protected Hashtable properties = null; protected string nameSpace = String.Empty; protected ArrayList languages = new ArrayList(); protected string appdir = AppDomain.CurrentDomain.SetupInformation.ApplicationBase; protected string shareddir = String.Empty; protected string outputdir = String.Empty; /// <summary> /// Creates a new <see cref="AbstractConfig"/> instance. /// </summary> /// <param name="nameSpace">Namespace.</param> public AbstractConfig(string nameSpace) { this.nameSpace = nameSpace; shareddir = Path.Combine(this.appdir, "shared"); } /// <summary> /// Gets the base output directory for this template library /// </summary> /// <value></value> public virtual string PackageDirectory { get { return this.PackageName; } } /// <summary> /// Gets or sets the output directory. /// </summary> /// <value></value> public virtual string OutputDirectory { get { return this.outputdir; } set { this.outputdir = value; } } /// <summary> /// Gets the application directory. /// </summary> /// <value></value> public string ApplicationDirectory { get { return this.appdir; } } /// <summary> /// Gets or sets the shared directory. /// </summary> /// <value></value> public string SharedDirectory { get { return this.shareddir; } set { this.shareddir = value; } } /// <summary> /// Gets or sets the base namespace for this template library /// </summary> /// <value></value> public string NameSpace { get { return this.nameSpace; } set { this.nameSpace = value; } } /// <summary> /// Gets or sets the custom properties. /// </summary> /// <value></value> public virtual Hashtable CustomProperties { get { return this.properties; } set { this.properties = value; } } /// <summary> /// Processes the custom code. /// </summary> public virtual void ProcessCustomCode() { } public event ProcessCustomCodeHandler Processing; public void OnProcessing(string info) { if(Processing != null) { Processing(info); } } /// <summary> /// Gets the code DOM templates. /// </summary> /// <returns>A list of ICodeDomTemplates to process</returns> public abstract ArrayList GetCodeDomTemplates(); /// <summary> /// Gets the code templates. /// </summary> /// <returns>A list of ICodeTemplates to process</returns> public abstract ArrayList GetCodeTemplates(); // The name of the package. /// <summary> /// Gets the name of the package. /// </summary> /// <value></value> public abstract string PackageName { get; } /// <summary> /// Gets the package description. /// </summary> /// <value></value> public abstract string PackageDescription { get; } /// <summary> /// Gets the author. /// </summary> /// <value></value> public abstract string Author { get; } /// <summary> /// Gets the version. /// </summary> /// <value></value> public abstract string Version { get; } /// <summary> /// Gets the copyright. /// </summary> /// <value></value> public abstract string Copyright { get; } } } --- NEW FILE: AbstractSchemaConfig.cs --- namespace Adapdev.CodeGen { using System; using Adapdev.Data.Schema; /// <summary> /// Summary description for AbstractConfig. /// </summary> public abstract class AbstractSchemaConfig : AbstractConfig { protected string connectionString = String.Empty; protected DatabaseSchema databaseSchema = new DatabaseSchema(); /// <summary> /// Creates a new <see cref="AbstractSchemaConfig"/> instance. /// </summary> /// <param name="connectionString">Connection string.</param> /// <param name="nameSpace">Namespace.</param> /// <param name="databaseSchema">Database schema.</param> public AbstractSchemaConfig(string connectionString, string nameSpace, DatabaseSchema databaseSchema) : base(nameSpace) { this.connectionString = connectionString; this.databaseSchema = databaseSchema; } /// <summary> /// Gets or sets the connection string. /// </summary> /// <value></value> public string ConnectionString { get { return this.connectionString; } set { this.connectionString = value; } } /// <summary> /// Gets or sets the <see cref="DatabaseSchema"/> /// </summary> /// <value></value> public DatabaseSchema DatabaseSchema { get { return this.databaseSchema; } set { this.databaseSchema = value; } } } } --- NEW FILE: NVelocityTableCodeTemplate.cs --- namespace Adapdev.CodeGen { using System; using System.Collections; using System.IO; using System.Text; using Adapdev.Data; using Adapdev.Data.Schema; using Adapdev.Data.Sql; using NVelocity; using NVelocity.App; /// <summary> /// Summary description for NVelocityTableCodeTemplate. /// </summary> public class NVelocityTableCodeTemplate : TableCodeTemplate, INVelocityTemplate { protected DatabaseSchema di = null; protected string templateFile = String.Empty; protected VelocityContext context = null; /// <summary> /// Creates a new <see cref="NVelocityTableCodeTemplate"/> instance. /// </summary> /// <param name="di">Database Schema.</param> /// <param name="ti">Table Schema.</param> /// <param name="outputDirectory">Output directory.</param> /// <param name="templateFile">Template file.</param> /// <param name="nameSpace">Namespace.</param> /// <param name="fileName">Name of the file.</param> /// <param name="fileExtension">File extension.</param> /// <param name="className">Name of the class.</param> /// <param name="overWrite">Over write.</param> public NVelocityTableCodeTemplate(DatabaseSchema di, TableSchema ti, string outputDirectory, string templateFile, string nameSpace, string fileName, string fileExtension, string className, bool overWrite) : base(ti, nameSpace, fileName, fileExtension, className) { this.di = di; this.templateFile = templateFile; this.outputDir = outputDirectory; this.overwrite = overWrite; if (!File.Exists("nvelocity.properties")) File.Copy(Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "nvelocity.properties"), Path.Combine(".", "nvelocity.properties"), true); if (!File.Exists("directive.properties")) File.Copy(Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "directive.properties"), Path.Combine(".", "directive.properties"), true); Velocity.Init("nvelocity.properties"); context = new VelocityContext(); } /// <summary> /// Creates a new <see cref="NVelocityTableCodeTemplate"/> instance. /// </summary> /// <param name="di">Database Schema.</param> /// <param name="ti">Table Schema.</param> /// <param name="outputDirectory">Output directory.</param> /// <param name="templateFile">Template file.</param> /// <param name="fileName">Name of the file.</param> /// <param name="fileExtension">File extension.</param> public NVelocityTableCodeTemplate(DatabaseSchema di, TableSchema ti, string outputDirectory, string templateFile, string fileName, string fileExtension) : this(di, ti, outputDirectory, templateFile, String.Empty, fileName, fileExtension, String.Empty, true) { } /// <summary> /// Gets the code. /// </summary> /// <returns></returns> public override string GetCode() { context.Put("databaseschema", this.di); context.Put("tableschema", this.ti); if(!context.ContainsKey("namespace")) context.Put("namespace", this.nameSpace); if(!context.ContainsKey("classname")) context.Put("classname", this.className); if(!context.ContainsKey("filename")) context.Put("filename", this.fileName); context.Put("datetimenow", DateTime.Now); context.Put("datahelper", new DataHelper(di)); context.Put("providerinfo", ProviderInfoManager.GetInstance()); context.Put("template", this); context.Put("queryhelper", new QueryHelper()); context.Put("mysqlprovidertype", Adapdev.Data.DbProviderType.MYSQL); StringWriter writer = new StringWriter(); Velocity.MergeTemplate(this.templateFile, context, writer); return writer.GetStringBuilder().ToString(); } /// <summary> /// Gets the Sql to select one record by the primary key /// </summary> /// <returns></returns> public string GetSelectOneSql() { return this.GetSelectOneSql(this.ti); } /// <summary> /// Gets the Sql to select one record by the primary key /// </summary> /// <param name="ts">Ts.</param> /// <returns></returns> public string GetSelectOneSql(TableSchema ts) { if(ts.HasPrimaryKeys) { ISelectQuery query = QueryFactory.CreateSelectQuery(di.DatabaseType, di.DatabaseProviderType); query.SetTable(ts.Name); foreach (ColumnSchema ci in ts.OrdinalColumns.Values) { if(ci.IsActive)query.Add(ci.Name); } ArrayList pks = new ArrayList(ts.PrimaryKeys.Values); ColumnSchema pk = (ColumnSchema) pks[0]; ICriteria criteria = query.CreateCriteria(); criteria.DbProviderType = this.di.DatabaseProviderType; criteria.AddEqualTo(pk.Name); query.SetCriteria(criteria); return query.GetText(); } return ""; } /// <summary> /// Gets the insert SQL. /// </summary> /// <returns></returns> public string GetInsertSql() { return this.GetInsertSql(this.ti); } /// <summary> /// Gets the insert SQL. /// </summary> /// <param name="ts">Ts.</param> /// <returns></returns> public string GetInsertSql(TableSchema ts) { IInsertQuery query = QueryFactory.CreateInsertQuery(di.DatabaseType, di.DatabaseProviderType); query.SetTable(ts.Name); foreach (ColumnSchema ci in ts.SortedColumns.Values) { if (!ci.IsAutoIncrement && ci.IsActive) query.Add(ci.Name); } return query.GetText(); } /// <summary> /// Gets the update SQL. /// </summary> /// <returns></returns> public string GetUpdateSql() { return this.GetUpdateSql(this.ti); } /// <summary> /// Gets the update SQL. /// </summary> /// <returns></returns> public string GetUpdateSql(TableSchema ts) { IUpdateQuery query = QueryFactory.CreateUpdateQuery(di.DatabaseType, di.DatabaseProviderType); query.SetTable(ts.Name); foreach (ColumnSchema ci in ts.SortedColumns.Values) { if (!ci.IsAutoIncrement && ci.IsActive) query.Add(ci.Name); } ArrayList pks = new ArrayList(ts.PrimaryKeys.Values); ICriteria criteria = query.CreateCriteria(); criteria.DbProviderType = this.di.DatabaseProviderType; int i = 1; foreach(ColumnSchema pk in pks) { criteria.AddEqualTo(pk.Name); if(i < pks.Count) criteria.AddAnd(); i++; } query.SetCriteria(criteria); return query.GetText(); } /// <summary> /// Gets the delete one SQL. /// </summary> /// <returns></returns> public string GetDeleteOneSql() { return this.GetDeleteOneSql(this.ti); } /// <summary> /// Gets the sql to delete one record by primary key /// </summary> /// <returns></returns> public string GetDeleteOneSql(TableSchema ts) { if(ts.HasPrimaryKeys) { IDeleteQuery query = QueryFactory.CreateDeleteQuery(di.DatabaseType, di.DatabaseProviderType); query.SetTable(ts.Name); ArrayList pks = new ArrayList(ts.PrimaryKeys.Values); ColumnSchema pk = (ColumnSchema) pks[0]; ICriteria criteria = query.CreateCriteria(); criteria.DbProviderType = this.di.DatabaseProviderType; criteria.AddEqualTo(pk.Name); query.SetCriteria(criteria); return query.GetText(); } return ""; } /// <summary> /// Gets the foreign key SQL. /// </summary> /// <param name="ci">Ci.</param> /// <returns></returns> public string GetForeignKeySql(ColumnSchema ci) { return this.GetForeignKeySql(this.ti, ci); } /// <summary> /// Gets the foreign key SQL. /// </summary> /// <param name="ts">Ts.</param> /// <param name="columnSchema">Column schema.</param> /// <returns></returns> public string GetForeignKeySql(TableSchema ts, ColumnSchema columnSchema) { ISelectQuery query = QueryFactory.CreateSelectQuery(di.DatabaseType); query.SetTable(ts.Name); foreach (ColumnSchema ci2 in ts.OrdinalColumns.Values) { if(ci2.IsActive)query.Add(ci2.Name); } ICriteria criteria = query.CreateCriteria(); criteria.DbProviderType = this.di.DatabaseProviderType; criteria.AddEqualTo(columnSchema.Name); query.SetCriteria(criteria); return query.GetText(); } /// <summary> /// Gets the name of the parameter. /// </summary> /// <param name="name">Name.</param> /// <returns></returns> public string GetParameterName(string name) { return QueryHelper.GetParameterName(name, this.di.DatabaseProviderType); } /// <summary> /// Gets the parameter value. /// </summary> /// <param name="c">C.</param> /// <returns></returns> public string GetParameterValue(DatabaseSchema d, ColumnSchema c) { if (c.NetType.Equals("System.DateTime")) { if(d.DatabaseType == Adapdev.Data.DbType.SQLSERVER) return c.Alias + ".Subtract(new TimeSpan(2,0,0,0)).ToOADate()"; else if(d.DatabaseType == Adapdev.Data.DbType.ORACLE) return c.Alias; else if (d.DatabaseType == Adapdev.Data.DbType.MYSQL) return c.Alias; else return c.Alias + ".ToOADate()"; } else return c.Alias; } public string GetParameterLength(ColumnSchema c) { switch(c.DataType.ToLower()) { case "binary": case "char": case "nchar": case "nvarchar": case "varbinary": case "varchar": return "(" + c.Length + ")"; } return String.Empty; } public string GetParameterText(ColumnSchema cs) { return this.GetParameterName(cs.Name) + " " + cs.DataType.ToLower() + this.GetParameterLength(cs); } /// <summary> /// Gets or sets the template file. /// </summary> /// <value></value> public string TemplateFile { get { return this.templateFile; } set { this.templateFile = value; } } public override bool Overwrite { get { return this.overwrite; } set { base.Overwrite = value; } } /// <summary> /// Gets the context. /// </summary> /// <value></value> public VelocityContext Context { get { return this.context; } } public string GetConversionExpression(string objectType) { string subt = objectType.Substring(objectType.IndexOf(".") + 1); return "Convert.To"+subt; } public string GetSqlServerSPInsertParams(TableSchema ts) { StringBuilder sb = new StringBuilder(); ArrayList al = new ArrayList(); // Get all columns that aren't autoincrement foreach(ColumnSchema cs in ts.SortedColumns.Values) { if(!cs.IsAutoIncrement && cs.IsActive)al.Add(cs); } // Build the list of parameters int i = 1; foreach(ColumnSchema cs in al) { if(cs.IsActive) { if(i < al.Count) { sb.Append(this.GetParameterText(cs) + "," + Environment.NewLine); } else { sb.Append(this.GetParameterText(cs) + Environment.NewLine); } i++; } } return sb.ToString(); } public string GetSqlServerSPUpdateParams(TableSchema ts) { int i = 1; StringBuilder sb = new StringBuilder(); foreach (ColumnSchema columnSchema in ts.SortedColumns.Values) { if(columnSchema.IsActive) { if(i < ts.SortedColumns.Count) { sb.Append(this.GetParameterText(columnSchema) + "," + Environment.NewLine); } else { sb.Append(this.GetParameterText(columnSchema) + Environment.NewLine); } } i++; } return sb.ToString(); } } } --- NEW FILE: CompilerFactory.cs --- namespace Adapdev.CodeGen { using System.CodeDom.Compiler; using Microsoft.CSharp; using Microsoft.JScript; using Microsoft.MCpp; using Microsoft.VisualBasic; using Microsoft.VJSharp; /// <summary> /// Summary description for CompilerFactory. /// </summary> public class CodeProviderFactory { /// <summary> /// Gets the code provider. /// </summary> /// <param name="codeType">Code type.</param> /// <returns></returns> public static CodeDomProvider GetCodeProvider(LanguageType codeType) { switch (codeType) { case LanguageType.CPP: return new MCppCodeProvider(); case LanguageType.CSHARP: return new CSharpCodeProvider(); case LanguageType.JSCRIPT: return new JScriptCodeProvider(); case LanguageType.JSHARP: return new VJSharpCodeProvider(); case LanguageType.VBNET: return new VBCodeProvider(); default: return new CSharpCodeProvider(); } } } } --- NEW FILE: UnitTestType.cs --- using System; namespace Adapdev.Data.CodeGen { /// <summary> /// Summary description for UnitTestType. /// </summary> public enum UnitTestType { CSUNIT, NUNIT, ZANEBUG, MBUNIT } } --- NEW FILE: TableCodeTemplate.cs --- namespace Adapdev.CodeGen { using System; using Adapdev.Data.Schema; public abstract class TableCodeTemplate : AbstractCodeTemplate { protected TableSchema ti; /// <summary> /// Creates a new <see cref="TableCodeTemplate"/> instance. /// </summary> /// <param name="ti">TableSchema.</param> /// <param name="nameSpace">Namespace.</param> /// <param name="fileName">Name of the file.</param> /// <param name="fileExtension">File extension.</param> /// <param name="className">Name of the class.</param> public TableCodeTemplate(TableSchema ti, string nameSpace, string fileName, string fileExtension, string className) : base(fileName, fileExtension, className, nameSpace) { this.ti = ti; } /// <summary> /// Creates a new <see cref="TableCodeTemplate"/> instance. /// </summary> /// <param name="ti">TableSchema.</param> /// <param name="fileName">Name of the file.</param> /// <param name="fileExtension">File extension.</param> public TableCodeTemplate(TableSchema ti, string fileName, string fileExtension) : base(fileName, fileExtension, String.Empty, String.Empty) { this.ti = ti; } } } |
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.Cache/Scavengers In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.Cache/Scavengers Added Files: AbsoluteExpirationScavenger.cs GreaterThanOrdinalScavenger.cs IScavenger.cs LIFONumberScavenger.cs SlidingExpirationScavenger.cs Log Message: --- 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 } } |
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.Cache.Tests/Scavengers In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.Cache.Tests/Scavengers Added Files: AbsoluteExpirationScavengerTest.cs BaseScavengerTest.cs GreaterThanOrdinalScavengerTest.cs SlidingExpirationScavengerTest.cs Log Message: --- 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); } } } } |
From: Sean M. <int...@us...> - 2005-11-16 07:01:55
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.CodeGen.Tests In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.CodeGen.Tests Added Files: Adapdev.CodeGen.Tests.csproj Log Message: --- 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 06:54:26
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.Data/bin/Release In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv32278/Release Log Message: Directory /cvsroot/adapdev/Adapdev/src/Adapdev.Data/bin/Release added to the repository |
From: Sean M. <int...@us...> - 2005-11-16 06:08:36
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv25817/src/Adapdev Removed Files: Util.cs ValidationResult.cs Log Message: --- Util.cs DELETED --- --- ValidationResult.cs DELETED --- |
From: Sean M. <int...@us...> - 2005-11-16 06:08:36
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev/Text In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv25817/src/Adapdev/Text Removed Files: StringUtil.cs Log Message: --- StringUtil.cs DELETED --- |
From: Sean M. <int...@us...> - 2005-11-16 06:08:36
|
Update of /cvsroot/adapdev/Adapdev/src/FullTests In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv25817/src/FullTests Removed Files: FullTests.csproj Log Message: --- FullTests.csproj DELETED --- |
From: Sean M. <int...@us...> - 2005-11-16 06:08:36
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev/UID In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv25817/src/Adapdev/UID Removed Files: GuidUIDGenerator.cs TimeSpanUIDGenerator.cs UIDFactory.cs UIDGenerator.cs Log Message: --- UIDFactory.cs DELETED --- --- UIDGenerator.cs DELETED --- --- GuidUIDGenerator.cs DELETED --- --- TimeSpanUIDGenerator.cs DELETED --- |
From: Sean M. <int...@us...> - 2005-11-16 06:08:36
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev/XPath/Internal In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv25817/src/Adapdev/XPath/Internal Removed Files: ObjectNavigationContext.cs ObjectNavigatorState.cs ObjectNavigatorStateDictionary.cs ObjectNavigatorStateItem.cs ObjectNavigatorStateList.cs ObjectNavigatorStateRoot.cs Log Message: --- ObjectNavigationContext.cs DELETED --- --- ObjectNavigatorStateList.cs DELETED --- --- ObjectNavigatorStateRoot.cs DELETED --- --- ObjectNavigatorState.cs DELETED --- --- ObjectNavigatorStateDictionary.cs DELETED --- --- ObjectNavigatorStateItem.cs DELETED --- |
From: Sean M. <int...@us...> - 2005-11-16 06:08:36
|
Update of /cvsroot/adapdev/Adapdev/src In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv25817/src Removed Files: adapdev.snk Log Message: --- adapdev.snk DELETED --- |
From: Sean M. <int...@us...> - 2005-11-16 06:08:36
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev/XPath In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv25817/src/Adapdev/XPath Removed Files: TypeInfoCache.cs XPathObjectNavigator.cs Log Message: --- XPathObjectNavigator.cs DELETED --- --- TypeInfoCache.cs DELETED --- |
From: Sean M. <int...@us...> - 2005-11-16 06:08:36
|
Update of /cvsroot/adapdev/Adapdev/src/FullBuild In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv25817/src/FullBuild Removed Files: FullBuild.csproj FullBuild.csproj.user Log Message: --- FullBuild.csproj DELETED --- --- FullBuild.csproj.user DELETED --- |
From: Sean M. <int...@us...> - 2005-11-16 06:08:35
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev/Text/Indexing In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv25817/src/Adapdev/Text/Indexing Removed Files: IIndex.cs IRecord.cs ISearchExpression.cs ISearchHitFilter.cs SearchResult.cs Log Message: --- IIndex.cs DELETED --- --- ISearchHitFilter.cs DELETED --- --- SearchResult.cs DELETED --- --- IRecord.cs DELETED --- --- ISearchExpression.cs DELETED --- |
From: Sean M. <int...@us...> - 2005-11-16 06:08:35
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev/Threading In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv25817/src/Adapdev/Threading Removed Files: CallerThreadContext.cs DelegateAdapter.cs Exceptions.cs STPStartInfo.cs SmartThreadPool.cs ThreadPoolWait.cs WorkItem.cs WorkItemsQueue.cs Log Message: --- WorkItem.cs DELETED --- --- WorkItemsQueue.cs DELETED --- --- CallerThreadContext.cs DELETED --- --- DelegateAdapter.cs DELETED --- --- STPStartInfo.cs DELETED --- --- SmartThreadPool.cs DELETED --- --- ThreadPoolWait.cs DELETED --- --- Exceptions.cs DELETED --- |
From: Sean M. <int...@us...> - 2005-11-16 06:08:35
|
Update of /cvsroot/adapdev/Adapdev/src/TestBed In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv25817/src/TestBed Removed Files: App.ico AssemblyInfo.cs Class1.cs TestBed.csproj Log Message: --- App.ico DELETED --- --- TestBed.csproj DELETED --- --- Class1.cs DELETED --- --- AssemblyInfo.cs DELETED --- |
From: Sean M. <int...@us...> - 2005-11-16 06:08:35
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev/Text/Indexing/Records In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv25817/src/Adapdev/Text/Indexing/Records Removed Files: HashtableRecord.cs Log Message: --- HashtableRecord.cs DELETED --- |
From: Sean M. <int...@us...> - 2005-11-16 06:08:35
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev/Text/Indexing/FullText In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv25817/src/Adapdev/Text/Indexing/FullText Removed Files: TermOccurenceCollection.cs TermOccurrence.cs Token.cs Log Message: --- TermOccurenceCollection.cs DELETED --- --- Token.cs DELETED --- --- TermOccurrence.cs DELETED --- |