adapdev-commits Mailing List for Adapdev.NET (Page 10)
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
|
From: Sean M. <int...@us...> - 2005-11-16 07:02:08
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.UnitTest.TestRunner In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.UnitTest.TestRunner Added Files: Adapdev.UnitTest.TestRunner.csproj AdapdevTestRunner.cs Log Message: --- NEW FILE: AdapdevTestRunner.cs --- using System; using System.Text; using TestDriven.Framework; using System.Reflection; using Adapdev.UnitTest.Core; using System.Diagnostics; namespace Adapdev.UnitTest.TestRunner { public class AdapdevTestRunner : ITestRunner { public TestRunResult RunAssembly(ITestListener testListener, Assembly assembly) { ITestSuiteFilter filter = new NoFilter(); return run(testListener, assembly, filter); } public TestRunResult RunMember(ITestListener testListener, Assembly assembly, MemberInfo member) { if (member is Type) { ITestSuiteFilter filter = new TypeFilter(member as Type); return run(testListener, assembly, filter); } else if (member is MethodInfo) { ITestSuiteFilter filter = new MethodFilter(member as MethodInfo); return run(testListener, assembly, filter); } else { return TestRunResult.NoTests; } } public TestRunResult RunNamespace(ITestListener testListener, Assembly assembly, string ns) { ITestSuiteFilter filter = new NamespaceFilter(ns); return run(testListener, assembly, filter); } TestRunResult run(ITestListener testListener, Assembly assembly, ITestSuiteFilter filter) { string assemblyFile = new Uri(assembly.CodeBase).LocalPath; ITestEngine engine = TestEngineFactory.CreateLocal(assemblyFile); TestSuite suite = engine.GetTestSuite(); filter.Filter(suite); if (suite.GetTestCount() == 0) { return TestRunResult.NoTests; } ProxyTestListener listener = new ProxyTestListener(testListener, suite.GetTestCount()); engine.SetTestEventDispatcher(listener.CreateDispatcher()); TestAssemblyResult[] results = engine.Run(suite); // HACK: Not always Success. return TestRunResult.Success; } class ProxyTestListener { ITestListener testListener; int testCount; public ProxyTestListener(ITestListener testListener, int testCount) { this.testListener = testListener; this.testCount = testCount; } public TestEventDispatcher CreateDispatcher() { TestEventDispatcher dispatcher = new TestEventDispatcher(); dispatcher.TestCompleted += new TestCompletedEventHandler(dispatcher_TestCompleted); dispatcher.TestIterationCompleted += new TestIterationCompletedEventHandler(dispatcher_TestIterationCompleted); dispatcher.TestSuiteCompleted += new TestSuiteCompletedEventHandler(dispatcher_TestSuiteCompleted); return dispatcher; } void dispatcher_TestCompleted(object sender, TestResultEventArgs e) { } private void dispatcher_TestIterationCompleted(object sender, TestIterationEventArgs e) { // HACK: Should this event fire if the test is ForcedIgnore? if (e.TestIteration.State != TestState.Ignore) { TestResultSummary summary = new TestResultSummary(); summary.TotalTests = this.testCount; summary.IsFailure = e.TestIteration.State == TestState.Fail; summary.IsSuccess = e.TestIteration.State == TestState.Pass; summary.IsExecuted = summary.IsFailure || summary.IsSuccess; // This is the correct code, but commented out // since the TextFormatter is currently in place // if(summary.IsFailure) // { // summary.StackTrace = e.TestIteration.FullStackTrace; // summary.Message = e.TestIteration.Result + // Environment.NewLine + // e.TestIteration.ConsoleOutput; // // ConsoleOutput is a hack since // // I don't see a property in TestResultSummary. // // Where should this go? // } summary.Name = e.TestIteration.Name; summary.TimeSpan = TimeSpan.FromSeconds(e.TestIteration.Duration); summary.TestRunner = GetType().FullName; this.testListener.TestFinished(summary); } } private void dispatcher_TestSuiteCompleted(object sender, TestAssemblyResult[] tar) { Console.WriteLine(new Adapdev.UnitTest.Core.TextFormatter(tar).GetText()); } } interface ITestSuiteFilter { void Filter(TestSuite suite); } class NoFilter : ITestSuiteFilter { public void Filter(TestSuite suite) { } } class NamespaceFilter : ITestSuiteFilter { string ns; public NamespaceFilter(string ns) { this.ns = ns; } public void Filter(TestSuite suite) { if (this.ns.Length > 0) { string prefix = this.ns + "."; foreach (TestAssembly testAssembly in suite.GetTestAssemblies()) { foreach (TestFixture testFixture in testAssembly.GetTestFixtures()) { if (!toFullName(testFixture).StartsWith(prefix)) { testFixture.ShouldRun = false; } } } } } } class TypeFilter : ITestSuiteFilter { Type type; public TypeFilter(Type type) { this.type = type; } public void Filter(TestSuite suite) { foreach (TestAssembly testAssembly in suite.GetTestAssemblies()) { foreach (TestFixture testFixture in testAssembly.GetTestFixtures()) { if (toFullName(testFixture) != this.type.FullName) { testFixture.ShouldRun = false; } } } } } class MethodFilter : ITestSuiteFilter { MethodInfo method; public MethodFilter(MethodInfo method) { this.method = method; } public void Filter(TestSuite suite) { Type type = this.method.ReflectedType; foreach (TestAssembly testAssembly in suite.GetTestAssemblies()) { foreach (TestFixture testFixture in testAssembly.GetTestFixtures()) { if (toFullName(testFixture) != type.FullName) { testFixture.ShouldRun = false; } else { foreach (Test test in testFixture.GetTests()) { if (test.Method != method.Name) { test.ShouldRun = false; } } } } } } } static string toFullName(TestFixture testFixture) { string fullName = ""; if (testFixture.Namespace != null && testFixture.Namespace.Length > 0) { fullName += testFixture.Namespace + "."; } fullName += testFixture.Class; return fullName; } } } --- NEW FILE: Adapdev.UnitTest.TestRunner.csproj --- <VisualStudioProject> <CSHARP ProjectType = "Local" ProductVersion = "7.10.3077" SchemaVersion = "2.0" ProjectGuid = "{2D0C35AA-CC64-4513-947D-F67C035D2B71}" > <Build> <Settings ApplicationIcon = "" AssemblyKeyContainerName = "" AssemblyName = "Adapdev.TestRunner" AssemblyOriginatorKeyFile = "" DefaultClientScript = "JScript" DefaultHTMLPageLayout = "Grid" DefaultTargetSchema = "IE50" DelaySign = "false" OutputType = "Library" PreBuildEvent = "" PostBuildEvent = "" RootNamespace = "Adapdev.TestRunner" 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 = "G:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.dll" /> <Reference Name = "System.Data" AssemblyName = "System.Data" HintPath = "G:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.Data.dll" /> <Reference Name = "System.XML" AssemblyName = "System.Xml" HintPath = "G:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.XML.dll" /> <Reference Name = "Adapdev.UnitTest.Core" Project = "{B8592DE8-C10B-4ACB-A422-919C02C04B05}" 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 = "TestDriven.Framework" AssemblyName = "TestDriven.Framework" HintPath = "..\..\lib\TestDriven.Framework.dll" /> </References> </Build> <Files> <Include> <File RelPath = "AdapdevAssemblyInfo.cs" Link = "..\AdapdevAssemblyInfo.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "AdapdevTestRunner.cs" SubType = "Code" BuildAction = "Compile" /> </Include> </Files> </CSHARP> </VisualStudioProject> |
From: Sean M. <int...@us...> - 2005-11-16 07:02:03
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.Tests/Reflection In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.Tests/Reflection Added Files: ClassAccessorCacheTest.cs ClassAccessorTest.cs FieldAccessorTest.cs FieldAccessorTestObject.cs PropertyAccessorTest.cs PropertyAccessorTestObject.cs Log Message: --- NEW FILE: FieldAccessorTestObject.cs --- using System; namespace Adapdev.Reflection.Tests { using System.Collections; /// <summary> /// Summary description for FieldAccessorthis. /// </summary> public class FieldAccessorTestObject { private static readonly int TEST_INTEGER = 319; private static readonly string TEST_STRING = "Test string."; private static readonly sbyte TEST_SBYTE = 12; private static readonly byte TEST_BYTE = 234; private static readonly char TEST_CHAR = 'a'; private static readonly short TEST_SHORT = -673; private static readonly ushort TEST_USHORT = 511; private static readonly long TEST_LONG = 8798798798; private static readonly ulong TEST_ULONG = 918297981798; private static readonly bool TEST_BOOL = false; private static readonly double TEST_DOUBLE = 789.12; private static readonly float TEST_FLOAT = 123.12F; private static readonly DateTime TEST_DATETIME = new DateTime(2005, 3, 6); private static readonly decimal TEST_DECIMAL = new decimal(98798798.1221); private static readonly int[] TEST_ARRAY = new int[]{1,2,3}; public FieldAccessorTestObject() { this.mInt = TEST_INTEGER; this.mString = TEST_STRING; this.mBool = TEST_BOOL; this.mByte = TEST_BYTE; this.mChar = TEST_CHAR; this.mDateTime = TEST_DATETIME; this.mDecimal = TEST_DECIMAL; this.mDouble = TEST_DOUBLE; this.mFloat = TEST_FLOAT; this.mLong = TEST_LONG; this.mSbyte = TEST_SBYTE; this.mShort = TEST_SHORT; this.mUlong = TEST_ULONG; this.mUshort = TEST_USHORT; this.mList = new ArrayList(TEST_ARRAY); } public int Int { get { return this.mInt; } } public string String { get { return this.mString; } } public sbyte Sbyte { get { return this.mSbyte; } } public byte Byte { get { return this.mByte; } } public char Char { get { return this.mChar; } } public short Short { get { return this.mShort; } } public ushort UShort { get { return this.mUshort; } } public long Long { get { return this.mLong; } } public ulong ULong { get { return this.mUlong; } } public bool Bool { get { return this.mBool; } } public double Double { get { return this.mDouble; } } public float Float { get { return this.mFloat; } } public DateTime DateTime { get { return this.mDateTime; } } public decimal Decimal { get { return this.mDecimal; } } public IList List { get { return this.mList; } } public int ReadOnlyInt { get { return this.mReadOnlyInt; } } public int WriteOnlyInt { set { this.mWriteOnlyInt = value; } } public int mInt; public string mString; public sbyte mSbyte; public byte mByte; public char mChar; public short mShort; public ushort mUshort; public long mLong; public ulong mUlong; public bool mBool; public double mDouble; public float mFloat; public DateTime mDateTime; public decimal mDecimal; public IList mList; public int mReadOnlyInt = 0; public int mWriteOnlyInt; } } --- NEW FILE: ClassAccessorCacheTest.cs --- using System; using NUnit.Framework; using Adapdev.Reflection; namespace Adapdev.Reflection.Tests { /// <summary> /// Summary description for IValidatable. /// </summary> /// [TestFixture] public class ClassAccessorCacheTest { [SetUp] public void Clear() { ClassAccessorCache.Clear(); } [Test] public void GetByType() { ClassAccessor c = ClassAccessorCache.Get(typeof(PropertyAccessorTestObject)); Assert.IsNotNull(c); Assert.AreEqual(typeof(PropertyAccessorTestObject), c.Type); } [Test] public void GetByObject() { PropertyAccessorTestObject o = new PropertyAccessorTestObject(); ClassAccessor c = ClassAccessorCache.Get(o); Assert.IsNotNull(c); Assert.AreEqual(o.GetType(), c.Type); } [Test] public void Count() { PropertyAccessorTestObject o = new PropertyAccessorTestObject(); ClassAccessor c = ClassAccessorCache.Get(o); Assert.AreEqual(1, ClassAccessorCache.Count); } [Test] public void Remove() { PropertyAccessorTestObject o = new PropertyAccessorTestObject(); ClassAccessor c = ClassAccessorCache.Get(o); Assert.AreEqual(1, ClassAccessorCache.Count); ClassAccessorCache.Remove(c.Type); Assert.AreEqual(0, ClassAccessorCache.Count); } [Test] public void ShowToString() { PropertyAccessorTestObject o = new PropertyAccessorTestObject(); ClassAccessor c = ClassAccessorCache.Get(o); c.LoadAllProperties(); Console.WriteLine(ClassAccessorCache.ToString()); } } } --- NEW FILE: PropertyAccessorTest.cs --- // // Author: James Nies // Date: 3/22/2005 // Description: This class is a NUnit test for the PropertyAccessor class and // requires the NUnit framework. // // *** This code was written by James Nies and has been provided to you, *** // *** free of charge, for your use. I assume no responsibility for any *** // *** undesired events resulting from the use of this code or the *** // *** information that has been provided with it . *** // using System; using System.Collections; using System.Reflection; using NUnit.Framework; using Adapdev.Reflection; namespace Adapdev.Reflection.Tests { /// <summary> /// Test fixture for the PropertyAccessor class. /// </summary> [TestFixture] public class PropertyAccessorTest { #region Test Constants private static readonly int TEST_INTEGER = 319; private static readonly string TEST_STRING = "Test string."; private static readonly sbyte TEST_SBYTE = 12; private static readonly byte TEST_BYTE = 234; private static readonly char TEST_CHAR = 'a'; private static readonly short TEST_SHORT = -673; private static readonly ushort TEST_USHORT = 511; private static readonly long TEST_LONG = 8798798798; private static readonly ulong TEST_ULONG = 918297981798; private static readonly bool TEST_BOOL = false; private static readonly double TEST_DOUBLE = 789.12; private static readonly float TEST_FLOAT = 123.12F; private static readonly DateTime TEST_DATETIME = new DateTime(2005, 3, 6); private static readonly decimal TEST_DECIMAL = new decimal(98798798.1221); private static readonly int[] TEST_ARRAY = new int[]{1,2,3}; #endregion Test Constants #region Test Get And Set [Test] public void TestGetInteger() { PropertyAccessor propertyAccessor = new PropertyAccessor(typeof(PropertyAccessorTestObject), "Int"); PropertyAccessorTestObject testObject = this.CreateTestObject(); Assert.AreEqual(testObject.Int, propertyAccessor.Get(testObject)); } [Test] public void TestSetInteger() { PropertyAccessor propertyAccessor = new PropertyAccessor(typeof(PropertyAccessorTestObject), "Int"); PropertyAccessorTestObject testObject = this.CreateTestObject(); int testInt = 2345; propertyAccessor.Set(testObject, testInt); Assert.AreEqual(testInt, testObject.Int); } [Test] public void TestGetString() { PropertyAccessor propertyAccessor = new PropertyAccessor(typeof(PropertyAccessorTestObject), "String"); PropertyAccessorTestObject testObject = this.CreateTestObject(); Assert.AreEqual(testObject.String, propertyAccessor.Get(testObject)); } [Test] public void TestSetString() { PropertyAccessor propertyAccessor = new PropertyAccessor(typeof(PropertyAccessorTestObject), "String"); PropertyAccessorTestObject testObject = this.CreateTestObject(); string testString = "New string"; propertyAccessor.Set(testObject, testString); Assert.AreEqual(testString, testObject.String); } [Test] public void TestGetBool() { PropertyAccessor propertyAccessor = new PropertyAccessor(typeof(PropertyAccessorTestObject), "Bool"); PropertyAccessorTestObject testObject = this.CreateTestObject(); Assert.AreEqual(testObject.Bool, propertyAccessor.Get(testObject)); } [Test] public void TestSetBool() { PropertyAccessor propertyAccessor = new PropertyAccessor(typeof(PropertyAccessorTestObject), "Bool"); PropertyAccessorTestObject testObject = this.CreateTestObject(); bool testBool = true; propertyAccessor.Set(testObject, testBool); Assert.AreEqual(testBool, testObject.Bool); } [Test] public void TestGetByte() { PropertyAccessor propertyAccessor = new PropertyAccessor(typeof(PropertyAccessorTestObject), "Byte"); PropertyAccessorTestObject testObject = this.CreateTestObject(); Assert.AreEqual(testObject.Byte, propertyAccessor.Get(testObject)); } [Test] public void TestSetByte() { PropertyAccessor propertyAccessor = new PropertyAccessor(typeof(PropertyAccessorTestObject), "Byte"); PropertyAccessorTestObject testObject = this.CreateTestObject(); byte testByte = 16; propertyAccessor.Set(testObject, testByte); Assert.AreEqual(testByte, testObject.Byte); } [Test] public void TestGetChar() { PropertyAccessor propertyAccessor = new PropertyAccessor(typeof(PropertyAccessorTestObject), "Char"); PropertyAccessorTestObject testObject = this.CreateTestObject(); Assert.AreEqual(testObject.Char, propertyAccessor.Get(testObject)); } [Test] public void TestSetChar() { PropertyAccessor propertyAccessor = new PropertyAccessor(typeof(PropertyAccessorTestObject), "Char"); PropertyAccessorTestObject testObject = this.CreateTestObject(); char testChar = 'Z'; propertyAccessor.Set(testObject, testChar); Assert.AreEqual(testChar, testObject.Char); } [Test] public void TestGetDateTime() { PropertyAccessor propertyAccessor = new PropertyAccessor(typeof(PropertyAccessorTestObject), "DateTime"); PropertyAccessorTestObject testObject = this.CreateTestObject(); Assert.AreEqual(testObject.DateTime, propertyAccessor.Get(testObject)); } [Test] public void TestSetDateTime() { PropertyAccessor propertyAccessor = new PropertyAccessor(typeof(PropertyAccessorTestObject), "DateTime"); PropertyAccessorTestObject testObject = this.CreateTestObject(); DateTime testDateTime = DateTime.Now; propertyAccessor.Set(testObject, testDateTime); Assert.AreEqual(testDateTime, testObject.DateTime); } [Test] public void TestGetDecimal() { PropertyAccessor propertyAccessor = new PropertyAccessor(typeof(PropertyAccessorTestObject), "Decimal"); PropertyAccessorTestObject testObject = this.CreateTestObject(); Assert.AreEqual(testObject.Decimal, propertyAccessor.Get(testObject)); } [Test] public void TestSetDecimal() { PropertyAccessor propertyAccessor = new PropertyAccessor(typeof(PropertyAccessorTestObject), "Decimal"); PropertyAccessorTestObject testObject = this.CreateTestObject(); decimal testDecimal = new decimal(123123.12); propertyAccessor.Set(testObject, testDecimal); Assert.AreEqual(testDecimal, testObject.Decimal); } [Test] public void TestGetDouble() { PropertyAccessor propertyAccessor = new PropertyAccessor(typeof(PropertyAccessorTestObject), "Double"); PropertyAccessorTestObject testObject = this.CreateTestObject(); Assert.AreEqual(testObject.Double, propertyAccessor.Get(testObject)); } [Test] public void TestSetDouble() { PropertyAccessor propertyAccessor = new PropertyAccessor(typeof(PropertyAccessorTestObject), "Double"); PropertyAccessorTestObject testObject = this.CreateTestObject(); double testDouble = 9999.99; propertyAccessor.Set(testObject, testDouble); Assert.AreEqual(testDouble, testObject.Double); } [Test] public void TestGetFloat() { PropertyAccessor propertyAccessor = new PropertyAccessor(typeof(PropertyAccessorTestObject), "Float"); PropertyAccessorTestObject testObject = this.CreateTestObject(); Assert.AreEqual(testObject.Float, propertyAccessor.Get(testObject)); } [Test] public void TestSetFloat() { PropertyAccessor propertyAccessor = new PropertyAccessor(typeof(PropertyAccessorTestObject), "Float"); PropertyAccessorTestObject testObject = this.CreateTestObject(); float testFloat = 1982.12F; propertyAccessor.Set(testObject, testFloat); Assert.AreEqual(testFloat, testObject.Float); } [Test] public void TestGetLong() { PropertyAccessor propertyAccessor = new PropertyAccessor(typeof(PropertyAccessorTestObject), "Long"); PropertyAccessorTestObject testObject = this.CreateTestObject(); Assert.AreEqual(testObject.Long, propertyAccessor.Get(testObject)); } [Test] public void TestSetLong() { PropertyAccessor propertyAccessor = new PropertyAccessor(typeof(PropertyAccessorTestObject), "Long"); PropertyAccessorTestObject testObject = this.CreateTestObject(); long testLong = 92873987232; propertyAccessor.Set(testObject, testLong); Assert.AreEqual(testLong, testObject.Long); } [Test] public void TestGetSbyte() { PropertyAccessor propertyAccessor = new PropertyAccessor(typeof(PropertyAccessorTestObject), "Sbyte"); PropertyAccessorTestObject testObject = this.CreateTestObject(); Assert.AreEqual(testObject.Sbyte, propertyAccessor.Get(testObject)); } [Test] public void TestSetSbyte() { PropertyAccessor propertyAccessor = new PropertyAccessor(typeof(PropertyAccessorTestObject), "Sbyte"); PropertyAccessorTestObject testObject = this.CreateTestObject(); sbyte testSbyte = 19; propertyAccessor.Set(testObject, testSbyte); Assert.AreEqual(testSbyte, testObject.Sbyte); } [Test] public void TestGetShort() { PropertyAccessor propertyAccessor = new PropertyAccessor(typeof(PropertyAccessorTestObject), "Short"); PropertyAccessorTestObject testObject = this.CreateTestObject(); Assert.AreEqual(testObject.Short, propertyAccessor.Get(testObject)); } [Test] public void TestSetShort() { PropertyAccessor propertyAccessor = new PropertyAccessor(typeof(PropertyAccessorTestObject), "Short"); PropertyAccessorTestObject testObject = this.CreateTestObject(); short testShort = 2378; propertyAccessor.Set(testObject, testShort); Assert.AreEqual(testShort, testObject.Short); } [Test] public void TestGetULong() { PropertyAccessor propertyAccessor = new PropertyAccessor(typeof(PropertyAccessorTestObject), "ULong"); PropertyAccessorTestObject testObject = this.CreateTestObject(); Assert.AreEqual(testObject.ULong, propertyAccessor.Get(testObject)); } [Test] public void TestSetULong() { PropertyAccessor propertyAccessor = new PropertyAccessor(typeof(PropertyAccessorTestObject), "ULong"); PropertyAccessorTestObject testObject = this.CreateTestObject(); ulong testULong = 29837987298; propertyAccessor.Set(testObject, testULong); Assert.AreEqual(testULong, testObject.ULong); } [Test] public void TestGetUShort() { PropertyAccessor propertyAccessor = new PropertyAccessor(typeof(PropertyAccessorTestObject), "UShort"); PropertyAccessorTestObject testObject = this.CreateTestObject(); Assert.AreEqual(testObject.UShort, propertyAccessor.Get(testObject)); } [Test] public void TestSetUShort() { PropertyAccessor propertyAccessor = new PropertyAccessor(typeof(PropertyAccessorTestObject), "UShort"); PropertyAccessorTestObject testObject = this.CreateTestObject(); ushort testUShort = 789; propertyAccessor.Set(testObject, testUShort); Assert.AreEqual(testUShort, testObject.UShort); } [Test] public void TestGetList() { PropertyAccessor propertyAccessor = new PropertyAccessor(typeof(PropertyAccessorTestObject), "List"); PropertyAccessorTestObject testObject = this.CreateTestObject(); Assert.AreEqual(testObject.List, propertyAccessor.Get(testObject)); } [Test] public void TestSetList() { PropertyAccessor propertyAccessor = new PropertyAccessor(typeof(PropertyAccessorTestObject), "List"); PropertyAccessorTestObject testObject = this.CreateTestObject(); ArrayList list = new ArrayList(new int[]{4,5,6}); propertyAccessor.Set(testObject, list); Assert.AreEqual(list, testObject.List); } #endregion Test Get And Set [Test] public void TestTargetType() { PropertyAccessor propertyAccessor = new PropertyAccessor(typeof(PropertyAccessorTestObject), "Int"); Assert.AreEqual(typeof(PropertyAccessorTestObject), propertyAccessor.TargetType); } [Test] public void TestPropertyType() { PropertyAccessor propertyAccessor = new PropertyAccessor(typeof(PropertyAccessorTestObject), "Int"); Assert.AreEqual(typeof(int), propertyAccessor.PropertyType); } [Test] public void TestCanRead() { PropertyAccessor propertyAccessor; // // Can read // propertyAccessor = new PropertyAccessor(typeof(PropertyAccessorTestObject), "Int"); Assert.IsTrue(propertyAccessor.CanRead); // // Cannot read // propertyAccessor = new PropertyAccessor(typeof(PropertyAccessorTestObject), "WriteOnlyInt"); Assert.IsFalse(propertyAccessor.CanRead); } [Test] public void TestCanWrite() { PropertyAccessor propertyAccessor; // // Can read // propertyAccessor = new PropertyAccessor(typeof(PropertyAccessorTestObject), "Int"); Assert.IsTrue(propertyAccessor.CanWrite); // // Cannot write // propertyAccessor = new PropertyAccessor(typeof(PropertyAccessorTestObject), "ReadOnlyInt"); Assert.IsFalse(propertyAccessor.CanWrite); } [Test] [ExpectedException(typeof(PropertyAccessorException), "Property \"ReadOnlyInt\" does not have a set method.")] public void TestSetNotSupported() { PropertyAccessor propertyAccessor = new PropertyAccessor(typeof(PropertyAccessorTestObject), "ReadOnlyInt"); PropertyAccessorTestObject testObject = this.CreateTestObject(); // // Attempt to set a propert that is read only // propertyAccessor.Set(testObject, 123); } [Test] [ExpectedException(typeof(PropertyAccessorException), "Property \"WriteOnlyInt\" does not have a get method.")] public void TestGetNotSupported() { PropertyAccessor propertyAccessor = new PropertyAccessor(typeof(PropertyAccessorTestObject), "WriteOnlyInt"); PropertyAccessorTestObject testObject = this.CreateTestObject(); // // Attempt read a write-only property // int test = (int)propertyAccessor.Get(testObject); } [Test] [ExpectedException(typeof(PropertyAccessorException), "Property \"NonExistantProperty\" does not exist for " + "type Adapdev.Reflection.Tests.PropertyAccessorTestObject.")] public void TestNonExistantProperty() { PropertyAccessor propertyAccessor = new PropertyAccessor(typeof(PropertyAccessorTestObject), "NonExistantProperty"); } [Test] public void TestGetIntegerPerformance() { const int TEST_ITERATIONS = 1000000; PropertyAccessorTestObject testObject = this.CreateTestObject(); int test; // // Property accessor // DateTime start = DateTime.Now; PropertyAccessor propertyAccessor = new PropertyAccessor(typeof(PropertyAccessorTestObject), "Int"); for(int i = 0; i < TEST_ITERATIONS; i++) { test = (int)propertyAccessor.Get(testObject); } DateTime end = DateTime.Now; TimeSpan time = end - start; double propertyAccessorMs = time.TotalMilliseconds; // // Direct access // start = DateTime.Now; for(int i = 0; i < TEST_ITERATIONS; i++) { test = testObject.Int; } end = DateTime.Now; time = end - start; double directAccessMs = time.TotalMilliseconds; // // Reflection // start = DateTime.Now; Type type = testObject.GetType(); for(int i = 0; i < TEST_ITERATIONS; i++) { test = (int)type.InvokeMember("Int", BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.Instance, null, testObject, null); } end = DateTime.Now; time = end - start; double reflectionMs = time.TotalMilliseconds; // // Print results // Console.WriteLine( TEST_ITERATIONS.ToString() + " property gets on integer..." + "\nDirect access ms: \t\t\t\t\t" + directAccessMs.ToString() + "\nPropertyAccessor (Reflection.Emit) ms: \t\t" + propertyAccessorMs.ToString() + "\nReflection ms: \t\t\t\t\t" + reflectionMs.ToString()); } [Test] public void TestSetIntegerPerformance() { const int TEST_ITERATIONS = 1000000; const int TEST_VALUE = 123; PropertyAccessorTestObject testObject = this.CreateTestObject(); // // Property accessor // DateTime start = DateTime.Now; PropertyAccessor propertyAccessor = new PropertyAccessor(typeof(PropertyAccessorTestObject), "Int"); for(int i = 0; i < TEST_ITERATIONS; i++) { propertyAccessor.Set(testObject, TEST_VALUE); } DateTime end = DateTime.Now; TimeSpan time = end - start; double propertyAccessorMs = time.TotalMilliseconds; // // Direct access // start = DateTime.Now; for(int i = 0; i < TEST_ITERATIONS; i++) { testObject.Int = TEST_VALUE; } end = DateTime.Now; time = end - start; double directAccessMs = time.TotalMilliseconds; // // Reflection // start = DateTime.Now; Type type = testObject.GetType(); for(int i = 0; i < TEST_ITERATIONS; i++) { type.InvokeMember("Int", BindingFlags.Public | BindingFlags.SetProperty | BindingFlags.Instance, null, testObject, new object[]{TEST_VALUE}); } end = DateTime.Now; time = end - start; double reflectionMs = time.TotalMilliseconds; // // Print results // Console.WriteLine( TEST_ITERATIONS.ToString() + " property sets on integer..." + "\nDirect access ms: \t\t\t\t\t" + directAccessMs.ToString() + "\nPropertyAccessor (Reflection.Emit) ms: \t\t" + propertyAccessorMs.ToString() + "\nReflection ms: \t\t\t\t\t" + reflectionMs.ToString()); } [Test] public void TestGetStringPerformance() { const int TEST_ITERATIONS = 1000000; PropertyAccessorTestObject testObject = this.CreateTestObject(); string test; // // Property accessor // DateTime start = DateTime.Now; PropertyAccessor propertyAccessor = new PropertyAccessor(typeof(PropertyAccessorTestObject), "String"); for(int i = 0; i < TEST_ITERATIONS; i++) { test = (string)propertyAccessor.Get(testObject); } DateTime end = DateTime.Now; TimeSpan time = end - start; double propertyAccessorMs = time.TotalMilliseconds; // // Direct access // start = DateTime.Now; for(int i = 0; i < TEST_ITERATIONS; i++) { test = testObject.String; } end = DateTime.Now; time = end - start; double directAccessMs = time.TotalMilliseconds; // // Reflection // start = DateTime.Now; Type type = testObject.GetType(); for(int i = 0; i < TEST_ITERATIONS; i++) { test = (string)type.InvokeMember("String", BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.Instance, null, testObject, null); } end = DateTime.Now; time = end - start; double reflectionMs = time.TotalMilliseconds; // // Print results // Console.WriteLine( TEST_ITERATIONS.ToString() + " property gets on string..." + "\nDirect access ms: \t\t\t\t\t" + directAccessMs.ToString() + "\nPropertyAccessor (Reflection.Emit) ms: \t\t" + propertyAccessorMs.ToString() + "\nReflection ms: \t\t\t\t\t" + reflectionMs.ToString()); } [Test] public void TestSetStringPerformance() { const int TEST_ITERATIONS = 1000000; const string TEST_VALUE = "Test"; PropertyAccessorTestObject testObject = this.CreateTestObject(); // // Property accessor // DateTime start = DateTime.Now; PropertyAccessor propertyAccessor = new PropertyAccessor(typeof(PropertyAccessorTestObject), "String"); for(int i = 0; i < TEST_ITERATIONS; i++) { propertyAccessor.Set(testObject, TEST_VALUE); } DateTime end = DateTime.Now; TimeSpan time = end - start; double propertyAccessorMs = time.TotalMilliseconds; // // Direct access // start = DateTime.Now; for(int i = 0; i < TEST_ITERATIONS; i++) { testObject.String = TEST_VALUE; } end = DateTime.Now; time = end - start; double directAccessMs = time.TotalMilliseconds; // // Reflection // start = DateTime.Now; Type type = testObject.GetType(); for(int i = 0; i < TEST_ITERATIONS; i++) { type.InvokeMember("String", BindingFlags.Public | BindingFlags.SetProperty | BindingFlags.Instance, null, testObject, new object[]{TEST_VALUE}); } end = DateTime.Now; time = end - start; double reflectionMs = time.TotalMilliseconds; // // Print results // Console.WriteLine( TEST_ITERATIONS.ToString() + " property sets on string..." + "\nDirect access ms: \t\t\t\t\t" + directAccessMs.ToString() + "\nPropertyAccessor (Reflection.Emit) ms: \t\t" + propertyAccessorMs.ToString() + "\nReflection ms: \t\t\t\t\t" + reflectionMs.ToString()); } #region Private Methods private PropertyAccessorTestObject CreateTestObject() { PropertyAccessorTestObject testObject = new PropertyAccessorTestObject(); testObject.Int = TEST_INTEGER; testObject.String = TEST_STRING; testObject.Bool = TEST_BOOL; testObject.Byte = TEST_BYTE; testObject.Char = TEST_CHAR; testObject.DateTime = TEST_DATETIME; testObject.Decimal = TEST_DECIMAL; testObject.Double = TEST_DOUBLE; testObject.Float = TEST_FLOAT; testObject.Long = TEST_LONG; testObject.Sbyte = TEST_SBYTE; testObject.Short = TEST_SHORT; testObject.ULong = TEST_ULONG; testObject.UShort = TEST_USHORT; testObject.List = new ArrayList(TEST_ARRAY); return testObject; } #endregion Private Methods } } --- NEW FILE: FieldAccessorTest.cs --- // // Author: James Nies // Date: 3/22/2005 // Description: This class is a NUnit test for the FieldAccessor class and // requires the NUnit framework. // // *** This code was written by James Nies and has been provided to you, *** // *** free of charge, for your use. I assume no responsibility for any *** // *** undesired events resulting from the use of this code or the *** // *** information that has been provided with it . *** // using System; using System.Collections; using System.Reflection; using NUnit.Framework; using Adapdev.Reflection; namespace Adapdev.Reflection.Tests { /// <summary> /// Test fixture for the FieldAccessor class. /// </summary> [TestFixture] public class FieldAccessorTest { #region Test Get And Set [Test] public void TestGetInteger() { FieldAccessor FieldAccessor = new FieldAccessor(typeof(FieldAccessorTestObject), "mInt"); FieldAccessorTestObject testObject = this.CreateTestObject(); Assert.AreEqual(testObject.Int, FieldAccessor.Get(testObject)); } [Test] public void TestSetInteger() { FieldAccessor FieldAccessor = new FieldAccessor(typeof(FieldAccessorTestObject), "mInt"); FieldAccessorTestObject testObject = this.CreateTestObject(); int testInt = 2345; FieldAccessor.Set(testObject, testInt); Assert.AreEqual(testInt, testObject.Int); } [Test] public void TestGetString() { FieldAccessor FieldAccessor = new FieldAccessor(typeof(FieldAccessorTestObject), "mString"); FieldAccessorTestObject testObject = this.CreateTestObject(); Assert.AreEqual(testObject.String, FieldAccessor.Get(testObject)); } [Test] public void TestSetString() { FieldAccessor FieldAccessor = new FieldAccessor(typeof(FieldAccessorTestObject), "mString"); FieldAccessorTestObject testObject = this.CreateTestObject(); string testString = "New string"; FieldAccessor.Set(testObject, testString); Assert.AreEqual(testString, testObject.String); } [Test] public void TestGetBool() { FieldAccessor FieldAccessor = new FieldAccessor(typeof(FieldAccessorTestObject), "mBool"); FieldAccessorTestObject testObject = this.CreateTestObject(); Assert.AreEqual(testObject.Bool, FieldAccessor.Get(testObject)); } [Test] public void TestSetBool() { FieldAccessor FieldAccessor = new FieldAccessor(typeof(FieldAccessorTestObject), "mBool"); FieldAccessorTestObject testObject = this.CreateTestObject(); bool testBool = true; FieldAccessor.Set(testObject, testBool); Assert.AreEqual(testBool, testObject.Bool); } [Test] public void TestGetByte() { FieldAccessor FieldAccessor = new FieldAccessor(typeof(FieldAccessorTestObject), "mByte"); FieldAccessorTestObject testObject = this.CreateTestObject(); Assert.AreEqual(testObject.Byte, FieldAccessor.Get(testObject)); } [Test] public void TestSetByte() { FieldAccessor FieldAccessor = new FieldAccessor(typeof(FieldAccessorTestObject), "mByte"); FieldAccessorTestObject testObject = this.CreateTestObject(); byte testByte = 16; FieldAccessor.Set(testObject, testByte); Assert.AreEqual(testByte, testObject.Byte); } [Test] public void TestGetChar() { FieldAccessor FieldAccessor = new FieldAccessor(typeof(FieldAccessorTestObject), "mChar"); FieldAccessorTestObject testObject = this.CreateTestObject(); Assert.AreEqual(testObject.Char, FieldAccessor.Get(testObject)); } [Test] public void TestSetChar() { FieldAccessor FieldAccessor = new FieldAccessor(typeof(FieldAccessorTestObject), "mChar"); FieldAccessorTestObject testObject = this.CreateTestObject(); char testChar = 'Z'; FieldAccessor.Set(testObject, testChar); Assert.AreEqual(testChar, testObject.Char); } [Test] public void TestGetDateTime() { FieldAccessor FieldAccessor = new FieldAccessor(typeof(FieldAccessorTestObject), "mDateTime"); FieldAccessorTestObject testObject = this.CreateTestObject(); Assert.AreEqual(testObject.DateTime, FieldAccessor.Get(testObject)); } [Test] public void TestSetDateTime() { FieldAccessor FieldAccessor = new FieldAccessor(typeof(FieldAccessorTestObject), "mDateTime"); FieldAccessorTestObject testObject = this.CreateTestObject(); DateTime testDateTime = DateTime.Now; FieldAccessor.Set(testObject, testDateTime); Assert.AreEqual(testDateTime, testObject.DateTime); } [Test] public void TestGetDecimal() { FieldAccessor FieldAccessor = new FieldAccessor(typeof(FieldAccessorTestObject), "mDecimal"); FieldAccessorTestObject testObject = this.CreateTestObject(); Assert.AreEqual(testObject.Decimal, FieldAccessor.Get(testObject)); } [Test] public void TestSetDecimal() { FieldAccessor FieldAccessor = new FieldAccessor(typeof(FieldAccessorTestObject), "mDecimal"); FieldAccessorTestObject testObject = this.CreateTestObject(); decimal testDecimal = new decimal(123123.12); FieldAccessor.Set(testObject, testDecimal); Assert.AreEqual(testDecimal, testObject.Decimal); } [Test] public void TestGetDouble() { FieldAccessor FieldAccessor = new FieldAccessor(typeof(FieldAccessorTestObject), "mDouble"); FieldAccessorTestObject testObject = this.CreateTestObject(); Assert.AreEqual(testObject.Double, FieldAccessor.Get(testObject)); } [Test] public void TestSetDouble() { FieldAccessor FieldAccessor = new FieldAccessor(typeof(FieldAccessorTestObject), "mDouble"); FieldAccessorTestObject testObject = this.CreateTestObject(); double testDouble = 9999.99; FieldAccessor.Set(testObject, testDouble); Assert.AreEqual(testDouble, testObject.Double); } [Test] public void TestGetFloat() { FieldAccessor FieldAccessor = new FieldAccessor(typeof(FieldAccessorTestObject), "mFloat"); FieldAccessorTestObject testObject = this.CreateTestObject(); Assert.AreEqual(testObject.Float, FieldAccessor.Get(testObject)); } [Test] public void TestSetFloat() { FieldAccessor FieldAccessor = new FieldAccessor(typeof(FieldAccessorTestObject), "mFloat"); FieldAccessorTestObject testObject = this.CreateTestObject(); float testFloat = 1982.12F; FieldAccessor.Set(testObject, testFloat); Assert.AreEqual(testFloat, testObject.Float); } [Test] public void TestGetLong() { FieldAccessor FieldAccessor = new FieldAccessor(typeof(FieldAccessorTestObject), "mLong"); FieldAccessorTestObject testObject = this.CreateTestObject(); Assert.AreEqual(testObject.Long, FieldAccessor.Get(testObject)); } [Test] public void TestSetLong() { FieldAccessor FieldAccessor = new FieldAccessor(typeof(FieldAccessorTestObject), "mLong"); FieldAccessorTestObject testObject = this.CreateTestObject(); long testLong = 92873987232; FieldAccessor.Set(testObject, testLong); Assert.AreEqual(testLong, testObject.Long); } [Test] public void TestGetSbyte() { FieldAccessor FieldAccessor = new FieldAccessor(typeof(FieldAccessorTestObject), "mSbyte"); FieldAccessorTestObject testObject = this.CreateTestObject(); Assert.AreEqual(testObject.Sbyte, FieldAccessor.Get(testObject)); } [Test] public void TestSetSbyte() { FieldAccessor FieldAccessor = new FieldAccessor(typeof(FieldAccessorTestObject), "mSbyte"); FieldAccessorTestObject testObject = this.CreateTestObject(); sbyte testSbyte = 19; FieldAccessor.Set(testObject, testSbyte); Assert.AreEqual(testSbyte, testObject.Sbyte); } [Test] public void TestGetShort() { FieldAccessor FieldAccessor = new FieldAccessor(typeof(FieldAccessorTestObject), "mShort"); FieldAccessorTestObject testObject = this.CreateTestObject(); Assert.AreEqual(testObject.Short, FieldAccessor.Get(testObject)); } [Test] public void TestSetShort() { FieldAccessor FieldAccessor = new FieldAccessor(typeof(FieldAccessorTestObject), "mShort"); FieldAccessorTestObject testObject = this.CreateTestObject(); short testShort = 2378; FieldAccessor.Set(testObject, testShort); Assert.AreEqual(testShort, testObject.Short); } [Test] public void TestGetULong() { FieldAccessor FieldAccessor = new FieldAccessor(typeof(FieldAccessorTestObject), "mUlong"); FieldAccessorTestObject testObject = this.CreateTestObject(); Assert.AreEqual(testObject.ULong, FieldAccessor.Get(testObject)); } [Test] public void TestSetULong() { FieldAccessor FieldAccessor = new FieldAccessor(typeof(FieldAccessorTestObject), "mUlong"); FieldAccessorTestObject testObject = this.CreateTestObject(); ulong testULong = 29837987298; FieldAccessor.Set(testObject, testULong); Assert.AreEqual(testULong, testObject.ULong); } [Test] public void TestGetUShort() { FieldAccessor FieldAccessor = new FieldAccessor(typeof(FieldAccessorTestObject), "mUshort"); FieldAccessorTestObject testObject = this.CreateTestObject(); Assert.AreEqual(testObject.UShort, FieldAccessor.Get(testObject)); } [Test] public void TestSetUShort() { FieldAccessor FieldAccessor = new FieldAccessor(typeof(FieldAccessorTestObject), "mUshort"); FieldAccessorTestObject testObject = this.CreateTestObject(); ushort testUShort = 789; FieldAccessor.Set(testObject, testUShort); Assert.AreEqual(testUShort, testObject.UShort); } [Test] public void TestGetList() { FieldAccessor FieldAccessor = new FieldAccessor(typeof(FieldAccessorTestObject), "mList"); FieldAccessorTestObject testObject = this.CreateTestObject(); Assert.AreEqual(testObject.List, FieldAccessor.Get(testObject)); } [Test] public void TestSetList() { FieldAccessor FieldAccessor = new FieldAccessor(typeof(FieldAccessorTestObject), "mList"); FieldAccessorTestObject testObject = this.CreateTestObject(); ArrayList list = new ArrayList(new int[]{4,5,6}); FieldAccessor.Set(testObject, list); Assert.AreEqual(list, testObject.List); } #endregion Test Get And Set [Test] public void TestTargetType() { FieldAccessor FieldAccessor = new FieldAccessor(typeof(FieldAccessorTestObject), "mInt"); Assert.AreEqual(typeof(FieldAccessorTestObject), FieldAccessor.TargetType); } [Test] public void TestPropertyType() { FieldAccessor FieldAccessor = new FieldAccessor(typeof(FieldAccessorTestObject), "mInt"); Assert.AreEqual(typeof(int), FieldAccessor.FieldType); } [Test] public void TestCanRead() { FieldAccessor FieldAccessor; // // Can read // FieldAccessor = new FieldAccessor(typeof(FieldAccessorTestObject), "mInt"); Assert.IsTrue(FieldAccessor.CanRead); // // Cannot read // FieldAccessor = new FieldAccessor(typeof(FieldAccessorTestObject), "mWriteOnlyInt"); Assert.IsFalse(FieldAccessor.CanRead); } [Test] public void TestCanWrite() { FieldAccessor FieldAccessor; // // Can read // FieldAccessor = new FieldAccessor(typeof(FieldAccessorTestObject), "mInt"); Assert.IsTrue(FieldAccessor.CanWrite); // // Cannot write // FieldAccessor = new FieldAccessor(typeof(FieldAccessorTestObject), "ReadOnlyInt"); Assert.IsFalse(FieldAccessor.CanWrite); } [Test] [ExpectedException(typeof(FieldAccessorException), "Property \"ReadOnlyInt\" does not have a set method.")] public void TestSetNotSupported() { FieldAccessor FieldAccessor = new FieldAccessor(typeof(FieldAccessorTestObject), "ReadOnlyInt"); FieldAccessorTestObject testObject = this.CreateTestObject(); // // Attempt to set a propert that is read only // FieldAccessor.Set(testObject, 123); } [Test] [ExpectedException(typeof(FieldAccessorException), "Field \"WriteOnlyInt\" does not have a get method.")] public void TestGetNotSupported() { FieldAccessor FieldAccessor = new FieldAccessor(typeof(FieldAccessorTestObject), "WriteOnlyInt"); FieldAccessorTestObject testObject = this.CreateTestObject(); // // Attempt read a write-only property // int test = (int)FieldAccessor.Get(testObject); } [Test] [ExpectedException(typeof(FieldAccessorException), "Field \"NonExistantProperty\" does not exist for " + "type Adapdev.Reflection.Tests.FieldAccessorTestObject.")] public void TestNonExistantProperty() { FieldAccessor FieldAccessor = new FieldAccessor(typeof(FieldAccessorTestObject), "NonExistantField"); } [Test] public void TestGetIntegerPerformance() { const int TEST_ITERATIONS = 1000000; FieldAccessorTestObject testObject = this.CreateTestObject(); int test; // // Property accessor // DateTime start = DateTime.Now; FieldAccessor FieldAccessor = new FieldAccessor(typeof(FieldAccessorTestObject), "Int"); for(int i = 0; i < TEST_ITERATIONS; i++) { test = (int)FieldAccessor.Get(testObject); } DateTime end = DateTime.Now; TimeSpan time = end - start; double FieldAccessorMs = time.TotalMilliseconds; // // Direct access // start = DateTime.Now; for(int i = 0; i < TEST_ITERATIONS; i++) { test = testObject.Int; } end = DateTime.Now; time = end - start; double directAccessMs = time.TotalMilliseconds; // // Reflection // start = DateTime.Now; Type type = testObject.GetType(); for(int i = 0; i < TEST_ITERATIONS; i++) { test = (int)type.InvokeMember("Int", BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.Instance, null, testObject, null); } end = DateTime.Now; time = end - start; double reflectionMs = time.TotalMilliseconds; // // Print results // Console.WriteLine( TEST_ITERATIONS.ToString() + " property gets on integer..." + "\nDirect access ms: \t\t\t\t\t" + directAccessMs.ToString() + "\nFieldAccessor (Reflection.Emit) ms: \t\t" + FieldAccessorMs.ToString() + "\nReflection ms: \t\t\t\t\t" + reflectionMs.ToString()); } [Test] public void TestSetIntegerPerformance() { const int TEST_ITERATIONS = 1000000; const int TEST_VALUE = 123; FieldAccessorTestObject testObject = this.CreateTestObject(); // // Property accessor // DateTime start = DateTime.Now; FieldAccessor FieldAccessor = new FieldAccessor(typeof(FieldAccessorTestObject), "Int"); for(int i = 0; i < TEST_ITERATIONS; i++) { FieldAccessor.Set(testObject, TEST_VALUE); } DateTime end = DateTime.Now; TimeSpan time = end - start; double FieldAccessorMs = time.TotalMilliseconds; // // Reflection // start = DateTime.Now; Type type = testObject.GetType(); for(int i = 0; i < TEST_ITERATIONS; i++) { type.InvokeMember("Int", BindingFlags.Public | BindingFlags.SetProperty | BindingFlags.Instance, null, testObject, new object[]{TEST_VALUE}); } end = DateTime.Now; time = end - start; double reflectionMs = time.TotalMilliseconds; // // Print results // Console.WriteLine( TEST_ITERATIONS.ToString() + " property sets on integer..." + "\nFieldAccessor (Reflection.Emit) ms: \t\t" + FieldAccessorMs.ToString() + "\nReflection ms: \t\t\t\t\t" + reflectionMs.ToString()); } [Test] public void TestGetStringPerformance() { const int TEST_ITERATIONS = 1000000; FieldAccessorTestObject testObject = this.CreateTestObject(); string test; // // Property accessor // DateTime start = DateTime.Now; FieldAccessor FieldAccessor = new FieldAccessor(typeof(FieldAccessorTestObject), "String"); for(int i = 0; i < TEST_ITERATIONS; i++) { test = (string)FieldAccessor.Get(testObject); } DateTime end = DateTime.Now; TimeSpan time = end - start; double FieldAccessorMs = time.TotalMilliseconds; // // Direct access // start = DateTime.Now; for(int i = 0; i < TEST_ITERATIONS; i++) { test = testObject.String; } end = DateTime.Now; time = end - start; double directAccessMs = time.TotalMilliseconds; // // Reflection // start = DateTime.Now; Type type = testObject.GetType(); for(int i = 0; i < TEST_ITERATIONS; i++) { test = (string)type.InvokeMember("String", BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.Instance, null, testObject, null); } end = DateTime.Now; time = end - start; double reflectionMs = time.TotalMilliseconds; // // Print results // Console.WriteLine( TEST_ITERATIONS.ToString() + " property gets on string..." + "\nDirect access ms: \t\t\t\t\t" + directAccessMs.ToString() + "\nFieldAccessor (Reflection.Emit) ms: \t\t" + FieldAccessorMs.ToString() + "\nReflection ms: \t\t\t\t\t" + reflectionMs.ToString()); } [Test] public void TestSetStringPerformance() { const int TEST_ITERATIONS = 1000000; const string TEST_VALUE = "Test"; FieldAccessorTestObject testObject = this.CreateTestObject(); // // Property accessor // DateTime start = DateTime.Now; FieldAccessor FieldAccessor = new FieldAccessor(typeof(FieldAccessorTestObject), "String"); for(int i = 0; i < TEST_ITERATIONS; i++) { FieldAccessor.Set(testObject, TEST_VALUE); } DateTime end = DateTime.Now; TimeSpan time = end - start; double FieldAccessorMs = time.TotalMilliseconds; // // Reflection // start = DateTime.Now; Type type = testObject.GetType(); for(int i = 0; i < TEST_ITERATIONS; i++) { type.InvokeMember("String", BindingFlags.Public | BindingFlags.SetProperty | BindingFlags.Instance, null, testObject, new object[]{TEST_VALUE}); } end = DateTime.Now; time = end - start; double reflectionMs = time.TotalMilliseconds; // // Print results // Console.WriteLine( TEST_ITERATIONS.ToString() + " property sets on string..." + "\nFieldAccessor (Reflection.Emit) ms: \t\t" + FieldAccessorMs.ToString() + "\nReflection ms: \t\t\t\t\t" + reflectionMs.ToString()); } #region Private Methods private FieldAccessorTestObject CreateTestObject() { return new FieldAccessorTestObject(); } #endregion Private Methods } } --- NEW FILE: PropertyAccessorTestObject.cs --- // // Author: James Nies // Date: 3/22/2005 // Description: Class for testing the PropertyAccessor. // // *** This code was written by James Nies and has been provided to you, *** // *** free of charge, for your use. I assume no responsibility for any *** // *** undesired events resulting from the use of this code or the *** // *** information that has been provided with it . *** // using System; using System.Collections; namespace Adapdev.Reflection.Tests { /// <summary> /// PropertyAccessorTestObject. /// </summary> public class PropertyAccessorTestObject { public PropertyAccessorTestObject() { } public int Int { get { return this.mInt; } set { this.mInt = value; } } public string String { get { return this.mString; } set { this.mString = value; } } public sbyte Sbyte { get { return this.mSbyte; } set { this.mSbyte = value; } } public byte Byte { get { return this.mByte; } set { this.mByte = value; } } public char Char { get { return this.mChar; } set { this.mChar = value; } } public short Short { get { return this.mShort; } set { this.mShort = value; } } public ushort UShort { get { return this.mUshort; } set { this.mUshort = value; } } public long Long { get { return this.mLong; } set { this.mLong = value; } } public ulong ULong { get { return this.mUlong; } set { this.mUlong = value; } } public bool Bool { get { return this.mBool; } set { this.mBool = value; } } public double Double { get { return this.mDouble; } set { this.mDouble = value; } } public float Float { get { return this.mFloat; } set { this.mFloat = value; } } public DateTime DateTime { get { return this.mDateTime; } set { this.mDateTime = value; } } public decimal Decimal { get { return this.mDecimal; } set { this.mDecimal = value; } } public IList List { get { return this.mList; } set { this.mList = value; } } public int ReadOnlyInt { get { return this.mReadOnlyInt; } } public int WriteOnlyInt { set { this.mWriteOnlyInt = value; } } private int mInt; private string mString; private sbyte mSbyte; private byte mByte; private char mChar; private short mShort; private ushort mUshort; private long mLong; private ulong mUlong; private bool mBool; private double mDouble; private float mFloat; private DateTime mDateTime; private decimal mDecimal; private IList mList; private int mReadOnlyInt = 0; private int mWriteOnlyInt; } } --- NEW FILE: ClassAccessorTest.cs --- using System; using NUnit.Framework; using Adapdev.Reflection; namespace Adapdev.Reflection.Tests { /// <summary> /// Summary description for IValidatable. /// </summary> /// [TestFixture] public class ClassAccessorTest { [Test] public void SetAndGet() { PropertyAccessorTestObject o = new PropertyAccessorTestObject(); ClassAccessor c = new ClassAccessor(o); c.SetPropertyValue(o, "Bool", false); c.SetPropertyValue(o, "Int", 3); int i = (int)c.GetPropertyValue(o, "Int"); bool b = (bool)c.GetPropertyValue(o, "Bool"); Assert.AreEqual(3, o.Int, "Int should be 3."); Assert.AreEqual(false, o.Bool, "Bool should be false."); Assert.AreEqual(3, i, "Returned Int should be 3."); Assert.AreEqual(false, b, "Returned Bool should be false."); } [Test] public void LoadAllProperties() { PropertyAccessorTestObject o = new PropertyAccessorTestObject(); ClassAccessor c = new ClassAccessor(o); c.LoadAllProperties(); Console.WriteLine(c); Assert.AreEqual(17, c.PropertyCount, "Should have loaded 17 properties."); } } } |
From: Sean M. <int...@us...> - 2005-11-16 07:02:03
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.Tests/XPath In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.Tests/XPath Added Files: XPathObjectNavigatorTest.cs Log Message: --- NEW FILE: XPathObjectNavigatorTest.cs --- #region license // Bamboo.Prevalence - a .NET object prevalence engine // Copyright (C) 2004 Rodrigo B. de Oliveira // // Based on the original concept and implementation of Prevayler (TM) // by Klaus Wuestefeld. Visit http://www.prevayler.org for details. // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, // and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE // OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // Contact Information // // http://bbooprevalence.sourceforge.net // mailto:rod...@us... #endregion using System; using System.Collections; using System.Collections.Specialized; using System.Xml; using System.Xml.XPath; using NUnit.Framework; using Adapdev.XPath; namespace Adapdev.XPath.Tests { public class Address { string _street; short _number; public Address(string street, short number) { _street = street; _number = number; } public string Street { get { return _street; } } public short Number { get { return _number; } } } public class Product { string _name; StringCollection _categories; public Product(string name) { _name = name; _categories = new StringCollection(); } public string Name { get { return _name; } } public StringCollection Categories { get { return _categories; } } } public class OrderItem { Product _product; int _quantity; public OrderItem(Product product, int quantity) { _product = product; _quantity = quantity; } public Product Product { get { return _product; } } public int Quantity { get { return _quantity; } } } public class Order { Customer _customer; ArrayList _items; public Order(Customer customer) { _customer = customer; _items = new ArrayList(); } public Customer Customer { get { return _customer; } } public OrderItem[] Items { get { return (OrderItem[])_items.ToArray(typeof(OrderItem)); } } public void Add(OrderItem item) { _items.Add(item); } } public class Customer { string _fname; string _lname; Address _address; IDictionary _properties; public string Email; public Customer(string fname, string lname, Address address) { _fname = fname; _lname = lname; _address = address; _properties = new Hashtable(); } public IDictionary Properties { get { return _properties; } } public Address Address { get { return _address; } } public string FirstName { get { return _fname; } } public string LastName { get { return _lname; } } } /// <summary> /// Summary description for Class1. /// </summary> [TestFixture] public class XPathObjectNavigatorTest : Assertion { [Test] public void TestSimpleProperties() { Address address = new Address("Al. Calder�o Branco", 784); Customer customer = new Customer("Rodrigo", "Oliveira", address); XPathObjectNavigator context = new XPathObjectNavigator(customer); XPathNodeIterator i = context.Select("/Customer/Address/Street"); AssertEquals(1, i.Count); AssertEquals(true, i.MoveNext()); AssertEquals(customer.Address.Street, i.Current.Value); AssertEquals(customer.Address.Street, ((XPathObjectNavigator)i.Current).Node); i = context.Select("FirstName"); AssertEquals(1, i.Count); AssertEquals(true, i.MoveNext()); AssertEquals(customer.FirstName, i.Current.Value); i = context.Select("/Customer/LastName"); AssertEquals(true, i.MoveNext()); AssertEquals(customer.LastName, i.Current.Value); } [Test] public void TestIListProperties() { Product p1 = new Product("egg"); Product p2 = new Product("Monty Python Flying Circus Box"); p2.Categories.Add("Silly Stuff"); Customer c1 = new Customer("Rodrigo", "Oliveira", new Address("Al. Ribeir�o Preto", 487)); Customer c2 = new Customer("Marcia", "Longo", new Address("Al. Ribeir�o Preto", 487)); Order o1 = new Order(c1); o1.Add(new OrderItem(p1, 10)); o1.Add(new OrderItem(p2, 1)); Order o2 = new Order(c2); o2.Add(new OrderItem(p1, 15)); o2.Add(new OrderItem(p2, 1)); Order[] orders = new Order[] { o1, o2 }; XPathObjectNavigator navigator = new XPathObjectNavigator(orders, "Orders"); AssertEquals(2, navigator.Select("//Order").Count); AssertEquals(2, navigator.Select("Order").Count); AssertEquals(o1, navigator.SelectObject("Order[1]")); AssertEquals(o2, navigator.SelectObject("Order[2]")); AssertEquals(o1, navigator.SelectObject("//Order[Customer/FirstName='Rodrigo']")); AssertEquals(o2, navigator.SelectObject("//Order[Customer/LastName='Longo']")); XPathNodeIterator i = navigator.Select("//Product[Name='egg']"); AssertEquals(2, i.Count); AssertEquals(true, i.MoveNext()); AssertEquals(p1, ((XPathObjectNavigator)i.Current).Node); AssertEquals(o2.Items[0], navigator.SelectObject("//OrderItem[Quantity>10]")); AssertEquals(p2, navigator.SelectObject("//Product[Categories/String='Silly Stuff']")); } [Test] public void TestIDictionaryProperties() { Customer customer = new Customer("Rodrigo", "Oliveira", new Address("Penny Lane", 64)); customer.Properties["email"] = "rod...@us..."; XPathObjectNavigator navigator = new XPathObjectNavigator(customer); AssertEquals(customer.Properties["email"], navigator.SelectObject("Properties/email")); } [Test] public void TestSelectObjects() { Address address = new Address("Strawberry Street", 45); Customer customer1 = new Customer("Rodrigo", "Oliveira", address); Customer customer2 = new Customer("Marcia", "Longo", address); Customer[] customers = { customer1, customer2 }; XPathObjectNavigator navigator = new XPathObjectNavigator(customers); object[] actual = navigator.SelectObjects("Customer[Address/Number = 45]"); AssertEquals(2, actual.Length); AssertEquals(customer1, actual[0]); AssertEquals(customer2, actual[1]); } [Test] public void TestSelectByField() { Customer customer1 = new Customer("Rodrigo", "Oliveira", new Address("al. Calder�o Branco", 45)); customer1.Email = "rb...@ac..."; XPathObjectNavigator navigator = new XPathObjectNavigator(customer1); AssertSame(customer1.Email, navigator.SelectObject("Email")); AssertSame(customer1, navigator.SelectObject("/Customer[Email='rb...@ac...']")); } } } |
From: Sean M. <int...@us...> - 2005-11-16 07:02:03
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.Tests/Text/Indexing In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.Tests/Text/Indexing Added Files: FullTextSearchTests.cs RegExFilterTest.cs SearchResultTest.cs SpecialCharactersFilterTest.cs StringTokenizerTest.cs TokenAssertions.cs TokenLengthFilterTest.cs WordFilterTest.cs Log Message: --- NEW FILE: TokenAssertions.cs --- #region license // Bamboo.Prevalence - a .NET object prevalence engine // Copyright (C) 2004 Rodrigo B. de Oliveira // // Based on the original concept and implementation of Prevayler (TM) // by Klaus Wuestefeld. Visit http://www.prevayler.org for details. // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, // and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE // OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // Contact Information // // http://bbooprevalence.sourceforge.net // mailto:rod...@us... #endregion using System; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using NUnit.Framework; using Adapdev.Text.Indexing.FullText; using Adapdev.Text.Indexing.FullText.Tokenizers; namespace Adapdev.Text.Indexing.Tests { /// <summary> /// Summary description for TokenAssertions. /// </summary> public class TokenAssertions { public static void AssertTokens(string text, ITokenFilter filter, params Token[] tokens) { AssertTokens(new StringTokenizer(text), filter, tokens); } public static void AssertTokens(ITokenizer tokenizer, ITokenFilter filter, params Token[] tokens) { ITokenizer actual = filter.Clone(tokenizer); foreach (Token expected in tokens) { Assertion.AssertEquals(expected, actual.NextToken()); } } public static void AssertTokens(ITokenizer tokenizer, params Token[] tokens) { foreach (Token expected in tokens) { Assertion.AssertEquals(expected, tokenizer.NextToken()); } } public static void AssertTokenValues(ITokenizer tokenizer, params string[] expectedValues) { foreach (string value in expectedValues) { Assertion.AssertEquals(value, tokenizer.NextToken().Value); } Assertion.AssertNull(tokenizer.NextToken()); } public static void AssertTokenValues(string text, ITokenFilter filter, params string[] expectedValues) { ITokenizer tokenizer = filter.Clone(new StringTokenizer(text)); AssertTokenValues(tokenizer, expectedValues); } public static object SerializeDeserialize(object graph) { BinaryFormatter formatter = new BinaryFormatter(); MemoryStream stream = new MemoryStream(); formatter.Serialize(stream, graph); stream.Position = 0; return formatter.Deserialize(stream); } } } --- NEW FILE: SearchResultTest.cs --- #region license // Bamboo.Prevalence - a .NET object prevalence engine // Copyright (C) 2004 Rodrigo B. de Oliveira // // Based on the original concept and implementation of Prevayler (TM) // by Klaus Wuestefeld. Visit http://www.prevayler.org for details. // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, // and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE // OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // Contact Information // // http://bbooprevalence.sourceforge.net // mailto:rod...@us... #endregion using System; using NUnit.Framework; using Adapdev.Text.Indexing; using Adapdev.Text.Indexing.Records; namespace Adapdev.Text.Indexing.Tests { class AgeFilter : ISearchHitFilter { int _min; int _max; public AgeFilter(int min, int max) { _min = min; _max = max; } public bool Test(SearchHit hit) { int age = (int)hit.Record["Age"]; return (age >= _min && age <= _max); } } class NameComparer : System.Collections.IComparer { public int Compare(object a, object b) { HashtableRecord r1 = (HashtableRecord)a; HashtableRecord r2 = (HashtableRecord)b; return ((IComparable)r1["Name"]).CompareTo(r2["Name"]); } } /// <summary> /// Summary description for SearchResultTest. /// </summary> [TestFixture] public class SearchResultTest : Assertion { HashtableRecord _record1; HashtableRecord _record2; HashtableRecord _record3; SearchResult _result; [SetUp] public void SetUp() { _record1 = CreateRecord("Teresa", 43); _record2 = CreateRecord("M�rcia", 26); _record3 = CreateRecord("Bamboo", 27); _result = new SearchResult(); _result.Add(new SearchHit(_record1)); _result.Add(new SearchHit(_record2)); _result.Add(new SearchHit(_record3)); } [Test] public void TestToRecordArray() { HashtableRecord[] records = (HashtableRecord[])_result.ToRecordArray(typeof(HashtableRecord)); AssertEquals(3, records.Length); AssertSame(_record1, records[0]); AssertSame(_record2, records[1]); AssertSame(_record3, records[2]); } [Test] public void TestSortByField() { _result.SortByField("Name"); AssertSearchHits(_result, _record3, _record2, _record1); _result.SortByField("Age"); AssertSearchHits(_result, _record2, _record3, _record1); } [Test] public void TestSort() { _result.Sort(new NameComparer()); AssertSearchHits(_result, _record3, _record2, _record1); } [Test] public void TestFilter() { AssertSearchHits(_result.Filter(new AgeFilter(25, 28)), _record2, _record3); } [Test] public void TestIntersect() { SearchResult other = new SearchResult(); other.Add(new SearchHit(_record3)); other.Add(new SearchHit(_record1)); AssertSearchHits(_result.Intersect(other), _record1, _record3); other = new SearchResult(); other.Add(new SearchHit(_record2)); AssertSearchHits(_result.Intersect(other), _record2); AssertEquals(0, _result.Intersect(new SearchResult()).Count); AssertSearchHits(_result.Intersect(_result), _record1, _record2, _record3); } [Test] public void TestForEach() { int i=0; IRecord[] expected = { _record1, _record2, _record3 }; foreach (SearchHit hit in _result) { AssertEquals(expected[i++], hit.Record); } } void AssertSearchHits(SearchResult result, params IRecord[] expectedRecords) { AssertEquals(expectedRecords.Length, result.Count); for (int i=0; i<expectedRecords.Length; ++i) { IRecord expected = expectedRecords[i]; IRecord actual = result[i].Record; AssertEquals(string.Format("{0} != {1}", expected["Name"], actual["Name"]), expected, actual); } } HashtableRecord CreateRecord(string name, int age) { HashtableRecord record = new HashtableRecord(); record["Name"] = name; record["Age"] = age; return record; } } } --- NEW FILE: WordFilterTest.cs --- #region license // Bamboo.Prevalence - a .NET object prevalence engine // Copyright (C) 2004 Rodrigo B. de Oliveira // // Based on the original concept and implementation of Prevayler (TM) // by Klaus Wuestefeld. Visit http://www.prevayler.org for details. // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, // and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE // OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // Contact Information // // http://bbooprevalence.sourceforge.net // mailto:rod...@us... #endregion using System; using NUnit.Framework; using Adapdev.Text.Indexing.FullText; using Adapdev.Text.Indexing.FullText.Filters; namespace Adapdev.Text.Indexing.Tests { /// <summary> /// Summary description for WordFilterTest. /// </summary> [TestFixture] public class WordFilterTest : Assertion { [Test] public void TestFilter() { string[] filteredWords = { "de", "com" }; string text = "Bolo de chocolate com calda de morango"; TokenAssertions.AssertTokens(text, new WordFilter(filteredWords), new Token("Bolo", 0), new Token("chocolate", 8), new Token("calda", 22), new Token("morango", 31), null); } [Test] public void TestWordFilterChaining() { string[] filteredWords = { "de", "com" }; string text = "Bolo dé Açafrão com Rúcula"; TokenAssertions.AssertTokens(text, new WordFilter(new SpecialCharactersFilter(), filteredWords), new Token("bolo", 0), new Token("acafrao", 8), new Token("rucula", 20), null ); } } } --- NEW FILE: RegExFilterTest.cs --- #region license // Bamboo.Prevalence - a .NET object prevalence engine // Copyright (C) 2004 Rodrigo B. de Oliveira // // Based on the original concept and implementation of Prevayler (TM) // by Klaus Wuestefeld. Visit http://www.prevayler.org for details. // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, // and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE // OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // Contact Information // // http://bbooprevalence.sourceforge.net // mailto:rod...@us... #endregion using System; using NUnit.Framework; using Adapdev.Text.Indexing.FullText; using Adapdev.Text.Indexing.FullText.Filters; using Adapdev.Text.Indexing.FullText.Tokenizers; namespace Adapdev.Text.Indexing.Tests { /// <summary> /// Summary description for RegExFilterTest. /// </summary> [TestFixture] public class RegExFilterTest { RegexTokenFilter _filter; [SetUp] public void SetUp() { _filter = new RegexTokenFilter(@"[0-9]+\w*"); } [Test] public void TestSerializable() { _filter = (RegexTokenFilter)TokenAssertions.SerializeDeserialize(_filter); TestSimpleRegex(); } [Test] public void TestSimpleRegex() { TokenAssertions.AssertTokens("a token, 100 23 1g 144kg other token", _filter, new Token("a", 0), new Token("token", 2), new Token("other", 25), new Token("token", 31), null ); } } } --- NEW FILE: StringTokenizerTest.cs --- #region license // Bamboo.Prevalence - a .NET object prevalence engine // Copyright (C) 2004 Rodrigo B. de Oliveira // // Based on the original concept and implementation of Prevayler (TM) // by Klaus Wuestefeld. Visit http://www.prevayler.org for details. // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, // and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE // OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // Contact Information // // http://bbooprevalence.sourceforge.net // mailto:rod...@us... #endregion using System; using NUnit.Framework; using Adapdev.Text.Indexing.FullText; using Adapdev.Text.Indexing.FullText.Tokenizers; namespace Adapdev.Text.Indexing.Tests { /// <summary> /// Tests for the StringTokenizer class. /// </summary> [TestFixture] public class StringTokenizerTest : Assertion { [Test] public void TestSimpleStrings() { string text = "a foo Bar a�a\n45\n\n\n"; TokenAssertions.AssertTokens(new StringTokenizer(text), new Token("a", 0), new Token("foo", 2), new Token("Bar", 6), new Token("a�a", 10), new Token("45", 14), null ); TokenAssertions.AssertTokens(new StringTokenizer(""), (Token)null); TokenAssertions.AssertTokens(new StringTokenizer("\n\t "), (Token)null); TokenAssertions.AssertTokens(new StringTokenizer("\n\t a"), new Token("a", 4), null); } [Test] public void TestPunctuation() { string text = "A foo,bar goest! flu? Oh, yes, flu!!! really? yep.\n.\tdidn't think [so..(yep)"; TokenAssertions.AssertTokenValues(new StringTokenizer(text), "A", "foo", "bar", "goest", "flu", "Oh", "yes", "flu", "really", "yep", "didn", "t", "think", "so", "yep" ); } [Test] [ExpectedException(typeof(ArgumentNullException))] public void TestNullValues() { StringTokenizer tokenizer = new StringTokenizer(null); } } } --- NEW FILE: TokenLengthFilterTest.cs --- #region license // Bamboo.Prevalence - a .NET object prevalence engine // Copyright (C) 2004 Rodrigo B. de Oliveira // // Based on the original concept and implementation of Prevayler (TM) // by Klaus Wuestefeld. Visit http://www.prevayler.org for details. // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, // and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE // OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // Contact Information // // http://bbooprevalence.sourceforge.net // mailto:rod...@us... #endregion using System; using NUnit.Framework; using Adapdev.Text.Indexing.FullText; using Adapdev.Text.Indexing.FullText.Filters; namespace Adapdev.Text.Indexing.Tests { /// <summary> /// Summary description for TokenLengthFilterTest. /// </summary> [TestFixture] public class TokenLengthFilterTest { [Test] public void TestFilter() { string text = "a bc dado de o"; TokenAssertions.AssertTokenValues(text, new TokenLengthFilter(1), "a", "bc", "dado", "de", "o" ); TokenAssertions.AssertTokenValues(text, new TokenLengthFilter(2), "bc", "dado", "de" ); TokenAssertions.AssertTokenValues(text, new TokenLengthFilter(3), "dado" ); TokenAssertions.AssertTokenValues(text, new TokenLengthFilter(4), "dado" ); } } } --- NEW FILE: SpecialCharactersFilterTest.cs --- #region license // Bamboo.Prevalence - a .NET object prevalence engine // Copyright (C) 2004 Rodrigo B. de Oliveira // // Based on the original concept and implementation of Prevayler (TM) // by Klaus Wuestefeld. Visit http://www.prevayler.org for details. // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, // and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE // OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // Contact Information // // http://bbooprevalence.sourceforge.net // mailto:rod...@us... #endregion using System; using NUnit.Framework; using Adapdev.Text.Indexing.FullText; using Adapdev.Text.Indexing.FullText.Filters; using Adapdev.Text.Indexing.FullText.Tokenizers; namespace Adapdev.Text.Indexing.Tests { /// <summary> /// Summary description for SpecialCharactersFilterTest. /// </summary> [TestFixture] public class SpecialCharactersFilterTest { [Test] public void TestReplacements() { string text = "áéÃóú calção aviões aiouao"; TokenAssertions.AssertTokens(text, new SpecialCharactersFilter(), new Token("aeiou", 0), new Token("calcao", 6), new Token("avioes", 13), new Token("aiouao", 20), null ); } } } --- NEW FILE: FullTextSearchTests.cs --- #region license // Bamboo.Prevalence - a .NET object prevalence engine // Copyright (C) 2004 Rodrigo B. de Oliveira // // Based on the original concept and implementation of Prevayler (TM) // by Klaus Wuestefeld. Visit http://www.prevayler.org for details. // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, // and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE // OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // Contact Information // // http://bbooprevalence.sourceforge.net // mailto:rod...@us... #endregion using System; using NUnit.Framework; using Adapdev.Text.Indexing; using Adapdev.Text.Indexing.FullText; using Adapdev.Text.Indexing.Records; namespace Adapdev.Text.Indexing.Tests { /// <summary> /// Test cases for the fulltext indexing/search support. /// </summary> [TestFixture] public class FullTextSearchTests : Assertion { IIndex _index; IIndex _multipleFieldIndex; HashtableRecord _record1; HashtableRecord _record2; HashtableRecord _record3; [SetUp] public void SetUp() { FullTextSearchIndex index = new FullTextSearchIndex(); index.Fields.Add("Title"); FullTextSearchIndex multipleFieldIndex = new FullTextSearchIndex(); multipleFieldIndex.Fields.Add("Title"); multipleFieldIndex.Fields.Add("Ingredients"); _index = index; _multipleFieldIndex = multipleFieldIndex; _record1 = new HashtableRecord(); _record1["Title"] = "Bolo de Chocolate"; _record1["Calories"] = 300; _record1["Ingredients"] = "3 colheres de açucar\n1 lata de nescau\nfermento"; _index.Add(_record1); _multipleFieldIndex.Add(_record1); DumpPostings(index.Postings); _record2 = new HashtableRecord(); _record2["Title"] = "Bolo de Açafrão"; _record2["Calories"] = 100; _record2["Ingredients"] = "10 folhas de açafrão\n1 colher de fermento em pó"; _index.Add(_record2); _multipleFieldIndex.Add(_record2); DumpPostings(index.Postings); _record3 = new HashtableRecord(); _record3["Title"] = "Torta de Chocolate"; _record3["Calories"] = 400; _record3["Ingredients"] = "1 lata de nescau\nchocolate granulado\naçucar"; _index.Add(_record3); _multipleFieldIndex.Add(_record3); DumpPostings(index.Postings); } [Test] public void TestClear() { _index.Clear(); AssertEquals(0, ((FullTextSearchIndex)_index).Records.Length); AssertEquals(0, ((FullTextSearchIndex)_index).Postings.Length); AssertSearchContains(_index.Search(new FullTextSearchExpression("chocolate"))); } [Test] public void TestSimpleSearch() { ISearchExpression expression = new FullTextSearchExpression("bolo"); AssertSearchContains(_index.Search(expression), _record1, _record2); expression = new FullTextSearchExpression("chocolate"); AssertSearchContains(_index.Search(expression), _record1, _record3); expression = new FullTextSearchExpression("acafrão"); AssertSearchContains(_index.Search(expression), _record2); expression = new FullTextSearchExpression("bolo AcaFrao"); AssertSearchContains(_index.Search(expression), _record1, _record2); } [Test] public void TestMultiIndexSimpleSearch() { ISearchExpression expression = new FullTextSearchExpression("nescau"); AssertSearchContains(_multipleFieldIndex.Search(expression), _record1, _record3); expression = new FullTextSearchExpression("chocolate"); AssertSearchContains(_multipleFieldIndex.Search(expression), _record1, _record3); expression = new FullTextSearchExpression("fermento"); AssertSearchContains(_multipleFieldIndex.Search(expression), _record1, _record2); } [Test] public void TestIncludeAllSearch() { ISearchExpression expression = new FullTextSearchExpression("Bolo Chocolate", FullTextSearchMode.IncludeAll); AssertSearchContains(_index.Search(expression), _record1); AssertSearchContains(_multipleFieldIndex.Search(expression), _record1); expression = new FullTextSearchExpression("Bolo Açafrão", FullTextSearchMode.IncludeAll); AssertSearchContains(_index.Search(expression), _record2); AssertSearchContains(_multipleFieldIndex.Search(expression), _record2); expression = new FullTextSearchExpression("Torta Chocolate", FullTextSearchMode.IncludeAll); AssertSearchContains(_index.Search(expression), _record3); AssertSearchContains(_multipleFieldIndex.Search(expression), _record3); } [Test] public void TestMultiIndexIncludeAllSearch() { AssertSearchContains( _multipleFieldIndex.Search(new FullTextSearchExpression("bolo nescau", FullTextSearchMode.IncludeAll)), _record1 ); AssertSearchContains( _multipleFieldIndex.Search(new FullTextSearchExpression("torta nescau", FullTextSearchMode.IncludeAll)), _record3 ); AssertSearchContains( _multipleFieldIndex.Search(new FullTextSearchExpression("bolo fermento", FullTextSearchMode.IncludeAll)), _record1, _record2 ); } [Test] public void TestRemove() { _index.Remove(_record1); _multipleFieldIndex.Remove(_record1); AssertSearchContains( _index.Search(new FullTextSearchExpression("bolo chocolate")), _record2, _record3 ); AssertSearchContains( _multipleFieldIndex.Search(new FullTextSearchExpression("açucar")), _record3 ); } [Test] [ExpectedException(typeof(ArgumentException))] public void TestInvalidSearchExpression() { // this search is invalid because // the default filter should only let // pass tokens longer // than 2 characters _index.Search(new FullTextSearchExpression("de")); } [Test] public void TestUpdate() { _record1["Title"] = "Torta de Salsinha"; _index.Update(_record1); _multipleFieldIndex.Update(_record1); ISearchExpression expression = new FullTextSearchExpression("torta salsinha"); AssertSearchContains(_index.Search(expression), _record1, _record3); AssertSearchContains(_multipleFieldIndex.Search(expression), _record1, _record3); } [Test] public void TestIndexSerialization() { _index = TokenAssertions.SerializeDeserialize(_index) as IIndex; FullTextSearchIndex index = _index as FullTextSearchIndex; IRecord[] records = index.Records; AssertEquals(3, records.Length); _record1 = FindByTitle(records, (string)_record1["Title"]); _record2 = FindByTitle(records, (string)_record2["Title"]); _record3 = FindByTitle(records, (string)_record3["Title"]); TestSimpleSearch(); } HashtableRecord FindByTitle(IRecord[] records, string title) { foreach (HashtableRecord record in records) { if (((string)record["Title"]) == title) { return record; } } throw new ArgumentException("Record not found!"); } void AssertSearchContains(SearchResult result, params IRecord[] expected) { foreach (IRecord record in expected) { if (!result.Contains(record)) { Fail(string.Format("Expected record \"{0}\"!", record["Title"])); } } AssertEquals("result.Count", expected.Length, result.Count); } void DumpPostings(Postings[] postings) { System.Diagnostics.Trace.WriteLine("\n**************"); foreach (Postings p in postings) { System.Diagnostics.Trace.WriteLine(p.ToString()); } System.Diagnostics.Trace.WriteLine("**************"); } } } |
From: Sean M. <int...@us...> - 2005-11-16 07:02:03
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.UnitTest.Core.Tests In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.UnitTest.Core.Tests Added Files: Adapdev.UnitTest.Core.Tests.csproj AdapdevLocalTestEngineTest.cs AssemblyInfo.cs NUnitLocalSeparateTestEngineTest.cs NUnitLocalTestEngineTest.cs TestAssemblyTest.cs TestTest.cs Log Message: --- NEW FILE: TestTest.cs --- using System; namespace Adapdev.UnitTest.Core.Tests { /// <summary> /// Summary description for TestTest. /// </summary> public class TestTest { public TestTest() { // // TODO: Add constructor logic here // } } } --- NEW FILE: AssemblyInfo.cs --- using System.Reflection; using System.Runtime.CompilerServices; // // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. // [assembly: AssemblyTitle("")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.*")] // // In order to sign your assembly you must specify a key to use. Refer to the // Microsoft .NET Framework documentation for more information on assembly signing. // // Use the attributes below to control which key is used for signing. // // Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used. // (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be // relative to the project output directory which is // %Project Directory%\obj\<configuration>. For example, if your KeyFile is // located in the project directory, you would specify the AssemblyKeyFile // attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. // [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] [assembly: AssemblyKeyName("")] --- NEW FILE: Adapdev.UnitTest.Core.Tests.csproj --- <VisualStudioProject> <CSHARP ProjectType = "Local" ProductVersion = "7.10.3077" SchemaVersion = "2.0" ProjectGuid = "{D0F97D76-E7A6-4059-B902-F792626A29A8}" > <Build> <Settings ApplicationIcon = "" AssemblyKeyContainerName = "" AssemblyName = "Adapdev.UnitTest.Core.Tests" AssemblyOriginatorKeyFile = "" DefaultClientScript = "JScript" DefaultHTMLPageLayout = "Grid" DefaultTargetSchema = "IE50" DelaySign = "false" OutputType = "Library" PreBuildEvent = "" PostBuildEvent = "xcopy ..\..\..\..\lib\nunit $(TargetDir)\nunit /s /e /y /i
copy ..\..\..\Adapdev.UnitTest.Core.AdapdevTests\bin\Debug\Adapdev.UnitTest.Core.AdapdevTests.dll $(TargetDir)\Adapdev.UnitTest.Core.AdapdevTests.dll" RootNamespace = "Adapdev.UnitTest.Core.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.UnitTest.Core" Project = "{B8592DE8-C10B-4ACB-A422-919C02C04B05}" Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" /> <Reference Name = "Adapdev" Project = "{CC30A321-2569-4B1F-8E1A-781B5509B56D}" Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" /> <Reference Name = "nunit.framework" AssemblyName = "nunit.framework" HintPath = "..\..\lib\nunit.framework.dll" /> </References> </Build> <Files> <Include> <File RelPath = "AdapdevLocalTestEngineTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "AssemblyInfo.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "NUnitLocalSeparateTestEngineTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "NUnitLocalTestEngineTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "TestAssemblyTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "TestTest.cs" SubType = "Code" BuildAction = "Compile" /> </Include> </Files> </CSHARP> </VisualStudioProject> --- NEW FILE: NUnitLocalTestEngineTest.cs --- using System; using Adapdev; using Adapdev.UnitTest; using Adapdev.UnitTest.Core; using NUnit.Framework; namespace Adapdev.UnitTest.Core.Tests { /// <summary> /// Summary description for LocalSeparateTestEngineTest. /// </summary> /// [TestFixture] public class NUnitLocalTestEngineTest { private static readonly string basedir = @AppDomain.CurrentDomain.BaseDirectory; [Test] public void LoadNUnit2_2_2() { Console.WriteLine(AppDomain.CurrentDomain.BaseDirectory); ITestEngine engine = TestEngineFactory.CreateLocal(basedir + @"\nunit\222\nunit.framework.tests.dll"); Assert.IsTrue(engine.GetLoadedAssemblies().Count > 0, "No assemblies loaded."); TestAssembly assembly = engine.GetTestAssembly(); Assert.IsTrue(assembly.GetTestCount() > 0, "No tests loaded."); } [Test] public void RunNUnit2_2_2() { ITestEngine engine = TestEngineFactory.CreateLocal(basedir + @"\nunit\222\nunit.framework.tests.dll"); Assert.IsTrue(engine.GetLoadedAssemblies().Count > 0, "No assemblies loaded."); TestAssembly assembly = engine.GetTestAssembly(); Assert.IsTrue(assembly.GetTestCount() > 0, "No tests loaded."); TestAssemblyResult result = engine.Run(engine.GetTestAssembly()); Assert.AreEqual(300, result.Passed); } } } --- NEW FILE: TestAssemblyTest.cs --- using System; using NUnit.Framework; using Adapdev.UnitTest.Core; namespace Adapdev.UnitTest.Core.Tests { /// <summary> /// Summary description for Class1. /// </summary> /// [TestFixture] public class TestAssemblyTest { [Test] public void GetCount() { // Create the assembly TestAssembly ta = new TestAssembly(); // Create the first TestFixture and // add two tests TestFixture tf1 = new TestFixture(); Test t1 = new Test(); Test t2 = new Test(); t2.RepeatCount = 5; Assert.AreEqual(1, t1.GetTestCount()); Assert.AreEqual(5, t2.GetTestCount()); tf1.AddTest(t1); tf1.AddTest(t2); Assert.AreEqual(6, tf1.GetTestCount()); // Create the second TestFixture and // add two tests TestFixture tf2 = new TestFixture(); Test t3 = new Test(); Test t4 = new Test(); t4.RepeatCount = 5; Assert.AreEqual(1, t3.GetTestCount()); Assert.AreEqual(5, t4.GetTestCount()); tf2.AddTest(t3); tf2.AddTest(t4); Assert.AreEqual(6, tf2.GetTestCount()); ta.AddTestFixture(tf1); ta.AddTestFixture(tf2); // Make sure the total number of tests is correct // Should be 1 + 5 + 1 + 5 = 12 Assert.AreEqual(12, ta.GetTestCount()); // Ignore the second test t2.Ignore = true; Assert.AreEqual(7, ta.GetTestCount()); // Unignore the second test t2.Ignore = false; // Ignore the first test fixture tf1.Ignore = true; Assert.AreEqual(6, ta.GetTestCount()); // Ignore the second test fixture tf2.Ignore = true; Assert.AreEqual(0, ta.GetTestCount()); } } } --- NEW FILE: AdapdevLocalTestEngineTest.cs --- using System; using NUnit.Framework; namespace Adapdev.UnitTest.Core.Tests { /// <summary> /// Summary description for AdapdevLocalTestEngineTest. /// </summary> /// [TestFixture] public class AdapdevLocalTestEngineTest { private static readonly string basedir = @AppDomain.CurrentDomain.BaseDirectory; [Test] public void LoadAdapdev() { using(ITestEngine engine = TestEngineFactory.CreateLocal(basedir + @"\Adapdev.UnitTest.Core.AdapdevTests.dll")) { Assert.IsTrue(engine.GetLoadedAssemblies().Count > 0, "No assemblies loaded."); TestAssembly assembly = engine.GetTestAssembly(); Assert.IsTrue(assembly.GetTestCount() > 0, "No tests loaded."); } } [Test] public void RunAdapdev() { using(ITestEngine engine = TestEngineFactory.CreateLocal(basedir + @"\Adapdev.UnitTest.Core.AdapdevTests.dll")) { Assert.IsTrue(engine.GetLoadedAssemblies().Count > 0, "No assemblies loaded."); TestAssembly assembly = engine.GetTestAssembly(); Assert.IsTrue(assembly.GetTestCount() > 0, "No tests loaded."); TestAssemblyResult result = engine.Run(engine.GetTestAssembly()); Console.WriteLine(new Adapdev.UnitTest.Core.TextFormatter(new TestAssemblyResult[]{result}, true, true, true).GetText()); Assert.AreEqual(20, result.Passed); Assert.AreEqual(2, result.Failed); } } } } --- NEW FILE: NUnitLocalSeparateTestEngineTest.cs --- using System; using Adapdev; using Adapdev.UnitTest; using Adapdev.UnitTest.Core; using NUnit.Framework; namespace Adapdev.UnitTest.Core.Tests { /// <summary> /// Summary description for LocalSeparateTestEngineTest. /// </summary> /// [TestFixture] public class NUnitLocalSeparateTestEngineTest { private static readonly string basedir = @AppDomain.CurrentDomain.BaseDirectory; [Test] public void LoadNUnit2_2_2() { using(ITestEngine engine = TestEngineFactory.CreateLocalSeparate(basedir, basedir + @"\nunit\222\nunit.framework.tests.dll.config", basedir + @"\nunit\222\nunit.framework.tests.dll")) { Assert.IsTrue(engine.GetLoadedAssemblies().Count > 0, "No assemblies loaded."); TestAssembly assembly = engine.GetTestAssembly(); Assert.IsTrue(assembly.GetTestCount() > 0, "No tests loaded."); } } public void LoadNUnit2_2_2WithoutConfigParam() { using(ITestEngine engine = TestEngineFactory.CreateLocalSeparate(basedir, basedir + @"\nunit\222\nunit.framework.tests.dll")) { Assert.AreEqual(basedir + @"\nunit\222\nunit.framework.tests.dll.config", engine.ConfigurationFile, "Configuration file was not automatically detected."); Assert.IsTrue(engine.GetLoadedAssemblies().Count > 0, "No assemblies loaded."); TestAssembly assembly = engine.GetTestAssembly(); Assert.IsTrue(assembly.GetTestCount() > 0, "No tests loaded."); } } [Test] public void RunNUnit2_2_2() { using(ITestEngine engine = TestEngineFactory.CreateLocalSeparate(basedir, basedir + @"\nunit\222\nunit.framework.tests.dll.config", basedir + @"\nunit\222\nunit.framework.tests.dll")) { Assert.IsTrue(engine.GetLoadedAssemblies().Count > 0, "No assemblies loaded."); TestAssembly assembly = engine.GetTestAssembly(); Assert.IsTrue(assembly.GetTestCount() > 0, "No tests loaded."); TestAssemblyResult result = engine.Run(engine.GetTestAssembly()); Assert.AreEqual(302, result.Passed); } } [Test] public void LoadNUnit2_2_0() { using(ITestEngine engine = TestEngineFactory.CreateLocalSeparate(basedir, basedir + @"\nunit\220\nunit.tests.dll.config", basedir + @"\nunit\220\nunit.tests.dll")) { Assert.IsTrue(engine.GetLoadedAssemblies().Count > 0, "No assemblies loaded."); TestAssembly assembly = engine.GetTestAssembly(); Assert.IsTrue(assembly.GetTestCount() > 0, "No tests loaded."); } } public void LoadNUnit2_2_0WithoutConfigParam() { using(ITestEngine engine = TestEngineFactory.CreateLocalSeparate(basedir, basedir + @"\nunit\220\nunit.tests.dll")) { Assert.AreEqual(basedir + @"\nunit\220\nunit.tests.dll.config", engine.ConfigurationFile, "Configuration file was not automatically detected."); Assert.IsTrue(engine.GetLoadedAssemblies().Count > 0, "No assemblies loaded."); TestAssembly assembly = engine.GetTestAssembly(); Assert.IsTrue(assembly.GetTestCount() > 0, "No tests loaded."); } } [Test] public void RunNUnit2_2_0() { using(ITestEngine engine = TestEngineFactory.CreateLocalSeparate(basedir, basedir + @"\nunit\220\nunit.tests.dll.config", basedir + @"\nunit\220\nunit.tests.dll")) { Assert.IsTrue(engine.GetLoadedAssemblies().Count > 0, "No assemblies loaded."); TestAssembly assembly = engine.GetTestAssembly(); Assert.IsTrue(assembly.GetTestCount() > 0, "No tests loaded."); TestAssemblyResult result = engine.Run(engine.GetTestAssembly()); Assert.AreEqual(368, result.Passed); } } } } |
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.UnitTest.Core In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.UnitTest.Core Added Files: AbstractTest.cs AbstractTestEventArgs.cs AbstractTestIteration.cs AbstractTestResult.cs AbstractTestVisitor.cs Adapdev.UnitTest.Core.csproj AssemblyWatcher.cs AutoCommitCommand.cs AutoRollbackCommand.cs BaseTestHelper.cs CompositeAbstractTestIteration.cs ErrorEventArgs.cs IResultFormatter.cs ITestEngine.cs IThreadWorkItemCommand.cs LocalSeparateTestEngine.cs LocalTestEngine.cs RunMethodCommand.cs RunNonThreadedTestCommand.cs RunTestCommand.cs RunTestFixtureCommand.cs RunTestIterationCommand.cs RunThreadedTestCommand.cs Test.cs TestAssembly.cs TestAssemblyEventArgs.cs TestAssemblyIteration.cs TestAssemblyIterationEventArgs.cs TestAssemblyResult.cs TestAssemblyResultEventArgs.cs TestEngineFactory.cs TestEngineType.cs TestEventArgs.cs TestEventDispatcher.cs TestFixture.cs TestFixtureEventArgs.cs TestFixtureIteration.cs TestFixtureIterationEventArg.cs TestFixtureResult.cs TestFixtureResultEventArg.cs TestFramework.cs TestHelper.cs TestHelperEventArgs.cs TestIteration.cs TestIterationEventArgs.cs TestResult.cs TestResultEventArgs.cs TestRunner.cs TestState.cs TestSuite.cs TestSuiteBuilder.cs TestSuiteIteration.cs TestSuiteResult.cs TestSummary.cs TestUnit.cs TextFormatter.cs TransactionType.cs TypeHelper.cs VSProject.cs VSProjectConfig.cs VSProjectConfigCollection.cs XmlFormatter.cs Log Message: --- NEW FILE: TestIterationEventArgs.cs --- #region Copyright / License Information /* Author: Sean McCormack ================================================ Copyright ================================================ Copyright (c) 2004 Adapdev Technologies, LLC ================================================ License ================================================ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ Change History ================================================ III MM/DD/YYYY Change */ #endregion namespace Adapdev.UnitTest.Core { using System; /// <summary> /// Summary description for TestIterationEventArgs. /// </summary> /// [Serializable] public class TestIterationEventArgs : EventArgs { private TestIteration _ti = null; public TestIterationEventArgs(TestIteration ti) { this._ti = ti; } public TestIteration TestIteration { get { return this._ti; } set { this._ti = value; } } } } --- NEW FILE: TestSummary.cs --- using System; namespace Adapdev.UnitTest.Core { /// <summary> /// Summary description for TestSummary. /// </summary> public class TestSummary { private TestAssemblyResult[] tar = null; public TestSummary(TestAssemblyResult[] tar) { this.tar = tar; } public int TotalFailed { get { int total = 0; foreach (TestAssemblyResult testAssemblyResult in tar) { total += testAssemblyResult.Failed; } return total; } } public int TotalPassed { get { int total = 0; foreach (TestAssemblyResult testAssemblyResult in tar) { total += testAssemblyResult.Passed; } return total; } } public int TotalIgnored { get { int total = 0; foreach (TestAssemblyResult testAssemblyResult in tar) { total += testAssemblyResult.Ignored; } return total; } } public double PercentPassed { get { int passed = this.TotalPassed; int failed = this.TotalFailed; if ((passed + failed) > 0) return (Convert.ToDouble(passed)/Convert.ToDouble(passed + failed)); else return 0; } } public double PercentFailed { get{return 1 - this.PercentPassed;} } public double TotalDuration { get { double duration = 0; foreach(TestAssemblyResult t in this.tar) { duration += t.GetTotalDuration(); } return duration; } } } } --- NEW FILE: IThreadWorkItemCommand.cs --- using System; using Adapdev.Commands; namespace Adapdev.UnitTest.Core { /// <summary> /// Summary description for IThreadWorkItemCommand. /// </summary> public interface IThreadWorkItemCommand : ICommand { object Execute(object o); } } --- NEW FILE: VSProjectConfig.cs --- #region Original Copyright (c) 2002-2003, James W. Newkirk, Michael C. Two, Alexei A. Vorontsov, Charlie Poole, Philip A. Craig /************************************************************************************ ' ' Copyright 2002-2003 James W. Newkirk, Michael C. Two, Alexei A. Vorontsov, Charlie Poole ' Copyright 2000-2002 Philip A. Craig ' ' This software is provided 'as-is', without any express or implied warranty. In no ' event will the authors be held liable for any damages arising from the use of this ' software. ' ' Permission is granted to anyone to use this software for any purpose, including ' commercial applications, and to alter it and redistribute it freely, subject to the ' following restrictions: ' ' 1. The origin of this software must not be misrepresented; you must not claim that ' you wrote the original software. If you use this software in a product, an ' acknowledgment (see the following) in the product documentation is required. ' ' Portions Copyright 2002-2003 James W. Newkirk, Michael C. Two, Alexei A. Vorontsov, Charlie Poole ' or Copyright 2000-2002 Philip A. Craig ' ' 2. Altered source versions must be plainly marked as such, and must not be ' misrepresented as being the original software. ' ' 3. This notice may not be removed or altered from any source distribution. ' '***********************************************************************************/ #endregion #region Copyright / License Information /* Author: Sean McCormack ================================================ Copyright ================================================ Copyright (c) 2004 Adapdev Technologies, LLC ================================================ License ================================================ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ Change History ================================================ III MM/DD/YYYY Change */ #endregion namespace Adapdev.UnitTest.Core { using System.Collections.Specialized; /// <summary> /// Originally, we used the same ProjectConfig class for both /// NUnit and Visual Studio projects. Since we really do very /// little with VS Projects, this class has been created to /// hold the name and the collection of assembly paths. /// </summary> public class VSProjectConfig { private string name; private StringCollection assemblies = new StringCollection(); public VSProjectConfig(string name) { this.name = name; } public string Name { get { return name; } } public StringCollection Assemblies { get { return assemblies; } } } } --- NEW FILE: TestHelperEventArgs.cs --- #region Copyright / License Information /* Author: Sean McCormack ================================================ Copyright ================================================ Copyright (c) 2004 Adapdev Technologies, LLC ================================================ License ================================================ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ Change History ================================================ III MM/DD/YYYY Change */ #endregion namespace Adapdev.UnitTest.Core { using System; /// <summary> /// Summary description for BaseTestHelperEventArgs. /// </summary> [Serializable] public class BaseTestHelperEventArgs { private BaseTestHelper _ti = null; public BaseTestHelperEventArgs(BaseTestHelper th) { this._ti = th; } public BaseTestHelper BaseTestHelper { get { return this._ti; } set { this._ti = value; } } } } --- NEW FILE: TestAssemblyResultEventArgs.cs --- #region Copyright / License Information /* Author: Sean McCormack ================================================ Copyright ================================================ Copyright (c) 2004 Adapdev Technologies, LLC ================================================ License ================================================ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ Change History ================================================ III MM/DD/YYYY Change */ #endregion namespace Adapdev.UnitTest.Core { using System; /// <summary> /// Summary description for TestAssemblyResultEventArgs. /// </summary> /// [Serializable] public class TestAssemblyResultEventArgs : EventArgs { private TestAssemblyResult _ti = null; public TestAssemblyResultEventArgs(TestAssemblyResult ti) { this._ti = ti; } public TestAssemblyResult TestAssemblyResult { get { return this._ti; } set { this._ti = value; } } } } --- NEW FILE: TypeHelper.cs --- #region Copyright / License Information /* Author: Sean McCormack ================================================ Copyright ================================================ Copyright (c) 2004 Adapdev Technologies, LLC ================================================ License ================================================ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ Change History ================================================ III MM/DD/YYYY Change */ #endregion namespace Adapdev.UnitTest.Core { using System; using System.Reflection; /// <summary> /// Summary description for TypeHelper. /// </summary> public class TypeHelper { public static bool HasCustomAttribute(ICustomAttributeProvider t, Type customAttributeType) { if (t == null) throw new ArgumentNullException("t"); if (customAttributeType == null) throw new ArgumentNullException("customAttributeType"); return t.GetCustomAttributes(customAttributeType, true).Length != 0; } public static Object GetFirstCustomAttribute(ICustomAttributeProvider mi, Type customAttributeType) { if (mi == null) throw new ArgumentNullException("mi"); if (customAttributeType == null) throw new ArgumentNullException("customAttributeType"); Object[] attrs = mi.GetCustomAttributes(customAttributeType, true); if (attrs.Length == 0) throw new ArgumentException("type does not have custom attribute"); return attrs[0]; } } } --- NEW FILE: TestFixtureIterationEventArg.cs --- #region Copyright / License Information /* Author: Sean McCormack ================================================ Copyright ================================================ Copyright (c) 2004 Adapdev Technologies, LLC ================================================ License ================================================ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ Change History ================================================ III MM/DD/YYYY Change */ #endregion namespace Adapdev.UnitTest.Core { using System; /// <summary> /// Summary description for TestIterationEventArgs. /// </summary> /// [Serializable] public class TestFixtureIterationEventArgs : EventArgs { private TestFixtureIteration _ti = null; public TestFixtureIterationEventArgs(TestFixtureIteration ti) { this._ti = ti; } public TestFixtureIteration TestFixtureIteration { get { return this._ti; } set { this._ti = value; } } } } --- NEW FILE: CompositeAbstractTestIteration.cs --- using System; using System.Collections; namespace Adapdev.UnitTest.Core { /// <summary> /// Summary description for CompositeAbstractTestIteration. /// </summary> /// [Serializable] public class CompositeAbstractTestIteration : AbstractTestIteration { protected Hashtable _results = new Hashtable(); public void AddTestResult(AbstractTestResult tr) { this._results[tr.Name] = tr; if (tr.State == TestState.Fail) this._state = TestState.Fail; if (this._state != TestState.Fail) { if (tr.State == TestState.Pass) this._state = TestState.Pass; } } public ICollection GetTestResults() { return this._results.Values; } public override double Duration { get { double d = 0; foreach (AbstractTestResult tr in this.GetTestResults()) { d += tr.GetTotalDuration(); } return d; } } public AbstractTestResult GetTestResult(string name) { return this._results[name] as AbstractTestResult; } } } --- NEW FILE: RunMethodCommand.cs --- using System; using System.Reflection; using Adapdev.Commands; namespace Adapdev.UnitTest.Core { /// <summary> /// Summary description for RunMethodCommand. /// </summary> public class RunMethodCommand : ICommand { private MethodInfo _method = null; private object _o = null; public RunMethodCommand(MethodInfo method, object o) { this._method = method; this._o = o; } public void Execute() { this._method.Invoke(this._o, null); } } } --- NEW FILE: TestAssembly.cs --- #region Copyright / License Information /* Author: Sean McCormack ================================================ Copyright ================================================ Copyright (c) 2004 Adapdev Technologies, LLC ================================================ License ================================================ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ Change History ================================================ III MM/DD/YYYY Change */ #endregion namespace Adapdev.UnitTest.Core { using System; using System.Collections; /// <summary> /// Summary description for TestAssembly. /// </summary> /// [Serializable] public class TestAssembly : AbstractTest { protected Hashtable _fixtures = new Hashtable(); protected string _assemblyName = String.Empty; protected string _assemblyFullName = String.Empty; protected TestSuite _parent = null; protected string _path = String.Empty; protected string _location = String.Empty; protected string _original = String.Empty; protected string _configFile = String.Empty; public TestAssembly() { } public TestAssembly(string name) { this.AssemblyName = name; this.Name = name; } public string ConfigFile { get { return _configFile; } set { _configFile = value; } } public string Path { get { return this._path; } set { this._path = value; } } public string AssemblyName { get { return this._assemblyName; } set { this._assemblyName = value; } } public string AssemblyFullName { get { return this._assemblyFullName; } set { this._assemblyFullName = value; } } public string OriginalPath { get{return this._original;} set{this._original = value;} } public TestSuite Parent { get { return this._parent; } set { this._parent = value; } } public string Location { get { return this._location; } set { this._location = value; } } public void AddTestFixture(TestFixture tf) { if (tf != null) this._fixtures[tf.Id] = tf; } public void RemoveTestFixture(TestFixture tf) { if (tf != null) this._fixtures.Remove(tf.Id); } public void RemoveTestFixture(string id) { this._fixtures.Remove(id); } public override int GetTestCount() { if (!this.Ignore) { int count = 0; foreach (TestFixture t in this.GetTestFixtures()) { if(t.ShouldRun && !t.Ignore) { count += t.GetTestCount(); } } return count*this.RepeatCount; } else { return 0; } } public ICollection GetTestFixtures() { return this._fixtures.Values; } } } --- NEW FILE: TestFixtureIteration.cs --- #region Copyright / License Information /* Author: Sean McCormack ================================================ Copyright ================================================ Copyright (c) 2004 Adapdev Technologies, LLC ================================================ License ================================================ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ Change History ================================================ III MM/DD/YYYY Change */ #endregion namespace Adapdev.UnitTest.Core { using System; [Serializable] public class TestFixtureIteration : CompositeAbstractTestIteration { } } --- NEW FILE: TestAssemblyIterationEventArgs.cs --- #region Copyright / License Information /* Author: Sean McCormack ================================================ Copyright ================================================ Copyright (c) 2004 Adapdev Technologies, LLC ================================================ License ================================================ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ Change History ================================================ III MM/DD/YYYY Change */ #endregion namespace Adapdev.UnitTest.Core { using System; /// <summary> /// Summary description for TestAssemblyIterationEventArgs. /// </summary> /// [Serializable] public class TestAssemblyIterationEventArgs : EventArgs { private TestAssemblyIteration _ti = null; public TestAssemblyIterationEventArgs(TestAssemblyIteration ti) { this._ti = ti; } public TestAssemblyIteration TestAssemblyIteration { get { return this._ti; } set { this._ti = value; } } } } --- NEW FILE: XmlFormatter.cs --- using System.IO; namespace Adapdev.UnitTest.Core { using System; using System.Diagnostics; using System.Text; using System.Xml; /// <summary> /// Summary description for XmlFormatter. /// </summary> public class XmlFormatter : IResultFormatter { private XmlDocument xml = null; public XmlFormatter(TestAssemblyResult[] results){ this.FormatResults(results); } protected void FormatTestResult(TestResult tr, XmlNode testFixtureIteration) { Debug.Assert(tr != null); XmlNode testResult = xml.CreateElement("testResult"); XmlAttribute avgOpsSecond = xml.CreateAttribute("avgOpsSecond"); avgOpsSecond.Value = tr.GetAvgOpsPerSecond().ToString(); testResult.Attributes.Append(avgOpsSecond); XmlAttribute totalDuration = xml.CreateAttribute("totalDuration"); totalDuration.Value = tr.GetTotalDuration().ToString(); testResult.Attributes.Append(totalDuration); XmlAttribute category = xml.CreateAttribute("category"); category.Value = tr.Category; testResult.Attributes.Append(category); XmlAttribute description = xml.CreateAttribute("description"); description.Value = tr.Description; testResult.Attributes.Append(description); this.FormatAbstractTestResult(tr, testResult); foreach (TestIteration ti in tr.Iterations) { XmlNode testIteration = xml.CreateElement("testIteration"); XmlAttribute iteration = xml.CreateAttribute("iteration"); iteration.Value = ti.Iteration.ToString(); testIteration.Attributes.Append(iteration); XmlNode tcategory = xml.CreateElement("category"); testIteration.AppendChild(tcategory); XmlNode tcategorytext = xml.CreateCDataSection(tr.Category); tcategory.AppendChild(tcategorytext); XmlNode tmessage = xml.CreateElement("message"); testIteration.AppendChild(tmessage); XmlNode tmessagetext = xml.CreateCDataSection(ti.Result); tmessage.AppendChild(tmessagetext); XmlNode texception = xml.CreateElement("exception"); testIteration.AppendChild(texception); XmlNode texceptiontext = xml.CreateCDataSection(ti.FullStackTrace); texception.AppendChild(texceptiontext); XmlNode tduration = xml.CreateElement("duration"); tduration.InnerText = ti.Duration.ToString(); testIteration.AppendChild(tduration); XmlNode thread = xml.CreateElement("thread"); thread.InnerText = ti.Thread.ToString(); testIteration.AppendChild(thread); XmlNode state = xml.CreateElement("state"); state.InnerText = ti.State.ToString(); testIteration.AppendChild(state); XmlNode opsSecond = xml.CreateElement("opsSecond"); opsSecond.InnerText = ti.GetOpsPerSecond().ToString(); testIteration.AppendChild(opsSecond); XmlNode output = xml.CreateElement("consoleOutput"); testIteration.AppendChild(output); XmlNode outputText = xml.CreateCDataSection(ti.ConsoleOutput); output.AppendChild(outputText); XmlNode consoleError = xml.CreateElement("consoleError"); testIteration.AppendChild(consoleError); XmlNode consoleErrorText = xml.CreateCDataSection(ti.ConsoleError); consoleError.AppendChild(consoleErrorText); XmlNode debugOutput = xml.CreateElement("debugOutput"); testIteration.AppendChild(debugOutput); XmlNode debugOutputText = xml.CreateCDataSection(ti.DebugOutput); debugOutput.AppendChild(debugOutputText); XmlNode traceOutput = xml.CreateElement("traceOutput"); testIteration.AppendChild(traceOutput); XmlNode traceOutputText = xml.CreateCDataSection(ti.TraceOutput); traceOutput.AppendChild(traceOutputText); XmlNode allOutput = xml.CreateElement("allOutput"); testIteration.AppendChild(allOutput); XmlNode allOutputText = xml.CreateCDataSection(ti.AllOutput); allOutput.AppendChild(allOutputText); testResult.AppendChild(testIteration); } testFixtureIteration.AppendChild(testResult); } protected void FormatTestFixtureResult(TestFixtureResult tfr, XmlNode testAssemblyIteration) { Debug.Assert(tfr != null); XmlNode testFixtureResult = xml.CreateElement("testFixtureResult"); XmlAttribute totalDuration = xml.CreateAttribute("totalDuration"); totalDuration.Value = tfr.GetTotalDuration().ToString(); testFixtureResult.Attributes.Append(totalDuration); this.FormatAbstractTestResult(tfr, testFixtureResult); int i = 1; foreach (TestFixtureIteration tfi in tfr.Iterations) { XmlNode testFixtureIteration = xml.CreateElement("testFixtureIteration"); XmlAttribute iteration = xml.CreateAttribute("iteration"); iteration.Value = i.ToString(); testFixtureIteration.Attributes.Append(iteration); XmlAttribute totalDuration2 = xml.CreateAttribute("totalDuration"); totalDuration2.Value = tfr.GetTotalDuration().ToString(); testFixtureIteration.Attributes.Append(totalDuration2); XmlAttribute state = xml.CreateAttribute("state"); state.Value = tfr.GetTotalDuration().ToString(); testFixtureIteration.Attributes.Append(state); foreach (TestResult tr in tfi.GetTestResults()) { this.FormatTestResult(tr, testFixtureIteration); } testFixtureResult.AppendChild(testFixtureIteration); i++; } testAssemblyIteration.AppendChild(testFixtureResult); } protected void FormatTestAssemblyResult(TestAssemblyResult tar, XmlNode resultNode) { Debug.Assert(tar != null); XmlNode testAssemblyResult = xml.CreateNode(XmlNodeType.Element, "testAssemblyResult", ""); XmlAttribute runTime = xml.CreateAttribute("runTime"); runTime.Value = tar.RunTime.ToString(); testAssemblyResult.Attributes.Append(runTime); XmlAttribute assemblyName = xml.CreateAttribute("assemblyName"); assemblyName.Value = tar.AssemblyName; testAssemblyResult.Attributes.Append(assemblyName); XmlAttribute assemblyFullName = xml.CreateAttribute("assemblyFullName"); assemblyFullName.Value = tar.AssemblyFullName; testAssemblyResult.Attributes.Append(assemblyFullName); XmlAttribute location = xml.CreateAttribute("location"); location.Value = tar.Location; testAssemblyResult.Attributes.Append(location); this.FormatAbstractTestResult(tar, testAssemblyResult); int i = 1; foreach (TestAssemblyIteration tai in tar.Iterations) { XmlNode testAssemblyIteration = xml.CreateElement("testAssemblyIteration"); XmlAttribute iteration = xml.CreateAttribute("iteration"); iteration.Value = i.ToString(); testAssemblyIteration.Attributes.Append(iteration); XmlAttribute totalDuration = xml.CreateAttribute("totalDuration"); totalDuration.Value = tai.Duration.ToString(); testAssemblyIteration.Attributes.Append(totalDuration); XmlAttribute state = xml.CreateAttribute("state"); state.Value = tai.State.ToString(); testAssemblyIteration.Attributes.Append(state); foreach (TestFixtureResult tfr in tai.GetTestResults()) { this.FormatTestFixtureResult(tfr, testAssemblyIteration); } testAssemblyResult.AppendChild(testAssemblyIteration); i++; } resultNode.AppendChild(testAssemblyResult); } public void FormatResults(TestAssemblyResult[] tars) { Debug.Assert(tars != null); xml = new XmlDocument(); // xml.AppendChild(xml.CreateProcessingInstruction("xml", "version=\"1.0\" encoding=\"UTF-8\"")); XmlNode results = xml.CreateNode(XmlNodeType.Element, "results",String.Empty); xml.AppendChild(results); if (tars != null) { foreach (TestAssemblyResult tar in tars) { this.FormatTestAssemblyResult(tar, results); } } } protected void FormatAbstractTestResult(AbstractTestResult atr, XmlNode testResult) { Debug.Assert(atr != null); XmlAttribute name = xml.CreateAttribute("name"); name.Value = atr.Name; testResult.Attributes.Append(name); XmlAttribute avgDuration = xml.CreateAttribute("avgDuration"); avgDuration.Value = atr.GetAverageDuration().ToString(); testResult.Attributes.Append(avgDuration); XmlAttribute totalIterations = xml.CreateAttribute("totalIterations"); totalIterations.Value = atr.GetTotalIterations().ToString(); testResult.Attributes.Append(totalIterations); XmlAttribute state = xml.CreateAttribute("state"); state.Value = atr.State.ToString(); testResult.Attributes.Append(state); XmlAttribute id = xml.CreateAttribute("id"); id.Value = atr.TestId.ToString(); testResult.Attributes.Append(id); XmlAttribute passed = xml.CreateAttribute("passed"); passed.Value = atr.Passed.ToString(); testResult.Attributes.Append(passed); XmlAttribute failed = xml.CreateAttribute("failed"); failed.Value = atr.Failed.ToString(); testResult.Attributes.Append(failed); XmlAttribute ignored = xml.CreateAttribute("ignored"); ignored.Value = atr.Ignored.ToString(); testResult.Attributes.Append(ignored); XmlAttribute percentPassed = xml.CreateAttribute("percentPassed"); percentPassed.Value = atr.PercentPassed.ToString("p"); testResult.Attributes.Append(percentPassed); XmlAttribute percentFailed = xml.CreateAttribute("percentFailed"); percentFailed.Value = atr.PercentFailed.ToString("p"); testResult.Attributes.Append(percentFailed); } public string GetText(){ StringWriter sw = new StringWriter(); XmlTextWriter xtw = new XmlTextWriter(sw); xtw.WriteProcessingInstruction("xml", "version='1.0' encoding='UTF-8'"); xml.Save(sw); return sw.ToString().Replace("<?xml version=\"1.0\" encoding=\"utf-16\"?>",""); } } } --- NEW FILE: RunNonThreadedTestCommand.cs --- using System; using System.Diagnostics; using System.IO; using System.Reflection; using System.Threading; using Adapdev.Commands; using Adapdev.Diagnostics; using log4net; namespace Adapdev.UnitTest.Core { /// <summary> /// Summary description for NonThreadedRunTestCommand. /// </summary> public class RunNonThreadedTestCommand : ICommand { private MethodInfo _method = null; private object _o = null; // create the logger private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // setup the logging levels private bool _debugMode = log.IsDebugEnabled; private bool _infoMode = log.IsInfoEnabled; private IPerfTimer timer = PerfTimerFactory.GetPerfTimer(PerfTimerType.HIRESSECONDS); private TestEventDispatcher _dispatcher = null; private Test _test = null; private TestFixture _testFixture = null; private Type _type = null; private object o = null; private TestFixtureIteration _testFixtureIteration = null; public RunNonThreadedTestCommand(TestEventDispatcher dispatcher, Test test, TestFixture tf, Type type, object o, TestFixtureIteration tfi) { this._dispatcher = dispatcher; this._test = test; this._testFixture = tf; this.o = o; this._testFixtureIteration = tfi; this._type = type; } public void Execute() { try { MethodInfo m = _type.GetMethod(_test.Method); TestResult tr = new TestResult(_test); tr.TestId = _test.Id; tr.Description = _test.Description; if(this._debugMode) log.Debug("Running T " + _test.Name); if (!_test.Ignore && _test.ShouldRun) { if(_dispatcher != null)_dispatcher.OnTestStarted(new TestEventArgs(_test)); for (int i = 1; i <= _test.RepeatCount; i++) { TextWriter consoleOut = Console.Out; TextWriter errorOut = Console.Error; StringWriter consoleWriter = new StringWriter(); StringWriter errorWriter = new StringWriter(); StringWriter debugWriter = new StringWriter(); StringWriter traceWriter = new StringWriter(); //Console.SetOut(consoleWriter); Console.SetError(errorWriter); TextWriterTraceListener debug = new TextWriterTraceListener(debugWriter); TextWriterTraceListener error = new TextWriterTraceListener(traceWriter); Debug.Listeners.Add(debug); Trace.Listeners.Add(error); if (_test.RepeatDelay > 0) { Thread.Sleep(_test.RepeatDelay); Console.WriteLine("Sleeping..." + _test.RepeatDelay); } TestIteration ti = new TestIteration(); ti.Name = _test.Name; ti.Iteration = i; ti.Thread = AppDomain.GetCurrentThreadId().ToString(); long kStart = 0; long kEnd = 0; if(_dispatcher != null)_dispatcher.OnTestIterationStarted(new TestEventArgs(_test)); try { this.RunTestSetUps(_dispatcher, _testFixture, _test.Name, o, _type); kStart = Process.GetCurrentProcess().WorkingSet; timer.Start(); new RunMethodCommand(m, o).Execute(); timer.Stop(); ti.Duration = timer.Duration; kEnd = Process.GetCurrentProcess().WorkingSet; ti.MemoryUsed = (kEnd - kStart)/1024; if (_test.MaxKMemory > 0 && _test.MaxKMemory < ti.MemoryUsed) { ti.State = TestState.Fail; ti.Result = "Memory usage exceeded MaxK limit of " + _test.MaxKMemory; } else if (_test.MinOperationsPerSecond > 0 && ti.GetOpsPerSecond() < _test.MinOperationsPerSecond) { ti.State = TestState.Fail; ti.Result = "Ops per second was less than minimum limit of " + _test.MinOperationsPerSecond; } else if (_test.ExpectedExceptionType != null && _test.ExpectedExceptionType.Length > 0) { ti.State = TestState.Fail; ti.Result = "ExceptedException type " + _test.ExpectedExceptionType + " was not thrown."; } else { ti.State = TestState.Pass; } this.RunTestTearDowns(_dispatcher, _testFixture, _test.Name, o, _type); } catch (Exception e) { timer.Stop(); ti.Duration = timer.Duration; kEnd = Process.GetCurrentProcess().WorkingSet; if (_test.ExpectedExceptionType != null && _test.ExpectedExceptionType.Length > 0) { Type t = null; foreach(Assembly ass in AppDomain.CurrentDomain.GetAssemblies()) { try { t = ass.GetType(_test.ExpectedExceptionType, true, true); break; } catch(Exception){} } if(t == null) throw new TypeLoadException("Unable to locate " + _test.ExpectedExceptionType + ". Please make sure it is correct."); if (e.InnerException.GetType().IsSubclassOf(t) || e.InnerException.GetType() == t) { if(_test.ExpectedExceptionMessage != null && _test.ExpectedExceptionMessage.Length > 0) { if(_test.ExpectedExceptionMessage.ToLower() == e.InnerException.Message.ToLower()) { ti.Result = "Expected Exception: " + _test.ExpectedExceptionType + " was thrown. Message: " + e.InnerException.Message; ti.State = TestState.Pass; } else { ti.Result = "Expected Exception: " + _test.ExpectedExceptionType + " was thrown, but wrong message. Message: " + e.InnerException.Message + " - Expected: " + _test.ExpectedExceptionMessage; ti.State = TestState.Fail; } } else { ti.Result = "Expected Exception: " + _test.ExpectedExceptionType + " was thrown. Message: " + e.InnerException.Message; ti.State = TestState.Pass; } } else { ti.Result = "Expected Exception: " + _test.ExpectedExceptionType + " was NOT thrown. Message: " + e.InnerException.Message; ti.State = TestState.Fail; } ti.ExceptionType = e.InnerException.GetType().FullName; ti.FullStackTrace = e.InnerException.StackTrace; ti.MemoryUsed = (kEnd - kStart)/1024; } // TODO : Fix incrementing of tests in GUI when IgnoreException is thrown else if(e.InnerException.GetType() == typeof(IgnoreException) || e.InnerException.GetType() == typeof(IgnoreException)) { ti.Result = e.InnerException.Message; ti.State = TestState.ForcedIgnore; ti.ExceptionType = e.InnerException.GetType().FullName; ti.FullStackTrace = e.InnerException.StackTrace; } else { ti.Result = e.InnerException.Message; ti.ExceptionType = e.InnerException.GetType().FullName; ti.FullStackTrace = e.InnerException.StackTrace; ti.State = TestState.Fail; } this.RunTestTearDowns(_dispatcher, _testFixture, _test.Name, o, _type); } ti.ConsoleOutput = consoleWriter.ToString(); ti.ConsoleError = errorWriter.ToString(); ti.DebugOutput = debugWriter.ToString(); ti.TraceOutput = traceWriter.ToString(); lock(this){tr.AddIteration(ti);} if(_dispatcher != null)_dispatcher.OnTestIterationCompleted(new TestIterationEventArgs(ti)); Console.SetOut(consoleOut); Console.SetError(errorOut); Debug.Listeners.Remove(debug); Trace.Listeners.Remove(error); debug.Dispose(); error.Dispose(); } } else { TestIteration ti = new TestIteration(); ti.Name = _test.Name; ti.State = TestState.Ignore; ti.Result = _test.IgnoreReason; tr.AddIteration(ti); } if (_testFixture.ShouldShow) _testFixtureIteration.AddTestResult(tr); if(_dispatcher != null)_dispatcher.OnTestCompleted(new TestResultEventArgs(tr)); } catch (Exception e) { Console.WriteLine(e.Message + " " + e.StackTrace); } finally { } } protected void RunTestSetUps(TestEventDispatcher _dispatcher, TestFixture tf, string name, object instance, Type type) { foreach (TestHelper t in tf.GetTestSetUps()) { try { // Console.WriteLine(t.Method); if (t.Test.Length < 1 || t.Test.ToLower().Equals(name.ToLower())) { if(_dispatcher != null)_dispatcher.OnBaseTestHelperStarted(new BaseTestHelperEventArgs(t)); MethodInfo m = type.GetMethod(t.Method); m.Invoke(instance, null); } } catch (Exception e) { Console.Write(e); } } } protected void RunTestTearDowns(TestEventDispatcher _dispatcher, TestFixture tf, string name, object instance, Type type) { foreach (TestHelper t in tf.GetTestTearDowns()) { try { if (t.Test.Length < 1 || t.Test.ToLower().Equals(name.ToLower())) { if(_dispatcher != null)_dispatcher.OnBaseTestHelperStarted(new BaseTestHelperEventArgs(t)); MethodInfo m = type.GetMethod(t.Method); m.Invoke(instance, null); } } catch (Exception e) { Console.Write(e); } } } public void Execute(object o){this.Execute();} } } --- NEW FILE: TestAssemblyIteration.cs --- #region Copyright / License Information /* Author: Sean McCormack ================================================ Copyright ================================================ Copyright (c) 2004 Adapdev Technologies, LLC ================================================ License ================================================ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ Change History ================================================ III MM/DD/YYYY Change */ #endregion namespace Adapdev.UnitTest.Core { using System; using System.Collections; /// <summary> /// Summary description for TestAssemblyIteration. /// </summary> /// [Serializable] public class TestAssemblyIteration : CompositeAbstractTestIteration { } } --- NEW FILE: TestSuite.cs --- #region Copyright / License Information /* Author: Sean McCormack ================================================ Copyright ================================================ Copyright (c) 2004 Adapdev Technologies, LLC ================================================ License ================================================ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ Change History ================================================ III MM/DD/YYYY Change */ #endregion namespace Adapdev.UnitTest.Core { using System; using System.Collections; using Adapdev.IO; /// <summary> /// Summary description for TestSuite. /// </summary> /// [Serializable] public class TestSuite { protected Hashtable _assemblies = new Hashtable(); protected int failedTestCount = 0; protected int passedTestCount = 0; protected int ignoredTestCount = 0; protected double _duration = 0; public TestSuite(){} public void AddTestAssembly(TestAssembly ta) { this._assemblies[ta.Name] = ta; } public ICollection GetTestAssemblies() { return this._assemblies.Values; } public TestAssembly GetTestAssembly(string name) { return this._assemblies[name] as TestAssembly; } public int GetTestCount() { int count = 0; foreach (TestAssembly ta in this.GetTestAssemblies()) { if(ta.ShouldRun && !ta.Ignore) { count += ta.GetTestCount(); } } return count; } public int FailedTestCount { get { return this.failedTestCount; } set { this.failedTestCount = value; } } public int IgnoredTestCount { get { return this.ignoredTestCount; } set { this.ignoredTestCount = value; } } public int PassedTestCount { get { return this.passedTestCount; } set { this.passedTestCount = value; } } public double PercentPassed { get { if ((this.passedTestCount + this.failedTestCount) > 0) return (Convert.ToDouble(this.passedTestCount)/Convert.ToDouble(this.passedTestCount + this.failedTestCount)); else return 0; } } } } --- NEW FILE: AssemblyWatcher.cs --- #region Copyright / License Information /* Author: Sean McCormack ================================================ Copyright ================================================ Copyright (c) 2004 Adapdev Technologies, LLC ================================================ License ================================================ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ Change History ================================================ III MM/DD/YYYY Change */ #endregion #region Copyright (c) 2002-2003, James W. Newkirk, Michael C. Two, Alexei A. Vorontsov, Charlie Poole, Philip A. Craig /************************************************************************************ ' ' Copyright 2002-2003 James W. Newkirk, Michael C. Two, Alexei A. Vorontsov, Charlie Poole ' Copyright 2000-2002 Philip A. Craig ' ' This software is provided 'as-is', without any express or implied warranty. In no ' event will the authors be held liable for any damages arising from the use of this ' software. ' ' Permission is granted to anyone to use this software for any purpose, including ' commercial applications, and to alter it and redistribute it freely, subject to the ' following restrictions: ' ' 1. The origin of this software must not be misrepresented; you must not claim that ' you wrote the original software. If you use this software in a product, an ' acknowledgment (see the following) in the product documentation is required. ' ' Portions Copyright 2002-2003 James W. Newkirk, Michael C. Two, Alexei A. Vorontsov, Charlie Poole ' or Copyright 2000-2002 Philip A. Craig ' ' 2. Altered source versions must be plainly marked as such, and must not be ' misrepresented as being the original software. ' ' 3. This notice may not be removed or altered from any source distribution. ' '***********************************************************************************/ #endregion namespace Adapdev.UnitTest.Core { using System; using System.Collections; using System.IO; using System.Timers; /// <summary> /// AssemblyWatcher keeps track of one or more assemblies to /// see if they have changed. It incorporates a delayed notification /// and uses a standard event to notify any interested parties /// about the change. The path to the assembly is provided as /// an argument to the event handler so that one routine can /// be used to handle events from multiple watchers. /// </summary> public class AssemblyWatcher { private FileSystemWatcher[] fileWatcher; private FileInfo[] fileInfo; protected Timer timer; protected string changedAssemblyPath; public delegate void AssemblyChangedHandler(String fullPath); public event AssemblyChangedHandler AssemblyChangedEvent; public AssemblyWatcher(int delay, string assemblyFileName) : this(delay, new string[] {assemblyFileName}) { } public AssemblyWatcher(int delay, IList assemblies) { fileInfo = new FileInfo[assemblies.Count]; fileWatcher = new FileSystemWatcher[assemblies.Count]; for (int i = 0; i < assemblies.Count; i++) { fileInfo[i] = new FileInfo((string) assemblies[i]); fileWatcher[i] = new FileSystemWatcher(); fileWatcher[i].Path = fileInfo[i].DirectoryName; fileWatcher[i].Filter = fileInfo[i].Name; fileWatcher[i].NotifyFilter = NotifyFilters.Size | NotifyFilters.LastWrite; fileWatcher[i].Changed += new FileSystemEventHandler(OnChanged); fileWatcher[i].EnableRaisingEvents = false; } timer = new Timer(delay); timer.AutoReset = false; timer.Enabled = false; timer.Elapsed += new ElapsedEventHandler(OnTimer); } public FileInfo GetFileInfo(int index) { return fileInfo[index]; } public void Start() { EnableWatchers(true); } public void Stop() { EnableWatchers(false); } private void EnableWatchers(bool enable) { foreach (FileSystemWatcher watcher in fileWatcher) watcher.EnableRaisingEvents = enable; } protected void OnTimer(Object source, ElapsedEventArgs e) { lock (this) { PublishEvent(); timer.Enabled = false; } } protected void OnChanged(object source, FileSystemEventArgs e) { changedAssemblyPath = e.FullPath; if (timer != null) { lock (this) { if (!timer.Enabled) timer.Enabled = true; timer.Start(); } } else { PublishEvent(); } } protected void PublishEvent() { if (AssemblyChangedEvent != null) AssemblyChangedEvent(changedAssemblyPath); } } } --- NEW FILE: TestResult.cs --- #region Copyright / License Information /* Author: Sean McCormack ================================================ Copyright ================================================ Copyright (c) 2004 Adapdev Technologies, LLC ================================================ License ================================================ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ Change History ================================================ III MM/DD/YYYY Change */ #endregion namespace Adapdev.UnitTest.Core { using System; /// <summary> /// Summary description for TestResult. /// </summary> /// [Serializable] public class TestResult : AbstractTestResult { protected string _category = ""; protected string _description = ""; protected TestType _testType = TestType.Unit; public TestResult(Test t) { this.Name = t.Name; this.Category = t.Category; this.TestType = t.TestType; } public TestType TestType { get{return this._testType;} set{this._testType = value;} } /// <summary> /// Gets or sets the category. /// </summary> /// <value></value> public string Category { get { return this._category; } set { this._category = value; } } /// <summary> /// Gets or sets the description. /// </summary> /// <value></value> public string Description { get{ return this._description;} set{ this._description = value;} } public double GetAvgOpsPerSecond() { double i = 0; foreach (TestIteration ti in this._iterations) { i += ti.GetOpsPerSecond(); } double avg = i/this._iterations.Count; return avg; } public long GetAvgMemoryUsed() { long i = 0; foreach (TestIteration ti in this._iterations) { i += ti.MemoryUsed; } long avg = i/this._iterations.Count; return avg; } } } --- NEW FILE: TestHelper.cs --- #region Copyright / License Information /* Author: Sean McCormack ================================================ Copyright ================================================ Copyright (c) 2004 Adapdev Technologies, LLC ================================================ License ================================================ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ Change History ================================================ III MM/DD/YYYY Change */ #endregion namespace Adapdev.UnitTest.Core { using System; /// <summary> /// Summary description for TestHelper. /// </summary> /// [Serializable] public class TestHelper : BaseTestHelper { private string _test = ""; public string Test { get { return this._test; } set { this._test = value; } } } } --- NEW FILE: TestAssemblyResult.cs --- #region Copyright / License Information /* Author: Sean McCormack ================================================ Copyright ================================================ Copyright (c) 2004 Adapdev Technologies, LLC ================================================ License ================================================ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ Change History ================================================ III MM/DD/YYYY Change */ #endregion namespace Adapdev.UnitTest.Core { using System; /// <summary> /// Summary description for TestAssemblyResult. /// </summary> /// [Serializable] public class TestAssemblyResult : AbstractTestResult { protected string _assemblyName = ""; protected string _assemblyFullName = ""; protected string _location = null; protected DateTime _runTime = DateTime.Now; public TestAssemblyResult(TestAssembly ta) { this.Name = ta.Name; } public string Location { get { return this._location; } set { this._location = value; } } public string AssemblyName { get { return this._assemblyName; } set { this._assemblyName = value; } } public string AssemblyFullName { get { return this._assemblyFullName; } set { this._assemblyFullName = value; } } public DateTime RunTime { get{return this._runTime;} set{this._runTime = value;} } } } --- NEW FILE: TestEventDispatcher.cs --- #region Copyright / License Information /* Author: Sean McCormack ================================================ Copyright ================================================ Copyright (c) 2004 Adapdev Technologies, LLC ================================================ License ================================================ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ Change History ================================================ III MM/DD/YYYY Change */ #endregion using Adapdev; namespace Adapdev.UnitTest.Core { public delegate void TestIterationStartedEventHandler(object sender, TestEventArgs e); public delegate void TestIterationCompletedEventHandler(object sender, TestIterationEventArgs e); public delegate void TestCompletedEventHandler(object sender, TestResultEventArgs e); public delegate void TestStartedEventHandler(object sender, TestEventArgs e); public delegate void TestFixtureCompletedEventHandler(object sender, TestFixtureResultEventArgs e); public delegate void TestFixtureStartedEventHandler(object sender, TestFixtureEventArgs e); public delegate void TestFixtureIterationStartedEventHandler(object sender, TestFixtureEventArgs e); public delegate void TestFixtureIterationCompletedEventHandler(object sender, TestFixtureIterationEventArgs e); public delegate void TestAssemblyIterationCompletedEventHandler(object sender, TestAssemblyIterationEventArgs e); public delegate void TestAssemblyIterationStartedEventHandler(object sender, TestAssemblyEventArgs e); public delegate void TestAssemblyCompletedEventHandler(object sender, TestAssemblyResultEventArgs e); public delegate void TestAssemblyStartedEventHandler(object sender, TestAssemblyEventArgs e); public delegate void ErrorEventHandler(object sender, ErrorEventArgs e); public delegate void BaseTestHelperStartedEventHandler(object sender, BaseTestHelperEventArgs e); public delegate void TestSuiteCompletedEventHandler(object sender, TestAssemblyResult[] tar); /// <summary> /// Summary description for TestEventDispatcher. /// </summary> public class TestEventDispatcher : LongLivingMarshalByRefObject { public TestEventDispatcher() { } public event TestIterationCompletedEventHandler TestIterationCompleted; public event TestIterationStartedEventHandler TestIterationStarted; public event TestCompletedEventHandler TestCompleted; public event TestStartedEventHandler TestStarted; public event TestFixtureIterationStartedEventHandler TestFixtureIterationStarted; public event TestFixtureIterationCompletedEventHandler TestFixtureIterationCompleted; public event TestFixtureCompletedEventHandler TestFixtureCompleted; public event TestFixtureStartedEventHandler TestFixtureStarted; public event TestAssemblyIterationStartedEventHandler TestAssemblyIterationStarted; public event TestAssemblyIterationCompletedEventHandler TestAssemblyIterationCompleted; public event TestAssemblyCompletedEventHandler TestAssemblyCompleted; public event TestAssemblyStartedEventHandler TestAssemblyStarted; public event TestSuiteCompletedEventHandler TestSuiteCompleted; public event ErrorEventHandler ErrorOccured; public event BaseTestHelperStartedEventHandler BaseTestHelperStarted; public virtual void OnTestIterationStarted(TestEventArgs e) { if (TestIterationStarted != null) { //Invokes the delegates. TestIterationStarted(this, e); } } public virtual void OnTestIterationCompleted(TestIterationEventArgs e) { if (TestIterationCompleted != null) { //Invokes the delegates. TestIterationCompleted(this, e); } } public virtual void OnTestFixtureIterationStarted(TestFixtureEventArgs e) { if (TestFixtureIterationStarted != null) { //Invokes the delegates. TestFixtureIterationStarted(this, e); } } public virtual void OnTestFixtureIterationCompleted(TestFixtureIterationEventArgs e) { if (TestFixtureIterationCompleted != null) { //Invokes the delegates. TestFixtureIterationCompleted(this, e); } } public virtual void OnTestAssemblyIterationStarted(TestAssemblyEventArgs e) { if (TestAssemblyIterationStarted != null) { //Invokes the delegates. TestAssemblyIterationStarted(this, e); } } public virtual void OnTestAssemblyIterationCompleted(TestAssemblyIterationEventArgs e) { if (TestAssemblyIterationCompleted != null) { //Invokes the delegates. TestAssemblyIterationCompleted(this, e); } } public virtual void OnTestCompleted(TestResultEventArgs e) { if (TestCompleted != null) { //Invokes the delegates. TestCompleted(this, e); } } public virtual void OnTestFixtureCompleted(TestFixtureResultEventArgs e) { if (TestFixtureCompleted != null) { //Invokes the delegates. TestFixtureCompleted(this, e); } } public virtual void OnTestAssemblyCompleted(TestAssemblyResultEventArgs e) { if (TestAssemblyCompleted != null) { //Invokes the delegates. TestAssemblyCompleted(this, e); } } public... [truncated message content] |
From: Sean M. <int...@us...> - 2005-11-16 07:02:02
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.UnitTest.Core.NUnitTests In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.UnitTest.Core.NUnitTests Added Files: Adapdev.UnitTest.Core.NUnitTests.csproj AssemblyInfo.cs Class1.cs Log Message: --- NEW FILE: Adapdev.UnitTest.Core.NUnitTests.csproj --- <VisualStudioProject> <CSHARP ProjectType = "Local" ProductVersion = "7.10.3077" SchemaVersion = "2.0" ProjectGuid = "{4E7A445A-E686-46F0-A7E5-4129FAB5C3E3}" > <Build> <Settings ApplicationIcon = "" AssemblyKeyContainerName = "" AssemblyName = "Adapdev.UnitTest.Core.NUnitTests" AssemblyOriginatorKeyFile = "" DefaultClientScript = "JScript" DefaultHTMLPageLayout = "Grid" DefaultTargetSchema = "IE50" DelaySign = "false" OutputType = "Library" PreBuildEvent = "" PostBuildEvent = "" RootNamespace = "Adapdev.UnitTest.Core.NUnitTests" 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" /> </References> </Build> <Files> <Include> <File RelPath = "AssemblyInfo.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Class1.cs" SubType = "Code" BuildAction = "Compile" /> </Include> </Files> </CSHARP> </VisualStudioProject> --- NEW FILE: Class1.cs --- using System; namespace Adapdev.UnitTest.Core.NUnitTests { /// <summary> /// Summary description for Class1. /// </summary> public class Class1 { public Class1() { // // TODO: Add constructor logic here // } } } --- NEW FILE: AssemblyInfo.cs --- using System.Reflection; using System.Runtime.CompilerServices; // // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. // [assembly: AssemblyTitle("")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.*")] // // In order to sign your assembly you must specify a key to use. Refer to the // Microsoft .NET Framework documentation for more information on assembly signing. // // Use the attributes below to control which key is used for signing. // // Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used. // (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be // relative to the project output directory which is // %Project Directory%\obj\<configuration>. For example, if your KeyFile is // located in the project directory, you would specify the AssemblyKeyFile // attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. // [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] [assembly: AssemblyKeyName("")] |
From: Sean M. <int...@us...> - 2005-11-16 07:02:02
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.UnitTest.Core.AdapdevTests In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.UnitTest.Core.AdapdevTests Added Files: Adapdev.UnitTest.Core.AdapdevTests.csproj AdapdevAttributes.cs AssemblyInfo.cs MultiThreadedRepeatTest.cs MultiThreadedTest.cs RollbackTransactionTest.cs SomeTest.cs TransactionTest.cs Log Message: --- NEW FILE: AdapdevAttributes.cs --- using System; using System.Threading; using Adapdev.UnitTest; namespace Adapdev.UnitTest.Core.AdapdevTests { [TestFixture] public class AdapdevAttributes { // Runs only once, when the test assembly is dynamically loaded public AdapdevAttributes(){} // Runs once at the beginning of each TestFixture iteration [TestFixtureSetUp] public void TestFixtureSetUp() { Console.WriteLine("TestFixtureSetUp"); } // Runs once at the beginning of each Test iteration [TestSetUp] public void TestSetUp() { Console.WriteLine("TestSetUp"); } // Runs once at the beginning of each Test iteration [SetUp] public void SetUp() { Console.WriteLine("SetUp"); } // Runs once at the beginning of SimpleTest only [TestSetUp("SimpleTest")] public void SpecificTestSetUp() { Console.WriteLine("SpecificTestSetUp runs only for SimpleTest"); } // A Test [Test(Description="Basic test")] public void SimpleTest() { Console.WriteLine("SimpleTest"); } // Runs once at the end of SimpleTest only [TestTearDown("SimpleTest")] public void SpecificTestTearDown() { Console.WriteLine("SpecificTestTearDown runs only for SimpleTest"); } // A Test with a Category [Test(Category="Some Category", Description="Demonstrates a Test that's assigned to a category")] public void TestWithCategory() { Console.WriteLine("Test with category"); } // A Test with a Description [Test(Description="Demonstrates a Test that has a description")] public void TestWithDescription() { Console.WriteLine("Test with description"); Console.WriteLine("Thread: " + AppDomain.GetCurrentThreadId()); } // A Test that is expecting a specific Exception // type to be thrown or any child class [Test(Description="A Test that expects an Exception to be thrown.")] [ExpectedException(typeof(Exception))] public void ExpectedException() { Console.WriteLine("ExpectedException"); throw new Exception("This Exception is expected"); } // A Test that is expecting a specific Exception // type to be thrown with a specific message [Test(Description="A Test that expects an Exception to be thrown with a specific message.")] [ExpectedException(typeof(Exception), "This Exception is expected")] public void ExpectedExceptionWithMessage() { Console.WriteLine("ExpectedException"); throw new Exception("This Exception is expected"); } // A Test that is expecting a specific Exception // type to be thrown with a specific message and fails [Test(Description="A Test that expects an Exception to be thrown with a specific message and receives the wrong one.")] [ExpectedException(typeof(Exception), "This Exception is expected")] public void FailExpectedExceptionWithMessage() { Console.WriteLine("ExpectedException"); throw new Exception("This Exception is not expected"); } // A Test that is expecting a specific DivideByZeroException // type to be thrown or any child class [Test] [ExpectedException(typeof(Exception))] public void ExpectedDivideByZeroException() { Console.WriteLine("ExpectedException"); throw new DivideByZeroException("This Exception is expected."); } // A Test that will fail because the ExpectedException is not thrown [Test(Description="A Test that expects an Exception to be thrown, but fails because one isn't.")] [ExpectedException(typeof(Exception))] public void FailExpectedException() { Console.WriteLine("ExpectedException"); } // A Test that will be ignored (not run) by default [Test(Description="A Test that is ignored, with no reason provided.")] [Ignore] public void Ignore() { Console.WriteLine("Ignore"); } // A Test that will be ignored (not run) by default // and provides a reason [Test(Description="A Test that is ignored, with a reason provided.")] [Ignore("Some reason")] public void IgnoreWithReason() { Console.WriteLine("Ignore with reason"); } // A Test that specifies the maximum amount of memory // that the Test can consume [Test(Description="A Test who's total memory consumption should not exceed 200K")] [MaxKMemory(200)] public void MaxKMemory() { Console.WriteLine("MaxKMemory"); } // A Test that will fail if it can't be repeated // the min number of times in a second [Test(Description="A Test that should be able to run at least 10X per second.")] [MinOperationsPerSecond(10)] public void MinOperationsPerSecond() { Console.WriteLine("MinOperationsPerSecond"); } // A Test that is repeated a set number of times [Test(Description="A Test that is repeated 5X")] [Repeat(5)] public void Repeat() { Console.WriteLine("Repeat"); Console.WriteLine("Thread: " + AppDomain.GetCurrentThreadId()); } // A Test that is repeated a set number of times // with a 3 second delay in between [Test(Description="A Test that is repeated 5X, with a 3 second delay between each run.")] [Ignore] [Repeat(5,3000)] public void RepeatWithDelay() { Console.WriteLine("Repeat with delay"); Console.WriteLine("Thread: " + AppDomain.GetCurrentThreadId()); } // Runs once at the end of each Test iteration [TearDown] public void TearDown() { Console.WriteLine("TearDown"); } // Runs once at the end of each Test iteration [TestTearDown] public void TestTearDown() { Console.WriteLine("TestTearDown"); } // Runs once at the end of the TestFixture iteration [TestFixtureTearDown] public void TestFixtureTearDown() { Console.WriteLine("TestFixtureTearDown"); } } } --- NEW FILE: RollbackTransactionTest.cs --- using System; using System.EnterpriseServices; namespace Adapdev.UnitTest.Core.AdapdevTests { /// <summary> /// Summary description for RollbackTransactionTest. /// </summary> /// // [TestFixture] public class RollbackTransactionTest { [Test] // [RollbackTransaction] public void Transaction() { // Assert.IsTrue(ContextUtil.IsInTransaction, "Should be in a transaction."); Console.WriteLine("TransactionId: " + ContextUtil.TransactionId); } [Test] public void NoTransaction() { Assert.IsFalse(ContextUtil.IsInTransaction); } } } --- NEW FILE: TransactionTest.cs --- using System; using System.EnterpriseServices; using Adapdev.UnitTest; namespace Adapdev.UnitTest.Core.AdapdevTests { /// <summary> /// Summary description for AutoCommitTest. /// </summary> /// [TestFixture] public class TransactionTest { [Test] [Transaction] public void Transaction() { Assert.IsTrue(ContextUtil.IsInTransaction, "Should be in a transaction."); Console.WriteLine("TransactionId: " + ContextUtil.TransactionId); } [Test] public void NoTransaction() { Assert.IsFalse(ContextUtil.IsInTransaction); } } } --- NEW FILE: AssemblyInfo.cs --- using System.Reflection; using System.Runtime.CompilerServices; // // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. // [assembly: AssemblyTitle("")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.*")] // // In order to sign your assembly you must specify a key to use. Refer to the // Microsoft .NET Framework documentation for more information on assembly signing. // // Use the attributes below to control which key is used for signing. // // Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used. // (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be // relative to the project output directory which is // %Project Directory%\obj\<configuration>. For example, if your KeyFile is // located in the project directory, you would specify the AssemblyKeyFile // attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. // [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] [assembly: AssemblyKeyName("")] --- NEW FILE: Adapdev.UnitTest.Core.AdapdevTests.csproj --- <VisualStudioProject> <CSHARP ProjectType = "Local" ProductVersion = "7.10.3077" SchemaVersion = "2.0" ProjectGuid = "{3085922A-8F7B-4C5F-8C31-41BD7CCC0D05}" > <Build> <Settings ApplicationIcon = "" AssemblyKeyContainerName = "" AssemblyName = "Adapdev.UnitTest.Core.AdapdevTests" AssemblyOriginatorKeyFile = "" DefaultClientScript = "JScript" DefaultHTMLPageLayout = "Grid" DefaultTargetSchema = "IE50" DelaySign = "false" OutputType = "Library" PreBuildEvent = "" PostBuildEvent = "" RootNamespace = "Adapdev.UnitTest.Core.AdapdevTests" 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.UnitTest" Project = "{D450E7B3-CF48-421E-8B5E-9526E77E24C6}" Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" /> </References> </Build> <Files> <Include> <File RelPath = "AdapdevAttributes.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "AssemblyInfo.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "MultiThreadedRepeatTest.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "MultiThreadedTest.cs" SubType = "Code" BuildAction = "Compile" /> </Include> </Files> </CSHARP> </VisualStudioProject> --- NEW FILE: MultiThreadedRepeatTest.cs --- using System; using System.Threading; using Adapdev.UnitTest; namespace Adapdev.UnitTest.Core.AdapdevTests { /// <summary> /// Summary description for MultiThreadedTest. /// </summary> /// [TestFixture(IsMultiThreaded=true)] public class MultiThreadedRepeatTest { int i = 0; [Test, Repeat(5)] public void ThreadedRepeat() { i = 0; int a = 0; while(a <= 10) { i += 1; Thread.Sleep(5); a++; Console.WriteLine("Thread {0}: {1}", AppDomain.GetCurrentThreadId(), i); } Assert.IsFalse(i==10, "i equals 10, which means it was not interrupted by other Threads."); } } } --- NEW FILE: SomeTest.cs --- using System; namespace Adapdev.UnitTest.Core.AdapdevTests { /// <summary> /// Summary description for SomeTest. /// </summary> /// [TestFixture] public class SomeTest { [Test] public void TestA(){} [Test] public void TestB(){} [Test] public void TestC(){} } } --- NEW FILE: MultiThreadedTest.cs --- using System; using System.Threading; using Adapdev.UnitTest; namespace Adapdev.UnitTest.Core.AdapdevTests { /// <summary> /// Summary description for MultiThreadedTest. /// </summary> /// [TestFixture(IsMultiThreaded=true)] public class MultiThreadedTest { int i = 0; [Test] public void Thread1() { i = 0; int a = 0; while(a <= 10) { i += 4; Console.WriteLine("Thread1: " + i.ToString()); Thread.Sleep(5); a++; } Console.WriteLine("Thread1: " + i.ToString()); Assert.IsFalse(i==44, "i equals 44, which means it was not interrupted by Thread2."); } [Test] public void Thread2() { i = 0; int a = 0; while(a <= 10) { i += 10; Console.WriteLine("Thread2: " + i.ToString()); Thread.Sleep(5); a++; } Console.WriteLine("Thread2: " + i.ToString()); Assert.IsFalse(i==110, "i equals 110, which means it was not interrupted by Thread1."); } } } |
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/Util/Introspection In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.NVelocity/Util/Introspection Added Files: AmbiguousException.cs ClassMap.cs IntrospectionCacheData.cs Introspector.cs IntrospectorBase.cs MethodMap.cs Twonk.cs Log Message: --- NEW FILE: MethodMap.cs --- namespace NVelocity.Util.Introspection { using System; using System.Collections; using System.Reflection; public class MethodMap { public MethodMap() { } /// <summary> Keep track of all methods with the same name. /// </summary> //UPGRADE_NOTE: The initialization of 'methodByNameMap' was moved to method 'InitBlock'. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1005"' internal Hashtable methodByNameMap = new Hashtable(); /// <summary> Add a method to a list of methods by name. /// For a particular class we are keeping track /// of all the methods with the same name. /// </summary> public virtual void add(MethodInfo method) { String methodName = method.Name; IList l = (IList) methodByNameMap[methodName]; if (l == null) { l = new ArrayList(); methodByNameMap[methodName] = l; } l.Add(method); return; } /// <summary> Return a list of methods with the same name. /// </summary> /// <param name="String">key /// </param> /// <returns>List list of methods /// /// </returns> public virtual IList get(String key) { return (IList) methodByNameMap[key]; } /// <summary> <p> /// Find a method. Attempts to find the /// most appropriate method using the /// sense of 'specificity'. /// </p> /// /// <p> /// This turns out to be a relatively rare case /// where this is needed - however, functionality /// like this is needed. This may not be the /// optimum approach, but it works. /// </p> /// </summary> /// <param name="String">name of method /// </param> /// <param name="Object[]">params /// </param> /// <returns>Method /// /// </returns> public virtual MethodInfo find(String methodName, Object[] params_Renamed) { IList methodList = (IList) methodByNameMap[methodName]; if (methodList == null) { return null; } Type[] parameterTypes = null; MethodInfo method = null; int numMethods = methodList.Count; int bestDistance = - 2; MethodInfo bestMethod = null; Twonk bestTwonk = null; bool ambiguous = false; for (int i = 0; i < numMethods; i++) { method = (MethodInfo) methodList[i]; parameterTypes = GetMethodParameterTypes(method); /* * The methods we are trying to compare must * the same number of arguments. */ if (parameterTypes.Length == params_Renamed.Length) { /* * use the calling parameters as the baseline * and calculate the 'distance' from the parameters * to the method args. This will be useful when * determining specificity */ Twonk twonk = calcDistance(params_Renamed, parameterTypes); if (twonk != null) { /* * if we don't have anything yet, take it */ if (bestTwonk == null) { bestTwonk = twonk; bestMethod = method; } else { /* * now see which is more specific, this current * versus what we think of as the best candidate */ int val = twonk.moreSpecific(bestTwonk); //System.out.println("Val = " + val + " for " + method + " vs " + bestMethod ); if (val == 0) { /* * this means that the parameters 'crossed' * therefore, it's ambiguous because one is as * good as the other */ ambiguous = true; } else if (val == 1) { /* * the current method is clearly more * specific than the current best, so * we take the current we are testing * and clear the ambiguity flag */ ambiguous = false; bestTwonk = twonk; bestMethod = method; } } } } } /* * if ambiguous is true, it means we couldn't decide * so inform the caller... */ if (ambiguous) { throw new AmbiguousException(); } return bestMethod; } /// <summary> Calculates the distance, expressed as a vector of inheritance /// steps, between the calling args and the method args. /// There still is an issue re interfaces... /// </summary> private Twonk calcDistance(Object[] set, Type[] base_Renamed) { if (set.Length != base_Renamed.Length) return null; Twonk twonk = new Twonk(set.Length); int distance = 0; for (int i = 0; i < set.Length; i++) { /* * can I get from here to there? */ Type setclass = set[i].GetType(); if (!base_Renamed[i].IsAssignableFrom(set[i].GetType())) return null; /* * ok, I can. How many steps? */ Type c = setclass; while (c != null) { /* * is this a valid step? */ if (!base_Renamed[i].IsAssignableFrom(c)) { /* * it stopped being assignable - therefore we are looking at * an interface as our target, so move back one step * from the distance as the stop wasn't valid */ break; } if (base_Renamed[i].Equals(c)) { /* * we are equal, so no need to move forward */ break; } c = c.BaseType; twonk.distance++; twonk.vec[i]++; } } return twonk; } private static Type[] GetMethodParameterTypes(MethodInfo method) { ParameterInfo[] parms = method.GetParameters(); Type[] types = new Type[parms.Length]; for (Int32 i = 0; i < parms.Length; i++) { types[i] = parms[i].ParameterType; } return types; } } } --- NEW FILE: AmbiguousException.cs --- namespace NVelocity.Util.Introspection { using System; /// <summary> simple distinguishable exception, used when /// we run across ambiguous overloading /// </summary> public class AmbiguousException : Exception { } } --- NEW FILE: Introspector.cs --- namespace NVelocity.Util.Introspection { using System; using System.Reflection; using NVelocity.Runtime; /// <summary> This basic function of this class is to return a Method /// object for a particular class given the name of a method /// and the parameters to the method in the form of an Object[] /// /// The first time the Introspector sees a /// class it creates a class method map for the /// class in question. Basically the class method map /// is a Hastable where Method objects are keyed by a /// concatenation of the method name and the names of /// classes that make up the parameters. /// /// For example, a method with the following signature: /// /// public void method(String a, StringBuffer b) /// /// would be mapped by the key: /// /// "method" + "java.lang.String" + "java.lang.StringBuffer" /// /// This mapping is performed for all the methods in a class /// and stored for /// </summary> public class Introspector : IntrospectorBase { /// <summary> define a public string so that it can be looked for /// if interested /// </summary> public const String CACHEDUMP_MSG = "Introspector : detected classloader change. Dumping cache."; /// <summary> our engine runtime services /// </summary> private RuntimeServices rsvc = null; /// <summary> Recieves our RuntimeServices object /// </summary> public Introspector(RuntimeServices r) { this.rsvc = r; } /// <summary> Gets the method defined by <code>name</code> and /// <code>params</code> for the Class <code>c</code>. /// </summary> /// <param name="c">Class in which the method search is taking place /// </param> /// <param name="name">Name of the method being searched for /// </param> /// <param name="params">An array of Objects (not Classes) that describe the /// the parameters /// </param> /// <returns>The desired Method object. /// </returns> public override MethodInfo getMethod(Type c, String name, Object[] params_Renamed) { /* * just delegate to the base class */ try { return base.getMethod(c, name, params_Renamed); } catch (AmbiguousException ae) { /* * whoops. Ambiguous. Make a nice log message and return null... */ String msg = "Introspection Error : Ambiguous method invocation " + name + "( "; for (int i = 0; i < params_Renamed.Length; i++) { if (i > 0) msg = msg + ", "; msg = msg + params_Renamed[i].GetType().FullName; } msg = msg + ") for class " + c; rsvc.error(msg); } return null; } /// <summary> Gets the method defined by <code>name</code> and /// <code>params</code> for the Class <code>c</code>. /// </summary> /// <param name="c">Class in which the method search is taking place /// </param> /// <param name="name">Name of the method being searched for /// </param> /// <param name="params">An array of Objects (not Classes) that describe the /// the parameters /// </param> /// <returns>The desired Method object. /// </returns> public override PropertyInfo getProperty(Type c, String name) { /* * just delegate to the base class */ try { return base.getProperty(c, name); } catch (AmbiguousException ae) { /* * whoops. Ambiguous. Make a nice log message and return null... */ String msg = "Introspection Error : Ambiguous property invocation " + name + " "; msg = msg + " for class " + c; rsvc.error(msg); } return null; } /// <summary> Clears the classmap and classname /// caches, and logs that we did so /// </summary> protected internal override void clearCache() { base.clearCache(); rsvc.info(CACHEDUMP_MSG); } } } --- NEW FILE: Twonk.cs --- namespace NVelocity.Util.Introspection { /// <summary> little class to hold 'distance' information /// for calling params, as well as determine /// specificity /// </summary> internal class Twonk { public int distance; public int[] vec; public Twonk(int size) { vec = new int[size]; } public virtual int moreSpecific(Twonk other) { if (other.vec.Length != vec.Length) return - 1; bool low = false; bool high = false; for (int i = 0; i < vec.Length; i++) { if (vec[i] > other.vec[i]) { high = true; } else if (vec[i] < other.vec[i]) { low = true; } } /* * this is a 'crossing' - meaning that * we saw the parameter 'slopes' cross * this means ambiguity */ if (high && low) return 0; /* * we saw that all args were 'high', meaning * that the other method is more specific so * we are less */ if (high && !low) return - 1; /* * we saw that all points were lower, therefore * we are more specific */ if (!high && low) return 1; /* * the remainder, neither high or low * means we are the same. This really can't * happen, as it implies the same args, right? */ return 1; } } } --- NEW FILE: IntrospectorBase.cs --- namespace NVelocity.Util.Introspection { using System; using System.Collections; using System.Reflection; /// <summary> This basic function of this class is to return a Method /// object for a particular class given the name of a method /// and the parameters to the method in the form of an Object[] /// /// The first time the Introspector sees a /// class it creates a class method map for the /// class in question. Basically the class method map /// is a Hastable where Method objects are keyed by a /// concatenation of the method name and the names of /// classes that make up the parameters. /// /// For example, a method with the following signature: /// /// public void method(String a, StringBuffer b) /// /// would be mapped by the key: /// /// "method" + "java.lang.String" + "java.lang.StringBuffer" /// /// This mapping is performed for all the methods in a class /// and stored for /// </summary> /// <author> <a href="mailto:jv...@ap...">Jason van Zyl</a> /// </author> /// <author> <a href="mailto:bo...@we...">Bob McWhirter</a> /// </author> /// <author> <a href="mailto:sze...@fr...">Attila Szegedi</a> /// </author> /// <author> <a href="mailto:pau...@kr...">Paulo Gaspar</a> /// </author> /// <version> $Id: IntrospectorBase.cs,v 1.5 2005/11/16 07:01:52 intesar66 Exp $ /// </version> public class IntrospectorBase { public IntrospectorBase() { } /// <summary> Holds the method maps for the classes we know about, keyed by /// Class object. /// </summary> protected internal Hashtable classMethodMaps = new Hashtable(); /// <summary> Holds the qualified class names for the classes /// we hold in the classMethodMaps hash /// </summary> protected internal IList cachedClassNames = new ArrayList(); /// <summary> Gets the method defined by <code>name</code> and /// <code>params</code> for the Class <code>c</code>. /// </summary> /// <param name="c">Class in which the method search is taking place /// </param> /// <param name="name">Name of the method being searched for /// </param> /// <param name="params">An array of Objects (not Classes) that describe the /// the parameters /// </param> /// <returns>The desired Method object. /// </returns> public virtual MethodInfo getMethod(Type c, String name, Object[] params_Renamed) { if (c == null) { throw new Exception("Introspector.getMethod(): Class method key was null: " + name); } ClassMap classMap = null; lock (classMethodMaps) { classMap = (ClassMap) classMethodMaps[c]; /* * if we don't have this, check to see if we have it * by name. if so, then we have a classloader change * so dump our caches. */ if (classMap == null) { if (cachedClassNames.Contains(c.FullName)) { /* * we have a map for a class with same name, but not * this class we are looking at. This implies a * classloader change, so dump */ clearCache(); } classMap = createClassMap(c); } } return classMap.findMethod(name, params_Renamed); } /// <summary> Gets the method defined by <code>name</code> and /// <code>params</code> for the Class <code>c</code>. /// </summary> /// <param name="c">Class in which the method search is taking place /// </param> /// <param name="name">Name of the method being searched for /// </param> /// <param name="params">An array of Objects (not Classes) that describe the /// the parameters /// </param> /// <returns>The desired Method object. /// </returns> public virtual PropertyInfo getProperty(Type c, String name) { if (c == null) { throw new Exception("Introspector.getMethod(): Class method key was null: " + name); } ClassMap classMap = null; lock (classMethodMaps) { classMap = (ClassMap) classMethodMaps[c]; /* * if we don't have this, check to see if we have it * by name. if so, then we have a classloader change * so dump our caches. */ if (classMap == null) { if (cachedClassNames.Contains(c.FullName)) { /* * we have a map for a class with same name, but not * this class we are looking at. This implies a * classloader change, so dump */ clearCache(); } classMap = createClassMap(c); } } return classMap.findProperty(name); } /// <summary> Creates a class map for specific class and registers it in the /// cache. Also adds the qualified name to the name->class map /// for later Classloader change detection. /// </summary> protected internal virtual ClassMap createClassMap(Type c) { ClassMap classMap = new ClassMap(c); classMethodMaps[c] = classMap; cachedClassNames.Add(c.FullName); return classMap; } /// <summary> Clears the classmap and classname /// caches /// </summary> protected internal virtual void clearCache() { /* * since we are synchronizing on this * object, we have to clear it rather than * just dump it. */ classMethodMaps.Clear(); /* * for speed, we can just make a new one * and let the old one be GC'd */ cachedClassNames = new ArrayList(); } } } --- NEW FILE: ClassMap.cs --- namespace NVelocity.Util.Introspection { using System; using System.Collections; using System.Reflection; using System.Text; /// <summary> A cache of introspection information for a specific class instance. /// Keys {@link java.lang.Method} objects by a concatenation of the /// method name and the names of classes that make up the parameters. /// </summary> public class ClassMap { internal virtual Type CachedClass { get { return clazz; } } private sealed class CacheMiss { } //UPGRADE_NOTE: Final was removed from the declaration of 'CACHE_MISS '. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1003"' private static CacheMiss CACHE_MISS = new CacheMiss(); //UPGRADE_NOTE: Final was removed from the declaration of 'OBJECT '. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1003"' private static Object OBJECT = new Object(); /// /// <summary> Class passed into the constructor used to as /// the basis for the Method map. /// </summary> private Type clazz; /// <summary> Cache of Methods, or CACHE_MISS, keyed by method /// name and actual arguments used to find it. /// </summary> private Hashtable methodCache = new Hashtable(); private Hashtable propertyCache = new Hashtable(); private MethodMap methodMap = new MethodMap(); /// <summary> Standard constructor /// </summary> public ClassMap(Type clazz) { this.clazz = clazz; populateMethodCache(); populatePropertyCache(); } public ClassMap() { } /// <returns>the class object whose methods are cached by this map. /// </returns> /// <summary> Find a Method using the methodKey /// provided. /// /// Look in the methodMap for an entry. If found, /// it'll either be a CACHE_MISS, in which case we /// simply give up, or it'll be a Method, in which /// case, we return it. /// /// If nothing is found, then we must actually go /// and introspect the method from the MethodMap. /// </summary> public virtual System.Reflection.MethodInfo findMethod(String name, Object[] params_Renamed) { String methodKey = makeMethodKey(name, params_Renamed); Object cacheEntry = methodCache[methodKey]; if (cacheEntry == CACHE_MISS) { return null; } if (cacheEntry == null) { try { cacheEntry = methodMap.find(name, params_Renamed); } catch (AmbiguousException ae) { /* * that's a miss :) */ methodCache[methodKey] = CACHE_MISS; throw ae; } if (cacheEntry == null) { methodCache[methodKey] = CACHE_MISS; } else { methodCache[methodKey] = cacheEntry; } } // Yes, this might just be null. return (System.Reflection.MethodInfo) cacheEntry; } /// <summary> Find a Method using the methodKey /// provided. /// /// Look in the methodMap for an entry. If found, /// it'll either be a CACHE_MISS, in which case we /// simply give up, or it'll be a Method, in which /// case, we return it. /// /// If nothing is found, then we must actually go /// and introspect the method from the MethodMap. /// </summary> public virtual PropertyInfo findProperty(String name) { Object cacheEntry = propertyCache[name]; if (cacheEntry == CACHE_MISS) { return null; } // Yes, this might just be null. return (PropertyInfo) cacheEntry; } /// <summary> Populate the Map of direct hits. These /// are taken from all the public methods /// that our class provides. /// </summary> private void populateMethodCache() { StringBuilder methodKey; /* * get all publicly accessible methods */ System.Reflection.MethodInfo[] methods = getAccessibleMethods(clazz); /* * map and cache them */ for (int i = 0; i < methods.Length; i++) { System.Reflection.MethodInfo method = methods[i]; /* * now get the 'public method', the method declared by a * public interface or class. (because the actual implementing * class may be a facade... */ System.Reflection.MethodInfo publicMethod = getPublicMethod(method); /* * it is entirely possible that there is no public method for * the methods of this class (i.e. in the facade, a method * that isn't on any of the interfaces or superclass * in which case, ignore it. Otherwise, map and cache */ if (publicMethod != null) { methodMap.add(publicMethod); methodCache[makeMethodKey(publicMethod)] = publicMethod; } } } private void populatePropertyCache() { StringBuilder methodKey; /* * get all publicly accessible methods */ PropertyInfo[] properties = getAccessibleProperties(clazz); /* * map and cache them */ for (int i = 0; i < properties.Length; i++) { PropertyInfo property = properties[i]; /* * now get the 'public method', the method declared by a * public interface or class. (because the actual implementing * class may be a facade... */ PropertyInfo publicProperty = getPublicProperty(property); /* * it is entirely possible that there is no public method for * the methods of this class (i.e. in the facade, a method * that isn't on any of the interfaces or superclass * in which case, ignore it. Otherwise, map and cache */ if (publicProperty != null) { //propertyMap.add(publicProperty); propertyCache[publicProperty.Name] = publicProperty; } } } /// <summary> Make a methodKey for the given method using /// the concatenation of the name and the /// types of the method parameters. /// </summary> private String makeMethodKey(System.Reflection.MethodInfo method) { //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.reflect.Method.getParameterTypes' may return a different value. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1043"' ParameterInfo[] parameterTypes = method.GetParameters(); StringBuilder methodKey = new StringBuilder(method.Name); for (int j = 0; j < parameterTypes.Length; j++) { /* * If the argument type is primitive then we want * to convert our primitive type signature to the * corresponding Object type so introspection for * methods with primitive types will work correctly. */ // TODO: I don't think that this is needed in .Net - boxing will happen and the types will still be available. // if (parameterTypes[j].GetType().IsPrimitive) { // if (parameterTypes[j].Equals(System.Type.GetType("System.Boolean"))) // methodKey.Append("java.lang.Boolean"); // else if (parameterTypes[j].Equals(System.Type.GetType("System.Byte"))) // methodKey.Append("java.lang.Byte"); // else if (parameterTypes[j].Equals(System.Type.GetType("System.Char"))) // methodKey.Append("java.lang.Character"); // else if (parameterTypes[j].Equals(System.Type.GetType("System.Double"))) // methodKey.Append("java.lang.Double"); // else if (parameterTypes[j].Equals(System.Type.GetType("System.Single"))) // methodKey.Append("java.lang.Float"); // else { // //UPGRADE_TODO: Field java.lang.Integer.TYPE was not converted. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1095"' // if (parameterTypes[j].Equals(typeof(Int32))) // methodKey.Append("System.Int32"); // else { // //UPGRADE_TODO: Field java.lang.Long.TYPE was not converted. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1095"' // if (parameterTypes[j].Equals(typeof(Int64))) // methodKey.Append("System.Int64"); // else if (parameterTypes[j].Equals(System.Type.GetType("System.Int16"))) // methodKey.Append("System.Int16"); // } // } // } // else { // methodKey.Append(parameterTypes[j].FullName); // } methodKey.Append(parameterTypes[j].ParameterType.FullName); } return methodKey.ToString(); } private static String makeMethodKey(String method, Object[] params_Renamed) { StringBuilder methodKey = new StringBuilder().Append(method); if (params_Renamed != null) { for (int j = 0; j < params_Renamed.Length; j++) { Object arg = params_Renamed[j]; if (arg == null) { arg = OBJECT; } methodKey.Append(arg.GetType().FullName); } } return methodKey.ToString(); } /// <summary> Retrieves public methods for a class. In case the class is not /// public, retrieves methods with same signature as its public methods /// from public superclasses and interfaces (if they exist). Basically /// upcasts every method to the nearest acccessible method. /// </summary> private static System.Reflection.MethodInfo[] getAccessibleMethods(Type clazz) { System.Reflection.MethodInfo[] methods = clazz.GetMethods(); // TODO: the rest of this method is trying to determine what is supposed to be callable - I think .Net just returns what is callable return methods; /* * Short circuit for the (hopefully) majority of cases where the * clazz is public */ //UPGRADE_TODO: Method java.lang.reflect.Modifier.isPublic was not converted. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1095"' //UPGRADE_ISSUE: Method 'java.lang.Class.getModifiers' was not converted. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1000_javalangClassgetModifiers"' if (clazz.IsPublic) { return methods; } /* * No luck - the class is not public, so we're going the longer way. */ MethodInfo[] methodInfos = new MethodInfo[methods.Length]; for (int i = methods.Length; i-- > 0; ) { methodInfos[i] = new MethodInfo(methods[i]); } int upcastCount = getAccessibleMethods(clazz, methodInfos, 0); /* * Reallocate array in case some method had no accessible counterpart. */ if (upcastCount < methods.Length) { methods = new System.Reflection.MethodInfo[upcastCount]; } int j = 0; for (int i = 0; i < methodInfos.Length; ++i) { MethodInfo methodInfo = methodInfos[i]; if (methodInfo.upcast) { methods[j++] = methodInfo.method; } } return methods; } private static PropertyInfo[] getAccessibleProperties(Type clazz) { PropertyInfo[] properties = clazz.GetProperties(); //TODO return properties; /* * Short circuit for the (hopefully) majority of cases where the * clazz is public */ if (clazz.IsPublic) { return properties; } /* * No luck - the class is not public, so we're going the longer way. */ properties = new PropertyInfo[0]; return properties; // TODO // MethodInfo[] methodInfos = new MethodInfo[methods.Length]; // // for (int i = methods.Length; i-- > 0; ) { // methodInfos[i] = new MethodInfo(methods[i]); // } // // int upcastCount = getAccessibleMethods(clazz, methodInfos, 0); // // /* // * Reallocate array in case some method had no accessible counterpart. // */ // // if (upcastCount < methods.Length) { // methods = new System.Reflection.MethodInfo[upcastCount]; // } // // int j = 0; // for (int i = 0; i < methodInfos.Length; ++i) { // MethodInfo methodInfo = methodInfos[i]; // if (methodInfo.upcast) { // methods[j++] = methodInfo.method; // } // } // return methods; } /// <summary> /// Recursively finds a match for each method, starting with the class, and then /// searching the superclass and interfaces. /// </summary> /// <param name="clazz">Class to check</param> /// <param name="methodInfos">array of methods we are searching to match</param> /// <param name="upcastCount">current number of methods we have matched</param> /// <returns>count of matched methods</returns> private static int getAccessibleMethods(Type clazz, MethodInfo[] methodInfos, int upcastCount) { int l = methodInfos.Length; /* * if this class is public, then check each of the currently * 'non-upcasted' methods to see if we have a match */ //UPGRADE_TODO: Method java.lang.reflect.Modifier.isPublic was not converted. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1095"' //UPGRADE_ISSUE: Method 'java.lang.Class.getModifiers' was not converted. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1000_javalangClassgetModifiers"' if (clazz.IsPublic) { for (int i = 0; i < l && upcastCount < l; ++i) { try { MethodInfo methodInfo = methodInfos[i]; if (!methodInfo.upcast) { methodInfo.tryUpcasting(clazz); upcastCount++; } } catch (MethodAccessException e) { /* * Intentionally ignored - it means * it wasn't found in the current class */ } } /* * Short circuit if all methods were upcast */ if (upcastCount == l) { return upcastCount; } } /* * Examine superclass */ Type superclazz = clazz.BaseType; if (superclazz != null) { upcastCount = getAccessibleMethods(superclazz, methodInfos, upcastCount); /* * Short circuit if all methods were upcast */ if (upcastCount == l) { return upcastCount; } } /* * Examine interfaces. Note we do it even if superclazz == null. * This is redundant as currently java.lang.Object does not implement * any interfaces, however nothing guarantees it will not in future. */ Type[] interfaces = clazz.GetInterfaces(); for (int i = interfaces.Length; i-- > 0; ) { upcastCount = getAccessibleMethods(interfaces[i], methodInfos, upcastCount); /* * Short circuit if all methods were upcast */ if (upcastCount == l) { return upcastCount; } } return upcastCount; } /// <summary> For a given method, retrieves its publicly accessible counterpart. /// This method will look for a method with same name /// and signature declared in a public superclass or implemented interface of this /// method's declaring class. This counterpart method is publicly callable. /// </summary> /// <param name="method">a method whose publicly callable counterpart is requested. /// </param> /// <returns>the publicly callable counterpart method. Note that if the parameter /// method is itself declared by a public class, this method is an identity /// function. /// </returns> public static System.Reflection.MethodInfo getPublicMethod(System.Reflection.MethodInfo method) { Type clazz = method.DeclaringType; //TODO see other todo messages in this class return method; /* * Short circuit for (hopefully the majority of) cases where the declaring * class is public. */ if (clazz.IsPublic) { return method; } return getPublicMethod(clazz, method.Name, GetMethodParameterTypes(method)); } public static PropertyInfo getPublicProperty(PropertyInfo property) { Type clazz = property.DeclaringType; // TODO: return property; /* * Short circuit for (hopefully the majority of) cases where the declaring * class is public. */ if (clazz.IsPublic) { return property; } //TODO return null; // return getPublicMethod(clazz, method.Name, GetMethodParameterTypes(method)); } /// <summary> Looks up the method with specified name and signature in the first public /// superclass or implemented interface of the class. /// </summary> /// <param name="class">the class whose method is sought /// </param> /// <param name="name">the name of the method /// </param> /// <param name="paramTypes">the classes of method parameters /// </param> private static System.Reflection.MethodInfo getPublicMethod(Type clazz, String name, Type[] paramTypes) { /* * if this class is public, then try to get it */ if (clazz.IsPublic) { try { return clazz.GetMethod(name, (Type[]) paramTypes); } catch (MethodAccessException e) { /* * If the class does not have the method, then neither its * superclass nor any of its interfaces has it so quickly return * null. */ return null; } } /* * try the superclass */ Type superclazz = clazz.BaseType; if (superclazz != null) { System.Reflection.MethodInfo superclazzMethod = getPublicMethod(superclazz, name, paramTypes); if (superclazzMethod != null) { return superclazzMethod; } } /* * and interfaces */ Type[] interfaces = clazz.GetInterfaces(); for (int i = 0; i < interfaces.Length; ++i) { System.Reflection.MethodInfo interfaceMethod = getPublicMethod(interfaces[i], name, paramTypes); if (interfaceMethod != null) { return interfaceMethod; } } return null; } /// <summary> Used for the iterative discovery process for public methods. /// </summary> private sealed class MethodInfo { internal System.Reflection.MethodInfo method; internal String name; internal Type[] parameterTypes; internal bool upcast; internal MethodInfo(System.Reflection.MethodInfo method) { this.method = null; name = method.Name; parameterTypes = GetMethodParameterTypes(method); upcast = false; } internal void tryUpcasting(Type clazz) { method = clazz.GetMethod(name, (Type[]) parameterTypes); name = null; parameterTypes = null; upcast = true; } } private static Type[] GetMethodParameterTypes(System.Reflection.MethodInfo method) { ParameterInfo[] parms = method.GetParameters(); Type[] types = new Type[parms.Length]; for (Int32 i = 0; i < parms.Length; i++) { types[i] = parms[i].ParameterType; } return types; } } } --- NEW FILE: IntrospectionCacheData.cs --- namespace NVelocity.Util.Introspection { 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> Holds information for node-local context data introspection /// information. /// * /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version> $Id: IntrospectionCacheData.cs,v 1.5 2005/11/16 07:01:52 intesar66 Exp $ /// /// </version> public class IntrospectionCacheData { /// /// <summary> Object to pair with class - currently either a Method or /// AbstractExecutor. It can be used in any way the using node /// wishes. /// </summary> public Object thingy; /* * Class of context data object associated with the introspection * information */ public Type contextData; } } |
From: Sean M. <int...@us...> - 2005-11-16 07:02:02
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.Data/Xml In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.Data/Xml Added Files: ProviderConfig.cs ProviderConfig.xml ProviderConfig.xsd ProviderConfig.xsx ProviderInfo.cs ProviderInfo.xml ProviderInfo.xsd ProviderInfo.xsx Log Message: --- NEW FILE: ProviderConfig.cs --- using System; using System.Reflection; using System.Xml; using System.Data; using System.IO; using System.Text.RegularExpressions; namespace Adapdev.Data { /// <summary> /// DBConnectionManager manages the loading of the ADAPDEV.XML file into the DBConnection* classes /// </summary> [System.ComponentModel.DesignerCategoryAttribute("code")] public class ProviderConfig : DataSet { private DbConnectionTypes _connectionTypes = null; public ProviderConfig() : this( FindConfigFile() ) { } public ProviderConfig( string config ) { _connectionTypes = LoadConfig ( config ); } // Provides Get Access the the COnnection Types Instance public DbConnectionTypes ConnectionTypes { get { return _connectionTypes; } } /// <summary> /// Loads a config file into a XMLDocument and populates a DBConnectionTypes collection of the /// database connection details found in the config file. /// </summary> /// <param name="config">The name (and path) of a config file containing <connection> elements</param> /// <returns>A Collection of Connection Types</returns> private DbConnectionTypes LoadConfig ( string config ) { try { this.ReadXml(config); DbConnectionTypes connectionTypes = new DbConnectionTypes(); DataRow connectionsRow = this.Tables["connections"].Rows[0]; // Read the available connections from the connections collection // -------------------------------------------------------------- foreach (DataRow connectionRow in connectionsRow.GetChildRows("connections_connection")) { DbConnectionType connectionType = new DbConnectionType(); connectionType.Name = connectionRow["name"].ToString(); connectionType.DbTypeName = connectionRow["type"].ToString(); connectionType.InternalProviderName = connectionRow["internalProvider"].ToString(); // Read the Settings for this connection type // -------------------------------------------------------------- foreach (DataRow settingsRow in connectionRow.GetChildRows("connection_settings")) { if (settingsRow.Table.Columns.Contains("file")) { connectionType.SupportsFile = GetSettingState(settingsRow["file"].ToString(),false); connectionType.PromptFile = GetSettingValue(settingsRow["file"].ToString()); } if (settingsRow.Table.Columns.Contains("server")) { connectionType.SupportsServer = GetSettingState(settingsRow["server"].ToString(),true); connectionType.PromptServer = GetSettingValue(settingsRow["server"].ToString()); } if (settingsRow.Table.Columns.Contains("name")) { connectionType.SupportsName = GetSettingState(settingsRow["name"].ToString(),true); connectionType.PromptName = GetSettingValue(settingsRow["name"].ToString()); } if (settingsRow.Table.Columns.Contains("userid")) { connectionType.SupportsUserID = GetSettingState(settingsRow["userid"].ToString(),true); connectionType.PromptUserID = GetSettingValue(settingsRow["userid"].ToString()); } if (settingsRow.Table.Columns.Contains("password")) { connectionType.SupportsPassword = GetSettingState(settingsRow["password"].ToString(),true); connectionType.PromptPassword = GetSettingValue(settingsRow["password"].ToString()); } if (settingsRow.Table.Columns.Contains("filter")) { connectionType.SupportsFilter = GetSettingState(settingsRow["filter"].ToString(),false); connectionType.PromptFilter = GetSettingValue(settingsRow["filter"].ToString()); } } // Read each of the Providers Details // -------------------------------------------------------------- foreach (DataRow providersRow in connectionRow.GetChildRows("connection_providers")) { foreach (DataRow providerRow in providersRow.GetChildRows("providers_provider")) { DbConnectionProvider connectionProvider = new DbConnectionProvider(); connectionProvider.Name = providerRow["name"].ToString(); connectionProvider.ProviderTypeName = providerRow["type"].ToString(); connectionProvider.Parent = connectionType; connectionProvider.Template = Regex.Replace(providerRow["provider_Text"].ToString(), @"[\r\t\n]", ""); if (providerRow.Table.Columns.Contains("allowEmptyParameters")) connectionProvider.AllowEmptyParameters = GetSettingState(providerRow["allowEmptyParameters"].ToString(), true); if (providerRow.Table.Columns.Contains("enabled")) connectionProvider.Enabled = GetSettingState(providerRow["enabled"].ToString(),true); if (providerRow.Table.Columns.Contains("fileMask")) connectionProvider.FileMask = providerRow["fileMask"].ToString(); connectionType.Providers.Add(connectionProvider); } } connectionTypes.Add(connectionType); } return connectionTypes; } catch (Exception ex) { throw new ApplicationException(String.Format("Could not reference the ProviderConfig.xml configuration file: {0}\n{1}", config, ex.Message)); } } /// <summary> /// Returns the State if defined for a property. If it is false, return false /// otherwise return true. /// </summary> /// <param name="setting"></param> /// <returns></returns> private bool GetSettingState(string setting, bool defaultFlag) { if (setting == null) return defaultFlag; if (setting.Equals(string.Empty)) return defaultFlag; try { return Convert.ToBoolean(setting); } catch { return true; } } /// <summary> /// Return the setting for a property. If the property was "false" return a empty string /// or if the property was "true" return a empty string, otherwise return the contents. /// </summary> /// <param name="setting"></param> /// <returns></returns> private string GetSettingValue(string setting) { if (setting == null) return string.Empty; if (setting.Equals(string.Empty)) return string.Empty; try { bool flag = Convert.ToBoolean(setting); return string.Empty; } catch { return setting.Trim(); } } /// <summary> /// Determine the location and allow overriding of the ConfigFile /// </summary> /// <returns></returns> public static string FindConfigFile () { string configFile = String.Empty; string possibleConfig = String.Empty; // Look in the current application folder for the file if (configFile == String.Empty) { possibleConfig = AppDomain.CurrentDomain.BaseDirectory + @"ProviderConfig.XML"; if (System.IO.File.Exists(possibleConfig)) { configFile = possibleConfig; } } // If not found there, then override with a hardcoded default // TODO: Allow this to be overriden with the commandline if (configFile == String.Empty) { possibleConfig = @"..\..\..\..\..\Adapdev\src\Adapdev.Data\Xml\ProviderConfig.xml"; if (System.IO.File.Exists(possibleConfig)) { configFile = possibleConfig; } } if (configFile == String.Empty) { throw new ApplicationException(String.Format("Could not find the ProviderConfig.xml configuration file.\n It should exist in {0}", AppDomain.CurrentDomain.BaseDirectory)); } return configFile; } } } --- NEW FILE: ProviderInfo.xsd --- <?xml version="1.0"?> <xs:schema id="ProvidersInfo" targetNamespace="http://tempuri.org/ProviderInfo.xsd" xmlns:mstns="http://tempuri.org/ProviderInfo.xsd" xmlns="http://tempuri.org/ProviderInfo.xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" attributeFormDefault="qualified" elementFormDefault="qualified"> <xs:element name="ProvidersInfo" msdata:IsDataSet="true" msdata:EnforceConstraints="False"> <xs:complexType> <xs:choice maxOccurs="unbounded"> <xs:element name="ProviderInfo"> <xs:complexType> <xs:sequence> <xs:element name="Type" minOccurs="0" maxOccurs="unbounded"> <xs:complexType> <xs:sequence> <xs:element name="Id" type="xs:string" minOccurs="0" /> <xs:element name="Name" type="xs:string" minOccurs="0" /> <xs:element name="Object" type="xs:string" minOccurs="0" /> <xs:element name="Prefix" type="xs:string" minOccurs="0" /> <xs:element name="Postfix" type="xs:string" minOccurs="0" /> <xs:element name="Default" type="xs:string" minOccurs="0" /> <xs:element name="TestDefault" type="xs:string" minOccurs="0" /> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> <xs:attribute name="Name" form="unqualified" type="xs:string" /> </xs:complexType> </xs:element> </xs:choice> </xs:complexType> </xs:element> </xs:schema> --- NEW FILE: ProviderConfig.xml --- <?xml version="1.0" encoding="utf-8"?> <adapdev xmlns="http://tempuri.org/ProviderConfig.xsd"> <connections> <!-- You MUST specify a OLEDB connecion type as a minimum for a provider and specifiy it in the internalProvider attribute. Defining a connection string, use the following field replacement tokens: {0} Server Name or file location {1} Data Source or Initial Catalog Name {2} User Name or UserID to connect as {3} Password Available Settings are: <server file="true">Prompt</server> <name>Prompt<name> <userid>Prompt</userid> <password>Prompt</password> Note: When specifying a Driver={name} you must specify using {{ eg: Driver={{SQL Server}} --> <connection name="SQL Server" type="SQLSERVER" internalProvider="OLEDB"> <settings file="false" server="true" name="true" userid="true" password="true"/> <providers> <provider name="Sql Connect" type="SQLSERVER" allowEmptyParameters="true"> Data Source={0}; Initial Catalog={1}; User ID={2}; Password={3}; Trusted_Connection=false; </provider> <provider name="OLEDB" type="OLEDB"> Provider=sqloledb;Data Source={0}; Initial Catalog={1}; User ID={2}; Password={3}; </provider> <provider name="ODBC" type="ODBC" enabled="false"> Driver={{SQL Server}};Server={0}; Database={1}; Uid={2}; Pwd={3}; </provider> </providers> </connection> <connection name="SQL Server - Trusted" type="SQLSERVER" internalProvider="OLEDB"> <settings file="false" server="true" name="true" userid="false" password="false"/> <providers> <provider name="Sql Connect" type="SQLSERVER"> Data Source={0}; Initial Catalog={1}; Integrated Security=SSPI; </provider> <provider name="OLEDB" type="OLEDB"> Provider=sqloledb;Data Source={0}; Initial Catalog={1}; Integrated Security=SSPI </provider> <provider name="ODBC" type="ODBC" enabled="false"> Driver={{SQL Server}};Server={0}; Database={1}; Trusted_Connection=yes; </provider> </providers> </connection> <connection name="Microsoft Access" type="ACCESS" internalProvider="OLEDB"> <settings file="true" server="false" name="false" userid="true" password="true"/> <providers> <provider name="ODBC" type="ODBC" enabled="false"> Driver={{Microsoft Access Driver (*.mdb)}}; Dbq={0}; Uid={2}; Pwd={3}; </provider> <provider name="OLEDB" type="OLEDB" fileMask="Access Database (*.mdb)|*.mdb"> Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0}; User ID={2}; Password={3}; </provider> <provider name="OLEDB (DNS)" type="OLEDB" fileMask="File Data Sources (*.dsn)|*.dsn"> DSN={0};Uid={2};Pwd={3}; </provider> </providers> </connection> <connection name="Oracle" type="ORACLE" internalProvider="OLEDB (Microsoft)"> <settings file="false" server="true" name="false" userid="true" password="true" filter="Schema"/> <providers> <provider name="Oracle Connect" type="ORACLE" enabled="true"> Data Source={0}; User ID={2}; Password={3}; Integrated Security=no; </provider> <provider name="OLEDB (Microsoft)" type="OLEDB" enabled="true"> Provider=msdaora; Data Source={0}; Database={1}; User ID={2}; Password={3}; </provider> <provider name="OLEDB (Oracle)" type="OLEDB" enabled="false"> Provider=OraOLEDB; Data Source={0}; User ID={2}; Password={3}; </provider> <provider name="ODBC" type="ODBC" enabled="false"> Driver={{Microsoft ODBC for Oracle}}; Server={0}; Uid={2}; Pwd={3} </provider> </providers> </connection> <connection name="Oracle - Trusted" type="ORACLE" internalProvider="OLEDB (Oracle)"> <settings file="false" server="true" name="Schema" userid="true" password="true"/> <providers> <provider name="Oracle Connect" type="ORACLE" enabled="false"> Data Source={0}; Integrated Security=yes; </provider> <provider name="OLEDB (Oracle)" type="OLEDB" enabled="false"> Provider=OraOLEDB; Data Source={0}; OSAuthent=1; </provider> </providers> </connection> <connection name="MySql" type="MYSQL" internalProvider="MySql Native"> <settings file="false" server="true" name="true" userid="true" password="true"/> <providers> <provider name="MySql Native" type="MYSQL" enabled="true"> Data Source={0};Database={1};User ID={2};Password={3}; </provider> <provider name="ODBC" type="ODBC" enabled="false"> DRIVER={{MySQL ODBC 3.51 Driver}};SERVER={0};DATABASE={1};USER={2};PASSWORD={3}; </provider> </providers> </connection> </connections> </adapdev> --- NEW FILE: ProviderConfig.xsx --- <?xml version="1.0" encoding="utf-8"?> <!--This file is auto-generated by the XML Schema Designer. It holds layout information for components on the designer surface.--> <XSDDesignerLayout /> --- NEW FILE: ProviderConfig.xsd --- <?xml version="1.0"?> <xs:schema id="adapdev" targetNamespace="http://tempuri.org/ProviderConfig.xsd" xmlns:mstns="http://tempuri.org/ProviderConfig.xsd" xmlns="http://tempuri.org/ProviderConfig.xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" attributeFormDefault="qualified" elementFormDefault="qualified"> <xs:element name="adapdev" msdata:IsDataSet="true" msdata:Locale="en-NZ" msdata:EnforceConstraints="False"> <xs:complexType> <xs:choice maxOccurs="unbounded"> <xs:element name="connections"> <xs:complexType> <xs:sequence> <xs:element name="connection" minOccurs="0" maxOccurs="unbounded"> <xs:complexType> <xs:sequence> <xs:element name="settings" minOccurs="0" maxOccurs="unbounded"> <xs:complexType> <xs:attribute name="file" form="unqualified" type="xs:string" /> <xs:attribute name="server" form="unqualified" type="xs:string" /> <xs:attribute name="name" form="unqualified" type="xs:string" /> <xs:attribute name="userid" form="unqualified" type="xs:string" /> <xs:attribute name="password" form="unqualified" type="xs:string" /> <xs:attribute name="filter" form="unqualified" type="xs:string" /> </xs:complexType> </xs:element> <xs:element name="providers" minOccurs="0" maxOccurs="unbounded"> <xs:complexType> <xs:sequence> <xs:element name="provider" nillable="true" minOccurs="0" maxOccurs="unbounded"> <xs:complexType> <xs:simpleContent msdata:ColumnName="provider_Text" msdata:Ordinal="3"> <xs:extension base="xs:string"> <xs:attribute name="name" form="unqualified" type="xs:string" /> <xs:attribute name="type" form="unqualified" type="xs:string" /> <xs:attribute name="allowEmptyParameters" form="unqualified" type="xs:string" /> <xs:attribute name="enabled" form="unqualified" type="xs:string" /> <xs:attribute name="fileMask" form="unqualified" type="xs:string" /> </xs:extension> </xs:simpleContent> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> <xs:attribute name="name" form="unqualified" type="xs:string" /> <xs:attribute name="type" form="unqualified" type="xs:string" /> <xs:attribute name="internalProvider" form="unqualified" type="xs:string" /> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:choice> </xs:complexType> </xs:element> </xs:schema> --- NEW FILE: ProviderInfo.cs --- (This appears to be a binary file; contents omitted.) --- NEW FILE: ProviderInfo.xml --- <?xml version="1.0" encoding="utf-8" ?> <ProvidersInfo xmlns="http://tempuri.org/ProviderInfo.xsd"> <ProviderInfo Name="oledb"> <Type> <Id>20</Id> <Name>BigInt</Name> <Object>Int64</Object> <Prefix></Prefix> <Postfix></Postfix> <Default>0</Default> <TestDefault>2</TestDefault> </Type> <Type> <Id>128</Id> <Name>Binary</Name> <Object>Byte[]</Object> <Prefix></Prefix> <Postfix></Postfix> <Default>null</Default> [...1486 lines suppressed...] <Type> <Id>252</Id> <Name>longtext</Name> <Object>Byte[]</Object> <Prefix>'</Prefix> <Postfix>'</Postfix> <Default></Default> <TestDefault></TestDefault> </Type>--> <Type> <Id>254</Id> <Name>uint</Name> <Object>Int32</Object> <Prefix></Prefix> <Postfix></Postfix> <Default>0</Default> <TestDefault>1</TestDefault> </Type> </ProviderInfo> </ProvidersInfo> --- NEW FILE: ProviderInfo.xsx --- <?xml version="1.0" encoding="utf-8"?> <!--This file is auto-generated by the XML Schema Designer. It holds layout information for components on the designer surface.--> <XSDDesignerLayout /> |
From: Sean M. <int...@us...> - 2005-11-16 07:02:01
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.Tests/Diagnostics In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.Tests/Diagnostics Added Files: CPUMeterTest.cs PerfTimerFactoryTest.cs Log Message: --- NEW FILE: CPUMeterTest.cs --- using System; namespace Adapdev.Diagnostics.Tests { using System.Threading; using NUnit.Framework; /// <summary> /// Summary description for CPUMeterTest. /// </summary> /// [TestFixture] public class CPUMeterTest { [Test] public void GetCpuUtilizationForCurrentProcess() { CPUMeter mtr = new CPUMeter(); this.Process(mtr); } [Test] public void GetCpuUtilizationForSystemProcess() { // System PID is 4 CPUMeter mtr = new CPUMeter(4); this.Process(mtr); } [Test] public void GetCpuUtilizationForCurrentProcessOverTime() { CPUMeter mtr = new CPUMeter(); this.Process(mtr); mtr.ResetCounter(); Thread.Sleep(1000); this.Process(mtr); } private double Process(CPUMeter cpuMeter) { double result = 0; for (int i = 0;i<100000000; i++) { result = result+Math.Sin(i); } double usage = cpuMeter.GetCpuUtilization(); Console.WriteLine("Done. CPU Usage {0:#00.00} %", usage); return usage; } } } --- NEW FILE: PerfTimerFactoryTest.cs --- using System; using Adapdev.Diagnostics; namespace Adapdev.Diagnostics.Tests { using System.Threading; using NUnit.Framework; /// <summary> /// Summary description for PerfTimerFactoryTest. /// </summary> /// [TestFixture] public class PerfTimerFactoryTest { [Test] public void HiResSeconds() { double result = this.GetOutput(PerfTimerType.HIRESSECONDS); Assert.IsTrue(result != 1000); Assert.IsTrue(result < 1.0 && result > 0.1); } [Test] public void Millisecond() { double result = this.GetOutput(PerfTimerType.MILLISECONDS); Assert.AreEqual(1000, result); } [Test] public void Minutes() { double result = this.GetOutput(PerfTimerType.MINUTES); Assert.AreEqual(0.0166666666666667, result); } [Test] public void Seconds() { double result = this.GetOutput(PerfTimerType.SECONDS); Assert.AreEqual(1, result); } [Test] public void Ticks() { double result = this.GetOutput(PerfTimerType.TICKS); Assert.AreEqual(1000, result); } private double GetOutput(PerfTimerType timer) { IPerfTimer t = PerfTimerFactory.GetPerfTimer(timer); t.Start(); Thread.Sleep(1000); t.Stop(); Console.WriteLine(timer.ToString() + ": " + t.Duration); return t.Duration; } } } |
From: Sean M. <int...@us...> - 2005-11-16 07:02:00
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/Runtime/Directive In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.NVelocity/Runtime/Directive Added Files: Directive.cs DirectiveConstants.cs Foreach.cs Include.cs Literal.cs Macro.cs Parse.cs ParseDirectiveException.cs VMProxyArg.cs VelocimacroProxy.cs Log Message: --- NEW FILE: Directive.cs --- namespace NVelocity.Runtime.Directive { /* * The Apache Software License, Version 1.1 * * Copyright (c) 2000-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 System.IO; using NVelocity.Context; using NVelocity.Runtime.Parser.Node; /// <summary> Base class for all directives used in Velocity. /// * /// </summary> /// <author> <a href="mailto:jv...@ap...">Jason van Zyl</a> /// </author> /// <version> $Id: Directive.cs,v 1.5 2005/11/16 07:01:50 intesar66 Exp $ /// /// </version> public abstract class Directive : DirectiveConstants //,System.ICloneable { public abstract String Name { get; set; } public abstract int Type { get; } public virtual int Line { get { return line; } } public virtual int Column { get { return column; } } private int line = 0; private int column = 0; protected internal RuntimeServices rsvc = null; /// <summary>Return the name of this directive /// </summary> /// <summary>Get the directive type BLOCK/LINE /// </summary> /// <summary>Allows the template location to be set /// </summary> public virtual void setLocation(int line, int column) { this.line = line; this.column = column; } /// <summary>for log msg purposes /// </summary> /// <summary>for log msg purposes /// </summary> /// <summary> How this directive is to be initialized. /// </summary> public virtual void init(RuntimeServices rs, InternalContextAdapter context, INode node) { rsvc = rs; // int i, k = node.jjtGetNumChildren(); //for (i = 0; i < k; i++) // node.jjtGetChild(i).init(context, rs); } /// <summary> How this directive is to be rendered /// </summary> public abstract bool render(InternalContextAdapter context, TextWriter writer, INode node); } } --- NEW FILE: VelocimacroProxy.cs --- namespace NVelocity.Runtime.Directive { using System; using System.Collections; using System.IO; using NVelocity.Context; using NVelocity.Exception; using NVelocity.Runtime.Parser; using NVelocity.Runtime.Parser.Node; using NVelocity.Runtime.Visitor; using NVelocity.Util; /// <summary> /// VelocimacroProxy.java /// a proxy Directive-derived object to fit with the current directive system /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a></author> /// <version> $Id: VelocimacroProxy.cs,v 1.5 2005/11/16 07:01:50 intesar66 Exp $ </version> public class VelocimacroProxy : Directive { public VelocimacroProxy() { InitBlock(); } private void InitBlock() { proxyArgHash = new Hashtable(); } public override String Name { get { return macroName; } set { macroName = value; } } public override int Type { get { return DirectiveConstants_Fields.LINE; } } public virtual String[] ArgArray { set { argArray = value; /* * get the arg count from the arg array. remember that the arg array * has the macro name as it's 0th element */ numMacroArgs = argArray.Length - 1; } } public virtual SimpleNode NodeTree { set { nodeTree = value; } } public virtual int NumArgs { get { return numMacroArgs; } } public virtual String Macrobody { set { macroBody = value; } } public virtual String Namespace { set { this.namespace_Renamed = value; } } private String macroName = ""; private String macroBody = ""; private String[] argArray = null; private SimpleNode nodeTree = null; private int numMacroArgs = 0; private String namespace_Renamed = ""; //UPGRADE_NOTE: Field init was renamed. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1029"' private bool init_Renamed_Field = false; private String[] callingArgs; private int[] callingArgTypes; //UPGRADE_NOTE: The initialization of 'proxyArgHash' was moved to method 'InitBlock'. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1005"' private Hashtable proxyArgHash; /// <summary> Return name of this Velocimacro. /// </summary> /// <summary> Velocimacros are always LINE /// type directives. /// </summary> /// <summary> sets the directive name of this VM /// </summary> /// <summary> sets the array of arguments specified in the macro definition /// </summary> /// <summary> returns the number of ars needed for this VM /// </summary> /// <summary> Sets the orignal macro body. This is simply the cat of the macroArray, but the /// Macro object creates this once during parsing, and everyone shares it. /// Note : it must not be modified. /// </summary> /// <summary> Renders the macro using the context /// </summary> public override bool render(InternalContextAdapter context, TextWriter writer, INode node) { try { /* * it's possible the tree hasn't been parsed yet, so get * the VMManager to parse and init it */ if (nodeTree != null) { if (!init_Renamed_Field) { nodeTree.init(context, rsvc); init_Renamed_Field = true; } /* * wrap the current context and add the VMProxyArg objects */ VMContext vmc = new VMContext(context, rsvc); for (int i = 1; i < argArray.Length; i++) { /* * we can do this as VMProxyArgs don't change state. They change * the context. */ VMProxyArg arg = (VMProxyArg) proxyArgHash[argArray[i]]; vmc.AddVMProxyArg(arg); } /* * now render the VM */ nodeTree.render(vmc, writer); } else { rsvc.error("VM error : " + macroName + ". Null AST"); } } catch (Exception e) { /* * if it's a MIE, it came from the render.... throw it... */ if (e is MethodInvocationException) { throw (MethodInvocationException) e; } rsvc.error("VelocimacroProxy.render() : exception VM = #" + macroName + "() : " + StringUtils.stackTrace(e)); } return true; } /// <summary> The major meat of VelocimacroProxy, init() checks the # of arguments, patches the /// macro body, renders the macro into an AST, and then inits the AST, so it is ready /// for quick rendering. Note that this is only AST dependant stuff. Not context. /// </summary> public override void init(RuntimeServices rs, InternalContextAdapter context, INode node) { base.init(rs, context, node); /* * how many args did we get? */ int i = node.jjtGetNumChildren(); /* * right number of args? */ if (NumArgs != i) { rsvc.error("VM #" + macroName + ": error : too " + ((NumArgs > i) ? "few" : "many") + " arguments to macro. Wanted " + NumArgs + " got " + i); return; } /* * get the argument list to the instance use of the VM */ callingArgs = getArgArray(node); /* * now proxy each arg in the context */ setupMacro(callingArgs, callingArgTypes); return; } /// <summary> /// basic VM setup. Sets up the proxy args for this /// use, and parses the tree /// </summary> public virtual bool setupMacro(String[] callArgs, int[] callArgTypes) { setupProxyArgs(callArgs, callArgTypes); parseTree(callArgs); return true; } /// <summary> /// parses the macro. We need to do this here, at init time, or else /// the local-scope template feature is hard to get to work :) /// </summary> private void parseTree(String[] callArgs) { try { //UPGRADE_ISSUE: The equivalent of constructor 'java.io.BufferedReader.BufferedReader' is incompatible with the expected type in C#. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1109"' TextReader br = new StringReader(macroBody); /* * now parse the macro - and don't dump the namespace */ nodeTree = rsvc.parse(br, namespace_Renamed, false); /* * now, to make null references render as proper schmoo * we need to tweak the tree and change the literal of * the appropriate references * * we only do this at init time, so it's the overhead * is irrelevant */ Hashtable hm = new Hashtable(); for (int i = 1; i < argArray.Length; i++) { String arg = callArgs[i - 1]; /* * if the calling arg is indeed a reference * then we add to the map. We ignore other * stuff */ if (arg[0] == '$') { hm[argArray[i]] = arg; } } /* * now make one of our reference-munging visitor, and * let 'er rip */ VMReferenceMungeVisitor v = new VMReferenceMungeVisitor(hm); nodeTree.jjtAccept(v, null); } catch (Exception e) { rsvc.error("VelocimacroManager.parseTree() : exception " + macroName + " : " + StringUtils.stackTrace(e)); } } private void setupProxyArgs(String[] callArgs, int[] callArgTypes) { /* * for each of the args, make a ProxyArg */ for (int i = 1; i < argArray.Length; i++) { VMProxyArg arg = new VMProxyArg(rsvc, argArray[i], callArgs[i - 1], callArgTypes[i - 1]); proxyArgHash[argArray[i]] = arg; } } /// <summary> gets the args to the VM from the instance-use AST /// </summary> private String[] getArgArray(INode node) { int numArgs = node.jjtGetNumChildren(); String[] args = new String[numArgs]; callingArgTypes = new int[numArgs]; /* * eat the args */ int i = 0; Token t = null; Token tLast = null; while (i < numArgs) { args[i] = ""; /* * we want string literalss to lose the quotes. #foo( "blargh" ) should have 'blargh' patched * into macro body. So for each arg in the use-instance, treat the stringlierals specially... */ callingArgTypes[i] = node.jjtGetChild(i).Type; if (false && node.jjtGetChild(i).Type == ParserTreeConstants.JJTSTRINGLITERAL) { args[i] += node.jjtGetChild(i).FirstToken.image.Substring(1, (node.jjtGetChild(i).FirstToken.image.Length - 1) - (1)); } else { /* * just wander down the token list, concatenating everything together */ t = node.jjtGetChild(i).FirstToken; tLast = node.jjtGetChild(i).LastToken; while (t != tLast) { args[i] += t.image; t = t.next; } /* * don't forget the last one... :) */ args[i] += t.image; } i++; } return args; } } } --- NEW FILE: Literal.cs --- namespace NVelocity.Runtime.Directive { /* * The Apache Software License, Version 1.1 * * Copyright (c) 2000-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 System.IO; using NVelocity.Context; using NVelocity.Runtime.Parser.Node; /// <summary> A very simple directive that leverages the Node.literal() /// to grab the literal rendition of a node. We basically /// grab the literal value on init(), then repeatedly use /// that during render(). /// * /// </summary> /// <author> <a href="mailto:jv...@ap...">Jason van Zyl</a> /// </author> /// <version> $Id: Literal.cs,v 1.5 2005/11/16 07:01:50 intesar66 Exp $ /// /// </version> public class Literal : Directive { public override String Name { get { return "literal"; } set { throw new NotSupportedException(); } } public override int Type { get { return DirectiveConstants_Fields.BLOCK; } } internal String literalText; /// <summary> Return name of this directive. /// </summary> /// <summary> Return type of this directive. /// </summary> /// <summary> Store the literal rendition of a node using /// the Node.literal(). /// </summary> public override void init(RuntimeServices rs, InternalContextAdapter context, INode node) { base.init(rs, context, node); literalText = node.jjtGetChild(0).literal(); } /// <summary> Throw the literal rendition of the block between /// #literal()/#end into the writer. /// </summary> public override bool render(InternalContextAdapter context, TextWriter writer, INode node) { writer.Write(literalText); return true; } } } --- NEW FILE: Parse.cs --- namespace NVelocity.Runtime.Directive { /* * The Apache Software License, Version 1.1 * * Copyright (c) 2000-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 System.IO; using System.Text; using NVelocity.Context; using NVelocity.Exception; using NVelocity.Runtime.Parser.Node; using NVelocity.Runtime.Resource; using Node = Parser.Node.INode; /// <summary> Pluggable directive that handles the #parse() statement in VTL. /// * /// Notes: /// ----- /// 1) The parsed source material can only come from somewhere in /// the TemplateRoot tree for security reasons. There is no way /// around this. If you want to include content from elsewhere on /// your disk, use a link from somwhere under Template Root to that /// content. /// * /// 2) There is a limited parse depth. It is set as a property /// "parse_directive.maxdepth = 10" for example. There is a 20 iteration /// safety in the event that the parameter isn't set. /// * /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <author> <a href="mailto:jv...@ap...">Jason van Zyl</a> /// </author> /// <author> <a href="mailto:Chr...@dl...">Christoph Reck</a> /// </author> /// <version> $Id: Parse.cs,v 1.5 2005/11/16 07:01:50 intesar66 Exp $ /// /// </version> public class Parse : Directive { public override String Name { get { return "parse"; } set { throw new NotSupportedException(); } } public override int Type { get { return DirectiveConstants_Fields.LINE; } } private bool ready = false; /// <summary> Return name of this directive. /// </summary> /// <summary> Return type of this directive. /// </summary> /// <summary> iterates through the argument list and renders every /// argument that is appropriate. Any non appropriate /// arguments are logged, but render() continues. /// </summary> public override bool render(InternalContextAdapter context, TextWriter writer, Node node) { /* * did we get an argument? */ if (node.jjtGetChild(0) == null) { rsvc.error("#parse() error : null argument"); return false; } /* * does it have a value? If you have a null reference, then no. */ Object value_Renamed = node.jjtGetChild(0).value_Renamed(context); if (value_Renamed == null) { rsvc.error("#parse() error : null argument"); return false; } /* * get the path */ //UPGRADE_TODO: The equivalent in .NET for method 'java.Object.toString' may return a different value. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1043"' String arg = value_Renamed.ToString(); /* * see if we have exceeded the configured depth. * If it isn't configured, put a stop at 20 just in case. */ Object[] templateStack = context.TemplateNameStack; if (templateStack.Length >= rsvc.getInt(RuntimeConstants_Fields.PARSE_DIRECTIVE_MAXDEPTH, 20)) { StringBuilder path = new StringBuilder(); for (int i = 0; i < templateStack.Length; ++i) { path.Append(" > " + templateStack[i]); } rsvc.error("Max recursion depth reached (" + templateStack.Length + ")" + " File stack:" + path); return false; } Resource current = context.CurrentResource; /* * get the resource, and assume that we use the encoding of the current template * the 'current resource' can be null if we are processing a stream.... */ String encoding = null; if (current != null) { encoding = current.Encoding; } else { encoding = (String) rsvc.getProperty(RuntimeConstants_Fields.INPUT_ENCODING); } /* * now use the Runtime resource loader to get the template */ Template t = null; try { FileInfo f = new FileInfo(context.CurrentTemplateName); string directory = f.DirectoryName; if(arg.IndexOf("\\") < 0) arg = Path.Combine(directory, arg); t = rsvc.getTemplate(arg, encoding); } catch (ResourceNotFoundException rnfe) { /* * the arg wasn't found. Note it and throw */ rsvc.error("#parse(): cannot find template '" + arg + "', called from template " + context.CurrentTemplateName + " at (" + Line + ", " + Column + ")"); throw rnfe; } catch (ParseErrorException pee) { /* * the arg was found, but didn't parse - syntax error * note it and throw */ rsvc.error("#parse(): syntax error in #parse()-ed template '" + arg + "', called from template " + context.CurrentTemplateName + " at (" + Line + ", " + Column + ")"); throw pee; } catch (Exception e) { rsvc.error("#parse() : arg = " + arg + ". Exception : " + e); return false; } /* * and render it */ try { context.PushCurrentTemplateName(arg); ((SimpleNode) t.Data).render(context, writer); } catch (Exception e) { /* * if it's a MIE, it came from the render.... throw it... */ if (e is MethodInvocationException) { throw (MethodInvocationException) e; } rsvc.error("Exception rendering #parse( " + arg + " ) : " + e); return false; } finally { context.PopCurrentTemplateName(); } return true; } } } --- NEW FILE: Macro.cs --- using Node = NVelocity.Runtime.Parser.Node.INode; namespace NVelocity.Runtime.Directive { using System; using System.Collections; using System.IO; using System.Text; using NVelocity.Context; using NVelocity.Runtime.Parser; using NVelocity.Runtime.Parser.Node; /// <summary> /// Macro.java /// /// Macro implements the macro definition directive of VTL. /// /// example : /// /// #macro( isnull $i ) /// #if( $i ) /// $i /// #end /// #end /// /// This object is used at parse time to mainly process and register the /// macro. It is used inline in the parser when processing a directive. /// /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a></author> /// <version> $Id: Macro.cs,v 1.5 2005/11/16 07:01:50 intesar66 Exp $</version> public class Macro : Directive { public override String Name { get { return "macro"; } set { throw new NotSupportedException(); } } public override int Type { get { return DirectiveConstants_Fields.BLOCK; } } private static bool debugMode = false; /// <summary> Return name of this directive. /// </summary> /// <summary> Return type of this directive. /// </summary> /// <summary> render() doesn't do anything in the final output rendering. /// There is no output from a #macro() directive. /// </summary> public override bool render(InternalContextAdapter context, TextWriter writer, Node node) { /* * do nothing : We never render. The VelocimacroProxy object does that */ return true; } public override void init(RuntimeServices rs, InternalContextAdapter context, Node node) { base.init(rs, context, node); /* * again, don't do squat. We want the AST of the macro * block to hang off of this but we don't want to * init it... it's useless... */ return; } /// <summary> /// Used by Parser.java to process VMs withing the parsing process /// /// processAndRegister() doesn't actually render the macro to the output /// Processes the macro body into the internal representation used by the /// VelocimacroProxy objects, and if not currently used, adds it /// to the macro Factory /// </summary> public static void processAndRegister(RuntimeServices rs, Node node, String sourceTemplate) { /* * There must be at least one arg to #macro, * the name of the VM. Note that 0 following * args is ok for naming blocks of HTML */ int numArgs = node.jjtGetNumChildren(); /* * this number is the # of args + 1. The + 1 * is for the block tree */ if (numArgs < 2) { /* * error - they didn't name the macro or * define a block */ rs.error("#macro error : Velocimacro must have name as 1st " + "argument to #macro()"); return; } /* * get the arguments to the use of the VM */ String[] argArray = getArgArray(node); /* * now, try and eat the code block. Pass the root. */ IList macroArray = getASTAsStringArray(node.jjtGetChild(numArgs - 1)); /* * make a big string out of our macro */ StringBuilder temp = new StringBuilder(); for (int i = 0; i < macroArray.Count; i++) temp.Append(macroArray[i]); String macroBody = temp.ToString(); /* * now, try to add it. The Factory controls permissions, * so just give it a whack... */ bool bRet = rs.addVelocimacro(argArray[0], macroBody, argArray, sourceTemplate); return; } /// <summary> creates an array containing the literal /// strings in the macro arguement /// </summary> private static String[] getArgArray(Node node) { /* * remember : this includes the block tree */ int numArgs = node.jjtGetNumChildren(); numArgs--; // avoid the block tree... String[] argArray = new String[numArgs]; int i = 0; /* * eat the args */ while (i < numArgs) { argArray[i] = node.jjtGetChild(i).FirstToken.image; /* * trim off the leading $ for the args after the macro name. * saves everyone else from having to do it */ if (i > 0) { if (argArray[i].StartsWith("$")) argArray[i] = argArray[i].Substring(1, (argArray[i].Length) - (1)); } i++; } if (debugMode) { Console.Out.WriteLine("Macro.getArgArray() : #args = " + numArgs); Console.Out.Write(argArray[0] + "("); for (i = 1; i < numArgs; i++) Console.Out.Write(" " + argArray[i]); Console.Out.WriteLine(" )"); } return argArray; } /// <summary> Returns an array of the literal rep of the AST /// </summary> private static IList getASTAsStringArray(Node rootNode) { /* * this assumes that we are passed in the root * node of the code block */ Token t = rootNode.FirstToken; Token tLast = rootNode.LastToken; /* * now, run down the part of the tree bounded by * our first and last tokens */ ArrayList list = new ArrayList(); t = rootNode.FirstToken; while (t != tLast) { list.Add(NodeUtils.tokenLiteral(t)); t = t.next; } /* * make sure we get the last one... */ list.Add(NodeUtils.tokenLiteral(t)); return list; } } } --- NEW FILE: VMProxyArg.cs --- namespace NVelocity.Runtime.Directive { /* * The Apache Software License, Version 1.1 * * Copyright (c) 2000-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 System.IO; using NVelocity.Context; using NVelocity.Exception; using NVelocity.Runtime.Parser; using NVelocity.Runtime.Parser.Node; using NVelocity.Util; /// <summary> The function of this class is to proxy for the calling parameter to the VM. /// * /// This class is designed to be used in conjunction with the VMContext class /// which knows how to get and set values via it, rather than a simple get() /// or put() from a hashtable-like object. /// * /// There is probably a lot of undocumented subtlty here, so step lightly. /// * /// We rely on the observation that an instance of this object has a constant /// state throughout its lifetime as it's bound to the use-instance of a VM. /// In other words, it's created by the VelocimacroProxy class, to represent /// one of the arguments to a VM in a specific template. Since the template /// is fixed (it's a file...), we don't have to worry that the args to the VM /// will change. Yes, the VM will be called in other templates, or in other /// places on the same template, bit those are different use-instances. /// * /// These arguments can be, in the lingo of /// the parser, one of : /// <ul> /// <li> Reference() : anything that starts with '$' /// <li> StringLiteral() : something like "$foo" or "hello geir" /// <li> NumberLiteral() : 1, 2 etc /// <li> IntegerRange() : [ 1..2] or [$foo .. $bar] /// <li> ObjectArray() : [ "a", "b", "c"] /// <li> True() : true /// <li> False() : false /// <li>Word() : not likely - this is simply allowed by the parser so we can have /// syntactical sugar like #foreach($a in $b) where 'in' is the Word /// </ul> /// Now, Reference(), StringLit, NumberLit, IntRange, ObjArr are all dynamic things, so /// their value is gotten with the use of a context. The others are constants. The trick /// we rely on is that the context rather than this class really represents the /// state of the argument. We are simply proxying for the thing, returning the proper value /// when asked, and storing the proper value in the appropriate context when asked. /// * /// So, the hope here, so an instance of this can be shared across threads, is to /// keep any dynamic stuff out of it, relying on trick of having the appropriate /// context handed to us, and when a constant argument, letting VMContext punch that /// into a local context. /// /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version> $Id: VMProxyArg.cs,v 1.5 2005/11/16 07:01:50 intesar66 Exp $ /// /// </version> public class VMProxyArg { public virtual String CallerReference { get { return callerReference; } } public virtual String ContextReference { get { return contextReference; } } public virtual SimpleNode NodeTree { get { return nodeTree; } } public virtual Object StaticObject { get { return staticObject; } } public virtual int Type { get { return type; } } /// <summary>type of arg I will have /// </summary> private int type = 0; /// <summary>the AST if the type is such that it's dynamic (ex. JJTREFERENCE ) /// </summary> private SimpleNode nodeTree = null; /// <summary>reference for the object if we proxy for a static arg like an NumberLiteral /// </summary> private Object staticObject = null; /// <summary>not used in this impl : carries the appropriate user context /// </summary> private InternalContextAdapter usercontext = null; /// <summary>number of children in our tree if a reference /// </summary> private int numTreeChildren = 0; /// <summary>our identity in the current context /// </summary> private String contextReference = null; /// <summary>the reference we are proxying for /// </summary> private String callerReference = null; /// <summary>the 'de-dollared' reference if we are a ref but don't have a method attached /// </summary> private String singleLevelRef = null; /// <summary>by default, we are dynamic. safest /// </summary> private bool constant = false; /// <summary>in the event our type is switched - we don't care really what it is /// </summary> private const int GENERALSTATIC = - 1; private RuntimeServices rsvc = null; /// <summary> ctor for current impl /// * /// takes the reference literal we are proxying for, the literal /// the VM we are for is called with... /// * /// </summary> /// <param name="contextRef">reference arg in the definition of the VM, used in the VM /// </param> /// <param name="callerRef"> reference used by the caller as an arg to the VM /// </param> /// <param name="t"> type of arg : JJTREFERENCE, JJTTRUE, etc /// /// </param> public VMProxyArg(RuntimeServices rs, String contextRef, String callerRef, int t) { rsvc = rs; contextReference = contextRef; callerReference = callerRef; type = t; /* * make our AST if necessary */ setup(); /* * if we are multi-node tree, then save the size to * avoid fn call overhead */ if (nodeTree != null) numTreeChildren = nodeTree.jjtGetNumChildren(); /* * if we are a reference, and 'scalar' (i.e. $foo ) * then get the de-dollared ref so we can * hit our context directly, avoiding the AST */ if (type == ParserTreeConstants.JJTREFERENCE) { if (numTreeChildren == 0) { /* * do this properly and use the Reference node */ singleLevelRef = ((ASTReference) nodeTree).RootString; } } } /// <summary> tells if arg we are poxying for is /// dynamic or constant. /// * /// </summary> /// <returns>true of constant, false otherwise /// /// </returns> public virtual bool isConstant() { return constant; } /// <summary> Invoked by VMContext when Context.put() is called for a proxied reference. /// * /// </summary> /// <param name="context">context to modify via direct placement, or AST.setValue() /// </param> /// <param name="o"> new value of reference /// </param> /// <returns>Object currently null /// /// </returns> public virtual Object setObject(InternalContextAdapter context, Object o) { /* * if we are a reference, we could be updating a property */ if (type == ParserTreeConstants.JJTREFERENCE) { if (numTreeChildren > 0) { /* * we are a property, and being updated such as * #foo( $bar.BangStart) */ try { ((ASTReference) nodeTree).setValue(context, o); } catch (MethodInvocationException mie) { rsvc.error("VMProxyArg.getObject() : method invocation error setting value : " + mie); } } else { /* * we are a 'single level' reference like $foo, so we can set * out context directly */ context.Put(singleLevelRef, o); // alternate impl : usercontext.put( singleLevelRef, o); } } else { /* * if we aren't a reference, then we simply switch type, * get a new value, and it doesn't go into the context * * in current impl, this shouldn't happen. */ type = GENERALSTATIC; staticObject = o; rsvc.error("VMProxyArg.setObject() : Programmer error : I am a constant! No setting! : " + contextReference + " / " + callerReference); } return null; } /// <summary> returns the value of the reference. Generally, this is only /// called for dynamic proxies, as the static ones should have /// been stored in the VMContext's localcontext store /// * /// </summary> /// <param name="context">Context to use for getting current value /// </param> /// <returns>Object value /// * /// /// </returns> public virtual Object getObject(InternalContextAdapter context) { try { /* * we need to output based on our type */ Object retObject = null; if (type == ParserTreeConstants.JJTREFERENCE) { /* * two cases : scalar reference ($foo) or multi-level ($foo.bar....) */ if (numTreeChildren == 0) { /* * if I am a single-level reference, can I not get get it out of my context? */ retObject = context.Get(singleLevelRef); } else { /* * I need to let the AST produce it for me. */ retObject = nodeTree.execute(null, context); } } else if (type == ParserTreeConstants.JJTOBJECTARRAY) { retObject = nodeTree.value_Renamed(context); } else if (type == ParserTreeConstants.JJTINTEGERRANGE) { retObject = nodeTree.value_Renamed(context); } else if (type == ParserTreeConstants.JJTTRUE) { retObject = staticObject; } else if (type == ParserTreeConstants.JJTFALSE) { retObject = staticObject; } else if (type == ParserTreeConstants.JJTSTRINGLITERAL) { retObject = nodeTree.value_Renamed(context); } else if (type == ParserTreeConstants.JJTNUMBERLITERAL) { retObject = staticObject; } else if (type == ParserTreeConstants.JJTTEXT) { /* * this really shouldn't happen. text is just a thowaway arg for #foreach() */ try { StringWriter writer = new StringWriter(); nodeTree.render(context, writer); retObject = writer; } catch (Exception e) { rsvc.error("VMProxyArg.getObject() : error rendering reference : " + e); } } else if (type == GENERALSTATIC) { retObject = staticObject; } else { rsvc.error("Unsupported VM arg type : VM arg = " + callerReference + " type = " + type + "( VMProxyArg.getObject() )"); } return retObject; } catch (MethodInvocationException mie) { /* * not ideal, but otherwise we propogate out to the * VMContext, and the Context interface's put/get * don't throw. So this is a the best compromise * I can think of */ rsvc.error("VMProxyArg.getObject() : method invocation error getting value : " + mie); return null; } } /// <summary> does the housekeeping upon creationg. If a dynamic type /// it needs to make an AST for further get()/set() operations /// Anything else is constant. /// </summary> private void setup() { switch (type) { case ParserTreeConstants.JJTINTEGERRANGE: case ParserTreeConstants.JJTREFERENCE: case ParserTreeConstants.JJTOBJECTARRAY: case ParserTreeConstants.JJTSTRINGLITERAL: case ParserTreeConstants.JJTTEXT: { /* * dynamic types, just render */ constant = false; try { /* * fakie : wrap in directive to get the parser to treat our args as args * it doesn't matter that #include() can't take all these types, because we * just want the parser to consider our arg as a Directive/VM arg rather than * as if inline in schmoo */ String buff = "#include(" + callerReference + " ) "; //ByteArrayInputStream inStream = new ByteArrayInputStream( buff.getBytes() ); //UPGRADE_ISSUE: The equivalent of constructor 'java.io.BufferedReader.BufferedReader' is incompatible with the expected type in C#. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1109"' TextReader br = new StringReader(buff); nodeTree = rsvc.parse(br, "VMProxyArg:" + callerReference, true); /* * now, our tree really is the first DirectiveArg(), and only one */ nodeTree = (SimpleNode) nodeTree.jjtGetChild(0).jjtGetChild(0); /* * sanity check */ if (nodeTree != null && nodeTree.Type != type) { rsvc.error("VMProxyArg.setup() : programmer error : type doesn't match node type."); } /* * init. We can do this as they are only references */ nodeTree.init(null, rsvc); } catch (Exception e) { rsvc.error("VMProxyArg.setup() : exception " + callerReference + " : " + StringUtils.stackTrace(e)); } break; } case ParserTreeConstants.JJTTRUE: { constant = true; staticObject = true; break; } case ParserTreeConstants.JJTFALSE: { constant = true; staticObject = false; break; } case ParserTreeConstants.JJTNUMBERLITERAL: { constant = true; staticObject = Int32.Parse(callerReference); break; } case ParserTreeConstants.JJTWORD: { /* * this is technically an error... */ rsvc.error("Unsupported arg type : " + callerReference + " You most likely intended to call a VM with a string literal, so enclose with ' or \" characters. (VMProxyArg.setup())"); constant = true; staticObject = new String(callerReference.ToCharArray()); break; } default: { rsvc.error(" VMProxyArg.setup() : unsupported type : " + callerReference); } break; } } /* * CODE FOR ALTERNATE IMPL : please ignore. I will remove when confortable with current. */ /// <summary> not used in current impl /// * /// Constructor for alternate impl where VelProxy class would make new /// VMProxyArg objects, and use this contructor to avoid reparsing the /// reference args /// * /// that impl also had the VMProxyArg carry it's context /// </summary> public VMProxyArg(VMProxyArg model, InternalContextAdapter c) { usercontext = c; contextReference = model.ContextReference; callerReference = model.CallerReference; nodeTree = model.NodeTree; staticObject = model.StaticObject; type = model.Type; if (nodeTree != null) numTreeChildren = nodeTree.jjtGetNumChildren(); if (type == ParserTreeConstants.JJTREFERENCE) { if (numTreeChildren == 0) { /* * use the reference node to do this... */ singleLevelRef = ((ASTReference) nodeTree).RootString; } } } } } --- NEW FILE: ParseDirectiveException.cs --- namespace NVelocity.Runtime.Directive { /* * The Apache Software License, Version 1.1 * * Copyright (c) 2000-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 System.Collections; /// <summary> Exception for #parse() problems /// * /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version> $Id: ParseDirectiveException.cs,v 1.5 2005/11/16 07:01:50 intesar66 Exp $ /// /// </version> public class ParseDirectiveException : Exception { private void InitBlock() { filenameStack = new Stack(); } public override String Message { get { String returnStr = "#parse() exception : depth = " + depthCount + " -> " + msg; returnStr += " File stack : "; try { while (!(filenameStack.Count == 0)) { returnStr += (String) filenameStack.Pop(); returnStr += " -> "; } } catch (Exception e) { } return returnStr; } } //UPGRADE_NOTE: The initialization of 'filenameStack' was moved to method 'InitBlock'. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1005"' private Stack filenameStack; private String msg = ""; private int depthCount = 0; /// <summary> Constructor /// </summary> internal ParseDirectiveException(String m, int i) { InitBlock(); msg = m; depthCount = i; } /// <summary> Get a message. /// </summary> /// <summary> Add a file to the filename stack /// </summary> public virtual void addFile(String s) { Object temp_object; temp_object = s; Object generatedAux = temp_object; filenameStack.Push(temp_object); } } } --- NEW FILE: Foreach.cs --- //using ArrayIterator = NVelocity.Util.ArrayIterator; //using EnumerationIterator = NVelocity.Util.EnumerationIterator; namespace NVelocity.Runtime.Directive { using System; using System.Collections; using System.IO; using NVelocity.Context; using NVelocity.Runtime.Parser.Node; using NVelocity.Util.Introspection; /// <summary> /// Foreach directive used for moving through arrays, /// or objects that provide an Iterator. /// </summary> /// <author> <a href="mailto:jv...@ap...">Jason van Zyl</a></author> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a></author> /// <version> $Id: Foreach.cs,v 1.5 2005/11/16 07:01:50 intesar66 Exp $</version> public class Foreach : Directive { public override String Name { get { return "foreach"; } set { throw new NotSupportedException(); } } public override int Type { get { return DirectiveConstants_Fields.BLOCK; } } /// <summary> Return name of this directive. /// </summary> /// <summary> Return type of this directive. /// </summary> private static int UNKNOWN = - 1; /// <summary> Flag to indicate that the list object being used /// in an array. /// </summary> private const int INFO_ARRAY = 1; /// <summary> Flag to indicate that the list object being used /// provides an Iterator. /// </summary> private const int INFO_ITERATOR = 2; /// <summary> Flag to indicate that the list object being used /// is a Map. /// </summary> private const int INFO_MAP = 3; /// <summary> Flag to indicate that the list object being used /// is a Collection. /// </summary> private const int INFO_COLLECTION = 4; /// <summary> Flag to indicate that the list object being used /// is an Enumeration /// </summary> private const int INFO_ENUMERATION = 5; /// <summary> Flag to indicate that the list object being used /// is an IEnumerable /// </summary> private const int INFO_ENUMERABLE = 6; /// <summary> The name of the variable to use when placing /// the counter value into the context. Right /// now the default is $velocityCount. /// </summary> private String counterName; /// <summary> What value to start the loop counter at. /// </summary> private int counterInitialValue; /// <summary> The reference name used to access each /// of the elements in the list object. It /// is the $item in the following: /// /// #foreach ($item in $list) /// /// This can be used class wide because /// it is immutable. /// </summary> private String elementKey; /// <summary> simple init - init the tree and get the elementKey from /// the AST /// </summary> public override void init(RuntimeServices rs, InternalContextAdapter context, INode node) { base.init(rs, context, node); counterName = rsvc.getString(RuntimeConstants_Fields.COUNTER_NAME); counterInitialValue = rsvc.getInt(RuntimeConstants_Fields.COUNTER_INITIAL_VALUE); /* * this is really the only thing we can do here as everything * else is context sensitive */ elementKey = node.jjtGetChild(0).FirstToken.image.Substring(1); } /// <summary> returns an Iterator to the collection in the #foreach() /// /// </summary> /// <param name="context"> current context /// </param> /// <param name="node"> AST node /// </param> /// <returns>Iterator to do the dataset /// /// </returns> private IEnumerator getIterator(InternalContextAdapter context, INode node) { /* * get our list object, and punt if it's null. */ Object listObject = node.jjtGetChild(2).value_Renamed(context); if (listObject == null) return null; /* * See if we already know what type this is. * Use the introspection cache */ int type = UNKNOWN; IntrospectionCacheData icd = context.ICacheGet(this); Type c = listObject.GetType(); /* * if we have an entry in the cache, and the Class we have * cached is the same as the Class of the data object * then we are ok */ if (icd != null && icd.contextData == c) { /* dig the type out of the cata object */ type = ((Int32) icd.thingy); } /* * If we still don't know what this is, * figure out what type of object the list * element is, and get the iterator for it */ if (type == UNKNOWN) { if (listObject.GetType().IsArray) type = INFO_ARRAY; // NOTE: IDictionary needs to come before ICollection as it support ICollection else if (listObject is IDictionary) type = INFO_MAP; else if (listObject is ICollection) type = INFO_COLLECTION; else if (listObject is IEnumerable) type = INFO_ENUMERABLE; else if (listObject is IEnumerator) type = INFO_ENUMERATION; /* * if we did figure it out, cache it */ if (type != UNKNOWN) { icd = new IntrospectionCacheData(); icd.thingy = type; icd.contextData = c; context.ICachePut(this, icd); } } /* * now based on the type from either cache or examination... */ switch (type) { case INFO_COLLECTION: return ((ICollection) listObject).GetEnumerator(); case INFO_ENUMERABLE: return ((IEnumerable) listObject).GetEnumerator(); case INFO_ENUMERATION: rsvc.warn("Warning! The reference " + node.jjtGetChild(2).FirstToken.image + " is an Enumeration in the #foreach() loop at [" + Line + "," + Column + "]" + " in template " + context.CurrentTemplateName + ". Because it's not resetable," + " if used in more than once, this may lead to" + " unexpected results."); return (IEnumerator) listObject; case INFO_ARRAY: return ((Array) listObject).GetEnumerator(); case INFO_MAP: return ((IDictionary) listObject).GetEnumerator(); default: /* we have no clue what this is */ rsvc.warn("Could not determine type of enumerator (" + listObject.GetType().Name + ") in " + "#foreach loop for " + node.jjtGetChild(2).FirstToken.image + " at [" + Line + "," + Column + "]" + " in template " + context.CurrentTemplateName); return null; } } /// <summary> renders the #foreach() block /// </summary> public override bool render(InternalContextAdapter context, TextWriter writer, INode node) { /* * do our introspection to see what our collection is */ IEnumerator i = getIterator(context, node); if (i == null) return false; int counter = counterInitialValue; /* * save the element key if there is one, * and the loop counter */ Object o = context.Get(elementKey); Object ctr = context.Get(counterName); while (i.MoveNext()) { context.Put(counterName, counter); context.Put(elementKey, i.Current); node.jjtGetChild(3).render(context, writer); counter++; } /* * restores the loop counter (if we were nested) * if we have one, else just removes */ if (ctr != null) { context.Put(counterName, ctr); } else { context.Remove(counterName); } /* * restores element key if exists * otherwise just removes */ if (o != null) { context.Put(elementKey, o); } else { context.Remove(elementKey); } return true; } } } --- NEW FILE: DirectiveConstants.cs --- namespace NVelocity.Runtime.Directive { /* * The Apache Software License, Version 1.1 * * Copyright (c) 2000-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 ... [truncated message content] |
From: Sean M. <int...@us...> - 2005-11-16 07:02:00
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/Runtime/Parser In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.NVelocity/Runtime/Parser Added Files: CharStream.cs JJTParserState.cs ParseException.cs Parser.cs ParserConstants.cs ParserTokenManager.cs ParserTreeConstants.cs Token.cs TokenMgrError.cs VelocityCharStream.cs Log Message: --- NEW FILE: ParserConstants.cs --- namespace NVelocity.Runtime.Parser { using System; /* Generated By:JJTree&JavaCC: Do not edit this line. ParserConstants.java */ public class ParserConstants { public const int EOF = 0; public const int LBRACKET = 1; public const int RBRACKET = 2; public const int COMMA = 3; public const int DOUBLEDOT = 4; public const int LPAREN = 5; public const int RPAREN = 6; public const int REFMOD2_RPAREN = 7; public const int ESCAPE_DIRECTIVE = 8; public const int SET_DIRECTIVE = 9; public const int DOLLAR = 10; public const int DOLLARBANG = 11; public const int HASH = 15; public const int DOUBLE_ESCAPE = 16; public const int ESCAPE = 17; public const int TEXT = 18; public const int SINGLE_LINE_COMMENT = 19; public const int FORMAL_COMMENT = 20; public const int MULTI_LINE_COMMENT = 21; public const int WHITESPACE = 23; public const int STRING_LITERAL = 24; public const int TRUE = 25; public const int FALSE = 26; public const int NEWLINE = 27; public const int MINUS = 28; public const int PLUS = 29; public const int MULTIPLY = 30; public const int DIVIDE = 31; public const int MODULUS = 32; public const int LOGICAL_AND = 33; public const int LOGICAL_OR = 34; public const int LOGICAL_LT = 35; public const int LOGICAL_LE = 36; public const int LOGICAL_GT = 37; public const int LOGICAL_GE = 38; public const int LOGICAL_EQUALS = 39; public const int LOGICAL_NOT_EQUALS = 40; public const int LOGICAL_NOT = 41; public const int EQUALS = 42; public const int END = 43; public const int IF_DIRECTIVE = 44; public const int ELSEIF_DIRECTIVE = 45; public const int ELSE_DIRECTIVE = 46; public const int STOP_DIRECTIVE = 47; public const int DIGIT = 48; public const int NUMBER_LITERAL = 49; public const int LETTER = 50; public const int DIRECTIVE_CHAR = 51; public const int WORD = 52; public const int ALPHA_CHAR = 53; public const int ALPHANUM_CHAR = 54; public const int IDENTIFIER_CHAR = 55; public const int IDENTIFIER = 56; public const int DOT = 57; public const int LCURLY = 58; public const int RCURLY = 59; public const int REFERENCE_TERMINATOR = 60; public const int DIRECTIVE_TERMINATOR = 61; public const int DIRECTIVE = 0; public const int REFMOD2 = 1; public const int REFMODIFIER = 2; public const int DEFAULT = 3; public const int PRE_DIRECTIVE = 4; public const int REFERENCE = 5; public const int IN_MULTI_LINE_COMMENT = 6; public const int IN_FORMAL_COMMENT = 7; public const int IN_SINGLE_LINE_COMMENT = 8; public static readonly String[] tokenImage = new String[] {"<EOF>", "\"[\"", "\"]\"", "\",\"", "\"..\"", "\"(\"", "<RPAREN>", "\")\"", "<ESCAPE_DIRECTIVE>", "<SET_DIRECTIVE>", "<DOLLAR>", "<DOLLARBANG>", "\"##\"", "<token of kind 13>", "\"#*\"", "\"#\"", "\"\\\\\\\\\"", "\"\\\\\"", "<TEXT>", "<SINGLE_LINE_COMMENT>", "\"*#\"", "\"*#\"", "<token of kind 22>", "<WHITESPACE>", "<STRING_LITERAL>", "\"true\"", "\"false\"", "<NEWLINE>", "\"-\"", "\"+\"", "\"*\"", "\"/\"", "\"%\"", "\"&&\"", "\"||\"", "\"<\"", "\"<=\"", "\">\"", "\">=\"", "\"==\"", "\"!=\"", "\"!\"", "\"=\"", "<END>", "\"if\"", "\"elseif\"", "<ELSE_DIRECTIVE>", "\"stop\"", "<DIGIT>", "<NUMBER_LITERAL>", "<LETTER>", "<DIRECTIVE_CHAR>", "<WORD>", "<ALPHA_CHAR>", "<ALPHANUM_CHAR>", "<IDENTIFIER_CHAR>", "<IDENTIFIER>", "<DOT>", "\"{\"", "\"}\"", "<REFERENCE_TERMINATOR>", "<DIRECTIVE_TERMINATOR>"}; } } --- NEW FILE: ParseException.cs --- /* Generated By:JavaCC: Do not edit this line. ParseException.java Version 2.1 */ namespace NVelocity.Runtime.Parser { using System; using System.Text; /// <summary> This exception is thrown when parse errors are encountered. /// You can explicitly create objects of this exception type by /// calling the method generateParseException in the generated /// parser. /// * /// You can modify this class to customize your error reporting /// mechanisms so long as you retain the public fields. /// </summary> public class ParseException : Exception { /// <summary> The end of line string for this machine. /// </summary> protected internal String eol = Environment.NewLine; public override String Message { get { if (!specialConstructor) { return base.Message; } String expected = ""; int maxSize = 0; for (int i = 0; i < expectedTokenSequences.Length; i++) { if (maxSize < expectedTokenSequences[i].Length) { maxSize = expectedTokenSequences[i].Length; } for (int j = 0; j < expectedTokenSequences[i].Length; j++) { expected += tokenImage[expectedTokenSequences[i][j]] + " "; } if (expectedTokenSequences[i][expectedTokenSequences[i].Length - 1] != 0) { expected += "..."; } expected += eol + " "; } String retval = "Encountered \""; Token tok = currentToken.next; for (int i = 0; i < maxSize; i++) { if (i != 0) retval += " "; if (tok.kind == 0) { retval += tokenImage[0]; break; } retval += add_escapes(tok.image); tok = tok.next; } retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn; retval += "." + eol; if (expectedTokenSequences.Length == 1) { retval += "Was expecting:" + eol + " "; } else { retval += "Was expecting one of:" + eol + " "; } retval += expected; return retval; } } /// <summary> This constructor is used by the method "generateParseException" /// in the generated parser. Calling this constructor generates /// a new object of this type with the fields "currentToken", /// "expectedTokenSequences", and "tokenImage" set. The boolean /// flag "specialConstructor" is also set to true to indicate that /// this constructor was used to create this object. /// This constructor calls its super class with the empty string /// to force the "toString" method of parent class "Throwable" to /// print the error message in the form: /// ParseException: <result of getMessage> /// </summary> public ParseException(Token currentTokenVal, int[][] expectedTokenSequencesVal, String[] tokenImageVal) : base("") { specialConstructor = true; currentToken = currentTokenVal; expectedTokenSequences = expectedTokenSequencesVal; tokenImage = tokenImageVal; } /// <summary> The following constructors are for use by you for whatever /// purpose you can think of. Constructing the exception in this /// manner makes the exception behave in the normal way - i.e., as /// documented in the class "Throwable". The fields "errorToken", /// "expectedTokenSequences", and "tokenImage" do not contain /// relevant information. The JavaCC generated code does not use /// these constructors. /// </summary> public ParseException() : base() { specialConstructor = false; } public ParseException(String message) : base(message) { specialConstructor = false; } /// <summary> This variable determines which constructor was used to create /// this object and thereby affects the semantics of the /// "getMessage" method (see below). /// </summary> protected internal bool specialConstructor; /// <summary> This is the last token that has been consumed successfully. If /// this object has been created due to a parse error, the token /// followng this token will (therefore) be the first error token. /// </summary> public Token currentToken; /// <summary> Each entry in this array is an array of integers. Each array /// of integers represents a sequence of tokens (by their ordinal /// values) that is expected at this point of the parse. /// </summary> public int[][] expectedTokenSequences; /// <summary> This is a reference to the "tokenImage" array of the generated /// parser within which the parse error occurred. This array is /// defined in the generated ...Constants interface. /// </summary> public String[] tokenImage; /// <summary> This method has the standard behavior when this object has been /// created using the standard constructors. Otherwise, it uses /// "currentToken" and "expectedTokenSequences" to generate a parse /// error message and returns it. If this object has been created /// due to a parse error, and you do not catch it (it gets thrown /// from the parser), then this method is called during the printing /// of the final stack trace, and hence the correct error message /// gets displayed. /// </summary> /// <summary> Used to convert raw characters to their escaped version /// when these raw version cannot be used as part of an ASCII /// string literal. /// </summary> protected internal virtual String add_escapes(String str) { StringBuilder retval = new StringBuilder(); char ch; for (int i = 0; i < str.Length; i++) { switch (str[i]) { case (char) (0): continue; case '\b': retval.Append("\\b"); continue; case '\t': retval.Append("\\t"); continue; case '\n': retval.Append("\\n"); continue; case '\f': retval.Append("\\f"); continue; case '\r': retval.Append("\\r"); continue; case '\"': retval.Append("\\\""); continue; case '\'': retval.Append("\\\'"); continue; case '\\': retval.Append("\\\\"); continue; default: if ((ch = str[i]) < 0x20 || ch > 0x7e) { String s = "0000" + Convert.ToString(ch, 16); retval.Append("\\u" + s.Substring(s.Length - 4, (s.Length) - (s.Length - 4))); } else { retval.Append(ch); } continue; } } return retval.ToString(); } } } --- NEW FILE: JJTParserState.cs --- /* Generated By:JJTree: Do not edit this line. JJTParserState.java */ namespace NVelocity.Runtime.Parser { using System; using System.Collections; using NVelocity.Runtime.Parser.Node; internal class JJTParserState { private Stack nodes; private Stack marks; private int sp; // number of nodes on stack private int mk; // current mark private bool node_created; internal JJTParserState() { nodes = new Stack(); marks = new Stack(); sp = 0; mk = 0; } /* Determines whether the current node was actually closed and pushed. This should only be called in the final user action of a node scope. */ internal virtual bool nodeCreated() { return node_created; } /* Call this to reinitialize the node stack. It is called automatically by the parser's ReInit() method. */ internal virtual void reset() { nodes.Clear(); marks.Clear(); sp = 0; mk = 0; } /* Returns the root node of the AST. It only makes sense to call this after a successful parse. */ internal virtual INode rootNode() { return (INode) (nodes.ToArray())[nodes.Count - (0 + 1)]; } /* Pushes a node on to the stack. */ internal virtual void pushNode(INode n) { Object temp_object; temp_object = n; Object generatedAux = temp_object; nodes.Push(temp_object); ++sp; } /* Returns the node on the top of the stack, and remove it from the stack. */ internal virtual INode popNode() { if (--sp < mk) { mk = ((Int32) marks.Pop()); } return (INode) nodes.Pop(); } /* Returns the node currently on the top of the stack. */ internal virtual INode peekNode() { return (INode) nodes.Peek(); } /* Returns the number of children on the stack in the current node scope. */ internal virtual int nodeArity() { return sp - mk; } internal virtual void clearNodeScope(INode n) { while (sp > mk) { popNode(); } mk = ((Int32) marks.Pop()); } internal virtual void openNodeScope(INode n) { Object temp_object; temp_object = mk; Object generatedAux = temp_object; marks.Push(temp_object); mk = sp; n.jjtOpen(); } /* A definite node is constructed from a specified number of children. That number of nodes are popped from the stack and made the children of the definite node. Then the definite node is pushed on to the stack. */ internal virtual void closeNodeScope(INode n, int num) { mk = ((Int32) marks.Pop()); while (num-- > 0) { INode c = popNode(); c.jjtSetParent(n); n.jjtAddChild(c, num); } n.jjtClose(); pushNode(n); node_created = true; } /* A conditional node is constructed if its condition is true. All the nodes that have been pushed since the node was opened are made children of the the conditional node, which is then pushed on to the stack. If the condition is false the node is not constructed and they are left on the stack. */ internal virtual void closeNodeScope(INode n, bool condition) { if (condition) { int a = nodeArity(); mk = ((Int32) marks.Pop()); while (a-- > 0) { INode c = popNode(); c.jjtSetParent(n); n.jjtAddChild(c, a); } n.jjtClose(); pushNode(n); node_created = true; } else { mk = ((Int32) marks.Pop()); node_created = false; } } } } --- NEW FILE: ParserTokenManager.cs --- namespace NVelocity.Runtime.Parser { using System; using System.Collections; using System.IO; using System.Text; /* Generated By:JJTree&JavaCC: Do not edit this line. ParserTokenManager.java */ public class ParserTokenManager : ParserConstants { private int fileDepth = 0; private int lparen = 0; private int rparen = 0; private Stack stateStack = new Stack(); public bool debugPrint = false; [...4273 lines suppressed...] matchedToken.image = "."; if (debugPrint) Console.Out.Write("DOT : switching to " + REFMODIFIER); SwitchTo(ParserConstants.REFMODIFIER); break; case 59: if (image == null) image = new StringBuilder(new String(input_stream.GetSuffix(jjimageLen + (lengthOfMatch = jjmatchedPos + 1)))); else image.Append(input_stream.GetSuffix(jjimageLen + (lengthOfMatch = jjmatchedPos + 1))); stateStackPop(); break; default: break; } } } } --- NEW FILE: Parser.cs --- /* Generated By:JJTree&JavaCC: Do not edit this line. Parser.java */ namespace NVelocity.Runtime.Parser { using System; using System.Collections; using System.IO; using NVelocity.Runtime.Directive; using NVelocity.Runtime.Parser.Node; using NVelocity.Util; /// <summary> This class is responsible for parsing a Velocity /// template. This class was generated by JavaCC using /// the JJTree extension to produce an Abstract /// Syntax Tree (AST) of the template. /// /// Please look at the Parser.jjt file which is /// what controls the generation of this class. /// </summary> [...5189 lines suppressed...] { p = p.next = new JJCalls(); break; } p = p.next; } p.gen = jj_gen + xla - jj_la; p.first = token; p.arg = xla; } private sealed class JJCalls { internal int gen; internal Token first; internal int arg; internal JJCalls next; } } } --- NEW FILE: TokenMgrError.cs --- /* Generated By:JavaCC: Do not edit this line. TokenMgrError.java Version 2.1 */ namespace NVelocity.Runtime.Parser { using System; using System.Text; public class TokenMgrError : ApplicationException { public override String Message { get { return base.Message; } } /* * Ordinals for various reasons why an Error of this type can be thrown. */ /// <summary> Lexical error occured. /// </summary> internal const int LEXICAL_ERROR = 0; /// <summary> An attempt wass made to create a second instance of a static token manager. /// </summary> internal const int STATIC_LEXER_ERROR = 1; /// <summary> Tried to change to an invalid lexical state. /// </summary> internal const int INVALID_LEXICAL_STATE = 2; /// <summary> Detected (and bailed out of) an infinite loop in the token manager. /// </summary> internal const int LOOP_DETECTED = 3; /// <summary> Indicates the reason why the exception is thrown. It will have /// one of the above 4 values. /// </summary> internal int errorCode; /// <summary> Replaces unprintable characters by their espaced (or unicode escaped) /// equivalents in the given string /// </summary> protected internal static String addEscapes(String str) { StringBuilder retval = new StringBuilder(); char ch; for (int i = 0; i < str.Length; i++) { switch (str[i]) { case (char) (0): continue; case '\b': retval.Append("\\b"); continue; case '\t': retval.Append("\\t"); continue; case '\n': retval.Append("\\n"); continue; case '\f': retval.Append("\\f"); continue; case '\r': retval.Append("\\r"); continue; case '\"': retval.Append("\\\""); continue; case '\'': retval.Append("\\\'"); continue; case '\\': retval.Append("\\\\"); continue; default: if ((ch = str[i]) < 0x20 || ch > 0x7e) { String s = "0000" + Convert.ToString(ch, 16); retval.Append("\\u" + s.Substring(s.Length - 4, (s.Length) - (s.Length - 4))); } else { retval.Append(ch); } continue; } } return retval.ToString(); } /// <summary> Returns a detailed message for the Error when it is thrown by the /// token manager to indicate a lexical error. /// Parameters : /// EOFSeen : indicates if EOF caused the lexicl error /// curLexState : lexical state in which this error occured /// errorLine : line number when the error occured /// errorColumn : column number when the error occured /// errorAfter : prefix that was seen before this error occured /// curchar : the offending character /// Note: You can customize the lexical error message by modifying this method. /// </summary> private static String LexicalError(bool EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar) { return ("Lexical error at line " + errorLine + ", column " + errorColumn + ". Encountered: " + (EOFSeen ? "<EOF> " : ("\"" + addEscapes(curChar.ToString()) + "\"") + " (" + (int) curChar + "), ") + "after : \"" + addEscapes(errorAfter) + "\""); } /// <summary> You can also modify the body of this method to customize your error messages. /// For example, cases like LOOP_DETECTED and INVALID_LEXICAL_STATE are not /// of end-users concern, so you can return something like : /// * /// "Internal Error : Please file a bug report .... " /// * /// from this method for such cases in the release version of your parser. /// </summary> /* * Constructors of various flavors follow. */ public TokenMgrError() { } public TokenMgrError(String message, int reason) : base(message) { errorCode = reason; } public TokenMgrError(bool EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar, int reason) : this(LexicalError(EOFSeen, lexState, errorLine, errorColumn, errorAfter, curChar), reason) { } } } --- NEW FILE: ParserTreeConstants.cs --- namespace NVelocity.Runtime.Parser { using System; /* Generated By:JJTree: Do not edit this line. ParserTreeConstants.java */ public class ParserTreeConstants { /// <summary> /// private constructor as class is meant to hold constants only. /// Class was orginally an interface in Java, but as C# does not support Fields in an interface and /// the jjtNodeName field, I converted it to a class with no constructor. /// </summary> private ParserTreeConstants() { } public const int JJTPROCESS = 0; public const int JJTVOID = 1; public const int JJTESCAPEDDIRECTIVE = 2; public const int JJTESCAPE = 3; public const int JJTCOMMENT = 4; public const int JJTNUMBERLITERAL = 5; public const int JJTSTRINGLITERAL = 6; public const int JJTIDENTIFIER = 7; public const int JJTWORD = 8; public const int JJTDIRECTIVE = 9; public const int JJTBLOCK = 10; public const int JJTOBJECTARRAY = 11; public const int JJTINTEGERRANGE = 12; public const int JJTMETHOD = 13; public const int JJTREFERENCE = 14; public const int JJTTRUE = 15; public const int JJTFALSE = 16; public const int JJTTEXT = 17; public const int JJTIFSTATEMENT = 18; public const int JJTELSESTATEMENT = 19; public const int JJTELSEIFSTATEMENT = 20; public const int JJTSETDIRECTIVE = 21; public const int JJTEXPRESSION = 22; public const int JJTASSIGNMENT = 23; public const int JJTORNODE = 24; public const int JJTANDNODE = 25; public const int JJTEQNODE = 26; public const int JJTNENODE = 27; public const int JJTLTNODE = 28; public const int JJTGTNODE = 29; public const int JJTLENODE = 30; public const int JJTGENODE = 31; public const int JJTADDNODE = 32; public const int JJTSUBTRACTNODE = 33; public const int JJTMULNODE = 34; public const int JJTDIVNODE = 35; public const int JJTMODNODE = 36; public const int JJTNOTNODE = 37; public static readonly String[] jjtNodeName = new String[] {"process", "void", "EscapedDirective", "Escape", "Comment", "NumberLiteral", "StringLiteral", "Identifier", "Word", "Directive", "Block", "ObjectArray", "IntegerRange", "Method", "Reference", "True", "False", "Text", "IfStatement", "ElseStatement", "ElseIfStatement", "SetDirective", "Expression", "Assignment", "OrNode", "AndNode", "EQNode", "NENode", "LTNode", "GTNode", "LENode", "GENode", "AddNode", "SubtractNode", "MulNode", "DivNode", "ModNode", "NotNode"}; } } --- NEW FILE: CharStream.cs --- /* Generated By:JavaCC: Do not edit this line. CharStream.java Version 2.1 */ namespace NVelocity.Runtime.Parser { using System; /// <summary> This interface describes a character stream that maintains line and /// column number positions of the characters. It also has the capability /// to backup the stream to some extent. An implementation of this /// interface is used in the TokenManager implementation generated by /// JavaCCParser. /// /// All the methods except backup can be implemented in any fashion. backup /// needs to be implemented correctly for the correct operation of the lexer. /// Rest of the methods are all used to get information like line number, /// column number and the String that constitutes a token and are not used /// by the lexer. Hence their implementation won't affect the generated lexer's /// operation. /// </summary> public interface CharStream { int Column { get; } int Line { get; } int EndColumn { get; } int EndLine { get; } int BeginColumn { get; } int BeginLine { get; } /// <summary> Returns the next character from the selected input. The method /// of selecting the input is the responsibility of the class /// implementing this interface. Can throw any java.io.IOException. /// </summary> char readChar(); /// <summary> Returns the column position of the character last read. /// </summary> /// <deprecated> /// </deprecated> /// <seealso cref=" #getEndColumn /// /// "/> /// <summary> Returns the line number of the character last read. /// </summary> /// <deprecated> /// </deprecated> /// <seealso cref=" #getEndLine /// /// "/> /// <summary> Returns the column number of the last character for current token (being /// matched after the last call to BeginTOken). /// </summary> /// <summary> Returns the line number of the last character for current token (being /// matched after the last call to BeginTOken). /// </summary> /// <summary> Returns the column number of the first character for current token (being /// matched after the last call to BeginTOken). /// </summary> /// <summary> Returns the line number of the first character for current token (being /// matched after the last call to BeginTOken). /// </summary> /// <summary> Backs up the input stream by amount steps. Lexer calls this method if it /// had already read some characters, but could not use them to match a /// (longer) token. So, they will be used again as the prefix of the next /// token and it is the implemetation's responsibility to do this right. /// </summary> void backup(int amount); /// <summary> Returns the next character that marks the beginning of the next token. /// All characters must remain in the buffer between two successive calls /// to this method to implement backup correctly. /// </summary> char BeginToken(); /// <summary> Returns a string made up of characters from the marked token beginning /// to the current buffer position. Implementations have the choice of returning /// anything that they want to. For example, for efficiency, one might decide /// to just return null, which is a valid implementation. /// </summary> String GetImage(); /// <summary> Returns an array of characters that make up the suffix of length 'len' for /// the currently matched token. This is used to build up the matched string /// for use in actions in the case of MORE. A simple and inefficient /// implementation of this is as follows : /// /// { /// String t = GetImage(); /// return t.substring(t.length() - len, t.length()).toCharArray(); /// } /// </summary> char[] GetSuffix(int len); /// <summary> The lexer calls this function to indicate that it is done with the stream /// and hence implementations can free any resources held by this class. /// Again, the body of this function can be just empty and it will not /// affect the lexer's operation. /// </summary> void Done(); } } --- NEW FILE: VelocityCharStream.cs --- namespace NVelocity.Runtime.Parser { using System; using System.IO; /// <summary> NOTE : This class was originally an ASCII_CharStream autogenerated /// by Javacc. It was then modified via changing class name with appropriate /// fixes for CTORS, and mods to readChar(). /// /// This is safe because we *always* use Reader with this class, and never a /// InputStream. This guarantees that we have a correct stream of 16-bit /// chars - all encoding transformations have been done elsewhere, so we /// believe that there is no risk in doing this. Time will tell :) /// </summary> /// <summary> An implementation of interface CharStream, where the stream is assumed to /// contain only ASCII characters (without unicode processing). /// </summary> public sealed class VelocityCharStream : CharStream { public int Column { get { return bufcolumn[bufpos]; } } public int Line { get { return bufline[bufpos]; } } public int EndColumn { get { return bufcolumn[bufpos]; } } public int EndLine { get { return bufline[bufpos]; } } public int BeginColumn { get { return bufcolumn[tokenBegin]; } } public int BeginLine { get { return bufline[tokenBegin]; } } public const bool staticFlag = false; internal int bufsize; internal int available; internal int tokenBegin; public int bufpos = - 1; private int[] bufline; private int[] bufcolumn; private int column = 0; private int line = 1; private bool prevCharIsCR = false; private bool prevCharIsLF = false; private TextReader inputStream; private char[] buffer; private int maxNextCharInd = 0; private int inBuf = 0; private void ExpandBuff(bool wrapAround) { char[] newbuffer = new char[bufsize + 2048]; int[] newbufline = new int[bufsize + 2048]; int[] newbufcolumn = new int[bufsize + 2048]; //UPGRADE_NOTE: Exception 'java.lang.Throwable' was converted to ' ' which has different behavior. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1100"' try { if (wrapAround) { Array.Copy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); Array.Copy(buffer, 0, newbuffer, bufsize - tokenBegin, bufpos); buffer = newbuffer; Array.Copy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); Array.Copy(bufline, 0, newbufline, bufsize - tokenBegin, bufpos); bufline = newbufline; Array.Copy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); Array.Copy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos); bufcolumn = newbufcolumn; maxNextCharInd = (bufpos += (bufsize - tokenBegin)); } else { Array.Copy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); buffer = newbuffer; Array.Copy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); bufline = newbufline; Array.Copy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); bufcolumn = newbufcolumn; maxNextCharInd = (bufpos -= tokenBegin); } } catch (Exception t) { throw new ApplicationException(t.Message); } bufsize += 2048; available = bufsize; tokenBegin = 0; } private void FillBuff() { if (maxNextCharInd == available) { if (available == bufsize) { if (tokenBegin > 2048) { bufpos = maxNextCharInd = 0; available = tokenBegin; } else if (tokenBegin < 0) bufpos = maxNextCharInd = 0; else ExpandBuff(false); } else if (available > tokenBegin) available = bufsize; else if ((tokenBegin - available) < 2048) ExpandBuff(true); else available = tokenBegin; } int i; try { // NOTE: java streams return -1 when done // NOTE: java throws java.io.IOException when anything goes wrong - .Net will throw // a System.ObjectDisposedException when the reader is closed try { i = inputStream.Read(buffer, maxNextCharInd, available - maxNextCharInd); } catch (Exception ex) { throw new IOException("exception reading from inputStream", ex); } if (i <= 0) { inputStream.Close(); throw new IOException(); } else maxNextCharInd += i; return; } catch (IOException e) { --bufpos; backup(0); if (tokenBegin == - 1) tokenBegin = bufpos; throw e; } } public char BeginToken() { tokenBegin = - 1; char c = readChar(); tokenBegin = bufpos; return c; } private void UpdateLineColumn(char c) { column++; if (prevCharIsLF) { prevCharIsLF = false; line += (column = 1); } else if (prevCharIsCR) { prevCharIsCR = false; if (c == '\n') { prevCharIsLF = true; } else line += (column = 1); } switch (c) { case '\r': prevCharIsCR = true; break; case '\n': prevCharIsLF = true; break; case '\t': column--; column += (8 - (column & 7)); break; default: break; } bufline[bufpos] = line; bufcolumn[bufpos] = column; } public char readChar() { if (inBuf > 0) { --inBuf; /* * was : return (char)((char)0xff & buffer[(bufpos == bufsize - 1) ? (bufpos = 0) : ++bufpos]); */ return buffer[(bufpos == bufsize - 1) ? (bufpos = 0) : ++bufpos]; } if (++bufpos >= maxNextCharInd) FillBuff(); /* * was : char c = (char)((char)0xff & buffer[bufpos]); */ char c = buffer[bufpos]; UpdateLineColumn(c); return (c); } /// <deprecated> /// </deprecated> /// <seealso cref=" #getEndColumn /// /// "/> /// <deprecated> /// </deprecated> /// <seealso cref=" #getEndLine /// /// "/> public void backup(int amount) { inBuf += amount; if ((bufpos -= amount) < 0) bufpos += bufsize; } public VelocityCharStream(TextReader dstream, int startline, int startcolumn, int buffersize) { inputStream = dstream; line = startline; column = startcolumn - 1; available = bufsize = buffersize; buffer = new char[buffersize]; bufline = new int[buffersize]; bufcolumn = new int[buffersize]; } public VelocityCharStream(TextReader dstream, int startline, int startcolumn) : this(dstream, startline, startcolumn, 4096) { } public void ReInit(TextReader dstream, int startline, int startcolumn, int buffersize) { inputStream = dstream; line = startline; column = startcolumn - 1; if (buffer == null || buffersize != buffer.Length) { available = bufsize = buffersize; buffer = new char[buffersize]; bufline = new int[buffersize]; bufcolumn = new int[buffersize]; } prevCharIsLF = prevCharIsCR = false; tokenBegin = inBuf = maxNextCharInd = 0; bufpos = - 1; } public void ReInit(TextReader dstream, int startline, int startcolumn) { ReInit(dstream, startline, startcolumn, 4096); } // TODO - I am still not sure what place regular Streams will play - so I will just stick with Text* streams // public VelocityCharStream(System.IO.Stream dstream, int startline, int startcolumn, int buffersize):this(new System.IO.TextReader(dstream), startline, startcolumn, 4096) { // } // // public VelocityCharStream(System.IO.Stream dstream, int startline, int startcolumn):this(dstream, startline, startcolumn, 4096) { // } // // public void ReInit(System.IO.Stream dstream, int startline, int startcolumn, int buffersize) { // ReInit(new System.IO.TextReader(dstream), startline, startcolumn, 4096); // } // public void ReInit(System.IO.Stream dstream, int startline, int startcolumn) { // ReInit(dstream, startline, startcolumn, 4096); // } public String GetImage() { if (bufpos >= tokenBegin) { Int32 len = (bufpos - tokenBegin + 1) > buffer.Length ? buffer.Length : (bufpos - tokenBegin + 1); //return new String(buffer, tokenBegin, bufpos - tokenBegin + 1); return new String(buffer, tokenBegin, len); } else { return new String(buffer, tokenBegin, bufsize - tokenBegin) + new String(buffer, 0, bufpos + 1); } } public char[] GetSuffix(int len) { char[] ret = new char[len]; if ((bufpos + 1) >= len) Array.Copy(buffer, bufpos - len + 1, ret, 0, len); else { Array.Copy(buffer, bufsize - (len - bufpos - 1), ret, 0, len - bufpos - 1); Array.Copy(buffer, 0, ret, len - bufpos - 1, bufpos + 1); } return ret; } public void Done() { buffer = null; bufline = null; bufcolumn = null; } /// <summary> Method to adjust line and column numbers for the start of a token.<BR> /// </summary> public void adjustBeginLineColumn(int newLine, int newCol) { int start = tokenBegin; int len; if (bufpos >= tokenBegin) { len = bufpos - tokenBegin + inBuf + 1; } else { len = bufsize - tokenBegin + bufpos + 1 + inBuf; } int i = 0, j = 0, k = 0; int nextColDiff = 0, columnDiff = 0; while (i < len && bufline[j = start%bufsize] == bufline[k = ++start%bufsize]) { bufline[j] = newLine; nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j]; bufcolumn[j] = newCol + columnDiff; columnDiff = nextColDiff; i++; } if (i < len) { bufline[j] = newLine++; bufcolumn[j] = newCol + columnDiff; while (i++ < len) { if (bufline[j = start%bufsize] != bufline[++start%bufsize]) bufline[j] = newLine++; else bufline[j] = newLine; } } line = bufline[j]; column = bufcolumn[j]; } } } --- NEW FILE: Token.cs --- /* Generated By:JavaCC: Do not edit this line. Token.java Version 2.1 */ namespace NVelocity.Runtime.Parser { using System; /// <summary> Describes the input token stream. /// </summary> public class Token { /// <summary> An integer that describes the kind of this token. This numbering /// system is determined by JavaCCParser, and a table of these numbers is /// stored in the file ...Constants.java. /// </summary> public int kind; /// <summary> beginLine and beginColumn describe the position of the first character /// of this token; endLine and endColumn describe the position of the /// last character of this token. /// </summary> public int beginLine, beginColumn, endLine, endColumn; /// <summary> The string image of the token. /// </summary> public String image; /// <summary> A reference to the next regular (non-special) token from the input /// stream. If this is the last token from the input stream, or if the /// token manager has not read tokens beyond this one, this field is /// set to null. This is true only if this token is also a regular /// token. Otherwise, see below for a description of the contents of /// this field. /// </summary> public Token next; /// <summary> This field is used to access special tokens that occur prior to this /// token, but after the immediately preceding regular (non-special) token. /// If there are no such special tokens, this field is set to null. /// When there are more than one such special token, this field refers /// to the last of these special tokens, which in turn refers to the next /// previous special token through its specialToken field, and so on /// until the first special token (whose specialToken field is null). /// The next fields of special tokens refer to other special tokens that /// immediately follow it (without an intervening regular token). If there /// is no such token, this field is null. /// </summary> public Token specialToken; /// <summary> Returns the image. /// </summary> public override String ToString() { return image; } /// <summary> Returns a new Token object, by default. However, if you want, you /// can create and return subclass objects based on the value of ofKind. /// Simply add the cases to the switch for all those special cases. /// For example, if you have a subclass of Token called IDToken that /// you want to create if ofKind is ID, simlpy add something like : /// * /// case MyParserConstants.ID : return new IDToken(); /// * /// to the following switch statement. Then you can cast matchedToken /// variable to the appropriate type and use it in your lexical actions. /// </summary> public static Token newToken(int ofKind) { switch (ofKind) { default: return new Token(); } } } } |
From: Sean M. <int...@us...> - 2005-11-16 07:02:00
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/Tool In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.NVelocity/Tool Added Files: DataInfo.cs IToolInfo.cs ToolLoader.cs Log Message: --- NEW FILE: ToolLoader.cs --- namespace NVelocity.Tool { using System; /// <summary> /// <p>A view tool that allows template designers to load /// an arbitrary object into the context. Any object /// with a public constructor without parameters can be used /// as a view tool.</p> /// <p>THIS CLASS IS HERE AS A PROOF OF CONCEPT ONLY. IT IS NOT /// INTENDED FOR USE IN PRODUCTION ENVIRONMENTS. USE AT YOUR OWN RISK.</p> /// </summary> /// <author><a href="mailto:si...@te...">Gabe Sidler</a></author> /// <author><a href="mailto:ge...@ap...">Geir Magnusson Jr.</a></author> public class ToolLoader { public ToolLoader() { } /// <summary> /// Creates and returns an object of the specified classname. /// The object must have a valid default constructor. /// </summary> /// <param name="clazz">the fully qualified class name of the object</param> /// <returns>an instance of the specified class or null if the class /// could not be instantiated.</returns> public virtual Object Load(String clazz) { try { Type type = Type.GetType(clazz); Object o = Activator.CreateInstance(type); return o; } catch (Exception) { return null; } } } } --- NEW FILE: IToolInfo.cs --- namespace NVelocity.Tool { using System; /// <summary> Interface to simplify and abstract tool handling. /// * /// Implementations of this class should hold both the context /// key for the tool and sufficient information to return /// an instance of the tool. /// * /// </summary> /// <author> <a href="mailto:na...@es...">Nathan Bubna</a> /// * /// </author> /// <version> $Id: IToolInfo.cs,v 1.5 2005/11/16 07:01:51 intesar66 Exp $ /// /// </version> public interface IToolInfo { String Key { get; } String Classname { get; } /// <returns>the context key for the tool /// /// </returns> /// <returns>the fully qualified classname for the tool /// /// </returns> /// <summary> Returns an instance of the tool. /// * /// Instances returned may be new on each call, pooled, or /// the be same instance every time depending on the /// implementation. The object passed to this method may /// be used to initialize or create the tool that is returned, /// or it may be null if no such data is required. /// * /// </summary> /// <param name="initData">an object that may be used to initialize the instance /// </param> /// <returns>an instance of the tool /// /// </returns> Object getInstance(Object initData); } } --- NEW FILE: DataInfo.cs --- namespace NVelocity.Tool { using System; /// <summary> ToolInfo implementation to handle "primitive" data types. /// It currently supports String, Number, and Boolean data. /// * /// </summary> /// <author> <a href="mailto:na...@es...">Nathan Bubna</a> /// * /// </author> /// <version> $Id: DataInfo.cs,v 1.5 2005/11/16 07:01:51 intesar66 Exp $ /// /// </version> public class DataInfo : IToolInfo { public virtual String Key { get { return key; } } public virtual String Classname { get { return data.GetType().FullName; } } public static String TYPE_STRING = "string"; public static String TYPE_NUMBER = "number"; public static String TYPE_BOOLEAN = "boolean"; private String key; private Object data; /// <summary> Parses the value string into a recognized type. If /// the type specified is not supported, the data will /// be held and returned as a string. /// * /// </summary> /// <param name="key">the context key for the data /// </param> /// <param name="type">the data type /// </param> /// <param name="value">the data /// /// </param> public DataInfo(String key, String type, String value_Renamed) { this.key = key; if (type.ToUpper().Equals(TYPE_BOOLEAN.ToUpper())) { this.data = Boolean.Parse(value_Renamed); } else if (type.ToUpper().Equals(TYPE_NUMBER.ToUpper())) { if (value_Renamed.IndexOf((Char) '.') >= 0) { //UPGRADE_TODO: Format of parameters of constructor 'java.lang.Double.Double' are different in the equivalent in .NET. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1092"' this.data = Double.Parse(value_Renamed); } else { this.data = Int32.Parse(value_Renamed); } } else { this.data = value_Renamed; } } /// <summary> Returns the data. Always returns the same /// object since the data is a constant. Initialization /// data is ignored. /// </summary> public virtual Object getInstance(Object initData) { return data; } } } |
From: Sean M. <int...@us...> - 2005-11-16 07:02:00
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/Runtime/Resource/Loader In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.NVelocity/Runtime/Resource/Loader Added Files: FileResourceLoader.cs ResourceLoader.cs ResourceLoaderFactory.cs ResourceLocator.cs Log Message: --- NEW FILE: ResourceLocator.cs --- namespace NVelocity.Runtime.Resource.Loader { using System; using System.Collections; using System.IO; using System.Reflection; /// <summary> /// Locates a resource (file) in the file system or as a resource in an assembly. /// </summary> public class ResourceLocator { private String filename = String.Empty; private FileInfo file = null; private Boolean isFile = false; private Boolean isResource = false; private IList assemblies = new ArrayList(); private Assembly assembly = null; public ResourceLocator(String filename) { this.filename = filename; file = new FileInfo(this.filename); if (file.Exists) { this.filename = file.FullName; isFile = true; } else { // the calling Executing and Entry assemblies may not have links to each other - // so attempt to get assemblies from all possible paths. GetReferencedAssemblies(Assembly.GetExecutingAssembly(), assemblies); if (Assembly.GetEntryAssembly() != null) { GetReferencedAssemblies(Assembly.GetEntryAssembly(), assemblies); } if (Assembly.GetCallingAssembly() != null) { GetReferencedAssemblies(Assembly.GetCallingAssembly(), assemblies); } String fn = filename.ToLower().Replace(".\\", ""); fn = fn.Replace("\\", "."); fn = fn.Replace("/", "."); foreach (Assembly a in assemblies) { String prefix = a.FullName.Substring(0, a.FullName.IndexOf(",")).ToLower(); String[] names = a.GetManifestResourceNames(); foreach (String s in names) { if (s.ToLower().Equals(fn) || s.ToLower().Equals(prefix + "." + fn)) { this.filename = s; assembly = a; isResource = true; } } } } } public static void GetReferencedAssemblies(Assembly a, IList list) { String s = a.GetName().FullName; foreach (AssemblyName an in a.GetReferencedAssemblies()) { Assembly c = Assembly.Load(an); if (!list.Contains(c)) { list.Add(c); GetReferencedAssemblies(c, list); } } if (!list.Contains(a)) { list.Add(a); } } public Stream OpenRead() { if (isFile) { return file.OpenRead(); } else if (isResource) { return assembly.GetManifestResourceStream(filename); } else { throw new FileNotFoundException("Resource could not be found", filename); } } public String FullName { get { return this.filename; } } public Boolean Exists { get { return (isFile || isResource); } } private Stream FindResource(String path, String template) { try { FileInfo file = new FileInfo(path + "\\" + template); if (file.Exists) { return new BufferedStream(new FileStream(file.FullName, FileMode.Open, FileAccess.Read)); } else { IList list = new ArrayList(); GetReferencedAssemblies(Assembly.GetEntryAssembly(), list); foreach (Assembly a in list) { Stream s = a.GetManifestResourceStream(template); if (s != null) { return s; } } return null; } } catch (FileNotFoundException fnfe) { /* * log and convert to a general Velocity ResourceNotFoundException */ return null; } } } } --- NEW FILE: ResourceLoader.cs --- namespace NVelocity.Runtime.Resource.Loader { using System; using System.IO; using Commons.Collections; /// <summary> /// This is abstract class the all text resource loaders should extend. /// </summary> /// <author> <a href="mailto:jv...@ap...">Jason van Zyl</a></author> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a></author> /// <version> $Id: ResourceLoader.cs,v 1.5 2005/11/16 07:01:51 intesar66 Exp $</version> public abstract class ResourceLoader { public virtual String ClassName { get { return className; } } public virtual bool CachingOn { set { isCachingOn_Renamed_Field = value; } } public virtual long ModificationCheckInterval { get { return modificationCheckInterval; } set { this.modificationCheckInterval = value; } } /// /// <summary> Does this loader want templates produced with it /// cached in the Runtime. /// </summary> protected internal bool isCachingOn_Renamed_Field = false; /// <summary> This property will be passed on to the templates /// that are created with this loader. /// </summary> protected internal long modificationCheckInterval = 2; /// <summary> Class name for this loader, for logging/debuggin /// purposes. /// </summary> protected internal String className = null; protected internal RuntimeServices rsvc = null; /// <summary> This initialization is used by all resource /// loaders and must be called to set up common /// properties shared by all resource loaders /// </summary> public virtual void commonInit(RuntimeServices rs, ExtendedProperties configuration) { this.rsvc = rs; /* * these two properties are not required for all loaders. * For example, for ClasspathLoader, what would cache mean? * so adding default values which I think are the safest * * don't cache, and modCheckInterval irrelevant... */ isCachingOn_Renamed_Field = configuration.GetBoolean("cache", false); modificationCheckInterval = configuration.GetLong("modificationCheckInterval", 0); /* * this is a must! */ className = configuration.GetString("class"); } /// /// <summary> Initialize the template loader with a /// a resources class. /// </summary> public abstract void init(ExtendedProperties configuration); /// /// <summary> Get the InputStream that the Runtime will parse /// to create a template. /// </summary> public abstract Stream getResourceStream(String source); /// <summary> Given a template, check to see if the source of InputStream /// has been modified. /// </summary> public abstract bool isSourceModified(Resource resource); /// <summary> Get the last modified time of the InputStream source /// that was used to create the template. We need the template /// here because we have to extract the name of the template /// in order to locate the InputStream source. /// </summary> public abstract long getLastModified(Resource resource); /// <summary> Return the class name of this resource Loader /// </summary> /// <summary> Set the caching state. If true, then this loader /// would like the Runtime to cache templates that /// have been created with InputStreams provided /// by this loader. /// </summary> /// <summary> The Runtime uses this to find out whether this /// template loader wants the Runtime to cache /// templates created with InputStreams provided /// by this loader. /// </summary> public virtual bool isCachingOn() { return isCachingOn_Renamed_Field; } /// <summary> Set the interval at which the InputStream source /// should be checked for modifications. /// </summary> /// <summary> Get the interval at which the InputStream source /// should be checked for modifications. /// </summary> } } --- NEW FILE: FileResourceLoader.cs --- /* 122704 SMM Removed code that calls StringUtils.normalizepath, since it caused the parse directive not to work correctly */ namespace NVelocity.Runtime.Resource.Loader { using System; using System.Collections; using System.IO; using Commons.Collections; using NVelocity.Exception; using NVelocity.Util; /// <summary> /// A loader for templates stored on the file system. /// </summary> /// <author> <a href="mailto:jv...@ap...">Jason van Zyl</a> </author> public class FileResourceLoader : ResourceLoader { /// <summary> /// The paths to search for templates. /// </summary> protected ArrayList paths = null; /// <summary> /// Used to map the path that a template was found on /// so that we can properly check the modification /// times of the files. /// </summary> protected Hashtable templatePaths = new Hashtable(); public FileResourceLoader() { } public override void init(ExtendedProperties configuration) { rsvc.info("FileResourceLoader : initialization starting."); paths = configuration.GetVector("path"); // lets tell people what paths we will be using foreach (String path in paths) { rsvc.info("FileResourceLoader : adding path '" + path + "'"); } rsvc.info("FileResourceLoader : initialization complete."); } /// <summary> /// Get an InputStream so that the Runtime can build a /// template with it. /// </summary> /// <param name="name">name of template to get</param> /// <returns>InputStream containing the template /// @throws ResourceNotFoundException if template not found /// in the file template path. /// </returns> public override Stream getResourceStream(String templateName) { lock (this) { String template = null; int size = paths.Count; for (int i = 0; i < size; i++) { String path = (String) paths[i]; // Make sure we have a valid templateName. if (templateName == null || templateName.Length == 0) { // If we don't get a properly formed templateName // then there's not much we can do. So // we'll forget about trying to search // any more paths for the template. throw new ResourceNotFoundException("Need to specify a file name or file path!"); } // template = StringUtils.normalizePath(templateName); // if (template == null || template.Length == 0) // { // String msg = "File resource error : argument " + template + " contains .. and may be trying to access " + "content outside of template root. Rejected."; // // rsvc.error("FileResourceLoader : " + msg); // // throw new ResourceNotFoundException(msg); // } // if a / leads off, then just nip that :) // if (template.StartsWith("/")) // { // template = template.Substring(1); // } Stream inputStream = findTemplate(templateName); if (inputStream != null) { // Store the path that this template came // from so that we can check its modification // time. SupportClass.PutElement(templatePaths, templateName, path); return inputStream; } } // We have now searched all the paths for // templates and we didn't find anything so // throw an exception. String msg2 = "FileResourceLoader Error: cannot find resource " + template; throw new ResourceNotFoundException(msg2); } } /// <summary> /// Try to find a template given a normalized path. /// </summary> /// <param name="String">a normalized path</param> /// <returns>InputStream input stream that will be parsed</returns> private Stream findTemplate(String template) { try { ResourceLocator rl = new ResourceLocator(template); if (rl.Exists) { return new BufferedStream(rl.OpenRead()); } else { return null; } } catch (FileNotFoundException fnfe) { // log and convert to a general Velocity ResourceNotFoundException return null; } } /// <summary> /// How to keep track of all the modified times /// across the paths. /// </summary> public override bool isSourceModified(Resource resource) { String path = (String) templatePaths[resource.Name]; FileInfo file = new FileInfo(path + "\\" + resource.Name); if (file.Exists) { if (file.LastWriteTime.Ticks != resource.LastModified) { return true; } else { return false; } } // If the file is now unreadable, or it has // just plain disappeared then we'll just say // that it's modified :-) When the loader attempts // to load the stream it will fail and the error // will be reported then. return true; } public override long getLastModified(Resource resource) { String path = (String) templatePaths[resource.Name]; FileInfo file = new FileInfo(resource.Name); if (file.Exists) { return file.LastWriteTime.Ticks; } else { return 0; } } } } --- NEW FILE: ResourceLoaderFactory.cs --- namespace NVelocity.Runtime.Resource.Loader { using System; using NVelocity.Util; /// <summary> /// Factory to grab a template loader. /// </summary> /// <author><a href="mailto:jv...@ap...">Jason van Zyl</a></author> public class ResourceLoaderFactory { /// <summary> /// Gets the loader specified in the configuration file. /// </summary> /// <returns>TemplateLoader</returns> public static ResourceLoader getLoader(RuntimeServices rs, String loaderClassName) { ResourceLoader loader = null; try { // since properties are parsed into arrays with commas, something else needed to be used loaderClassName = loaderClassName.Replace(';', ','); Type loaderType = Type.GetType(loaderClassName); Object o = Activator.CreateInstance(loaderType); loader = (ResourceLoader) o; rs.info("Resource Loader Instantiated: " + loader.GetType().FullName); return loader; } catch (Exception e) { rs.error("Problem instantiating the template loader.\n" + "Look at your properties file and make sure the\n" + "name of the template loader is correct. Here is the\n" + "error: " + StringUtils.stackTrace(e)); throw new Exception("Problem initializing template loader: " + loaderClassName + "\nError is: " + StringUtils.stackTrace(e)); } } } } |
From: Sean M. <int...@us...> - 2005-11-16 07:01:59
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/App In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.NVelocity/App Added Files: AppSupportClass.cs FieldMethodizer.cs Velocity.cs VelocityEngine.cs Log Message: --- NEW FILE: AppSupportClass.cs --- using System; public class AppSupportClass { public class TextNumberFormat { // Declaration of fields private System.Globalization.NumberFormatInfo numberFormat; private enum formatTypes { General, Number, Currency, Percent }; private int numberFormatType; private bool groupingActivated; private string separator; private int digits; // CONSTRUCTORS public TextNumberFormat() { this.numberFormat = new System.Globalization.NumberFormatInfo(); this.numberFormatType = (int)TextNumberFormat.formatTypes.General; this.groupingActivated = true; this.separator = this.GetSeparator( (int)TextNumberFormat.formatTypes.General ); this.digits = 3; } private TextNumberFormat(TextNumberFormat.formatTypes theType, int digits) { this.numberFormat = System.Globalization.NumberFormatInfo.CurrentInfo; this.numberFormatType = (int)theType; this.groupingActivated = true; this.separator = this.GetSeparator( (int)theType ); this.digits = digits; } private TextNumberFormat(TextNumberFormat.formatTypes theType, System.Globalization.CultureInfo cultureNumberFormat, int digits) { this.numberFormat = cultureNumberFormat.NumberFormat; this.numberFormatType = (int)theType; this.groupingActivated = true; this.separator = this.GetSeparator( (int)theType ); this.digits = digits; } public static TextNumberFormat getTextNumberInstance() { TextNumberFormat instance = new TextNumberFormat(TextNumberFormat.formatTypes.Number, 3); return instance; } public static TextNumberFormat getTextNumberCurrencyInstance() { TextNumberFormat instance = new TextNumberFormat(TextNumberFormat.formatTypes.Currency, 3); return instance; } public static TextNumberFormat getTextNumberPercentInstance() { TextNumberFormat instance = new TextNumberFormat(TextNumberFormat.formatTypes.Percent, 3); return instance; } public static TextNumberFormat getTextNumberInstance(System.Globalization.CultureInfo culture) { TextNumberFormat instance = new TextNumberFormat(TextNumberFormat.formatTypes.Number, culture, 3); return instance; } public static TextNumberFormat getTextNumberCurrencyInstance(System.Globalization.CultureInfo culture) { TextNumberFormat instance = new TextNumberFormat(TextNumberFormat.formatTypes.Currency, culture, 3); return instance; } public static TextNumberFormat getTextNumberPercentInstance(System.Globalization.CultureInfo culture) { TextNumberFormat instance = new TextNumberFormat(TextNumberFormat.formatTypes.Percent, culture, 3); return instance; } public System.Object Clone() { return (System.Object)this; } public override bool Equals(System.Object textNumberObject) { return System.Object.Equals((System.Object)this, textNumberObject); } public string FormatDouble(double number) { if (this.groupingActivated) { return number.ToString(this.GetCurrentFormatString() + this.digits , this.numberFormat); } else { return (number.ToString(this.GetCurrentFormatString() + this.digits , this.numberFormat)).Replace(this.separator,""); } } public string FormatLong(long number) { if (this.groupingActivated) { return number.ToString(this.GetCurrentFormatString() + this.digits , this.numberFormat); } else { return (number.ToString(this.GetCurrentFormatString() + this.digits , this.numberFormat)).Replace(this.separator,""); } } public static System.Globalization.CultureInfo[] GetAvailableCultures() { return System.Globalization.CultureInfo.GetCultures(System.Globalization.CultureTypes.AllCultures); } public override int GetHashCode() { return this.GetHashCode(); } private string GetCurrentFormatString() { string currentFormatString = "n"; //Default value switch (this.numberFormatType) { case (int)TextNumberFormat.formatTypes.Currency: currentFormatString = "c"; break; case (int)TextNumberFormat.formatTypes.General: currentFormatString = "n" + this.numberFormat.NumberDecimalDigits; break; case (int)TextNumberFormat.formatTypes.Number: currentFormatString = "n" + this.numberFormat.NumberDecimalDigits; break; case (int)TextNumberFormat.formatTypes.Percent: currentFormatString = "p"; break; } return currentFormatString; } private string GetSeparator(int numberFormatType) { string separatorItem = " "; //Default Separator switch (numberFormatType) { case (int)TextNumberFormat.formatTypes.Currency: separatorItem = this.numberFormat.CurrencyGroupSeparator; break; case (int)TextNumberFormat.formatTypes.General: separatorItem = this.numberFormat.NumberGroupSeparator; break; case (int)TextNumberFormat.formatTypes.Number: separatorItem = this.numberFormat.NumberGroupSeparator; break; case (int)TextNumberFormat.formatTypes.Percent: separatorItem = this.numberFormat.PercentGroupSeparator; break; } return separatorItem; } public bool GroupingUsed { get { return (this.groupingActivated); } set { this.groupingActivated = value; } } public int Digits { get { return this.digits; } set { this.digits = value; } } } /*******************************/ public class DateTimeFormatManager { static public DateTimeFormatHashTable manager = new DateTimeFormatHashTable(); public class DateTimeFormatHashTable :System.Collections.Hashtable { public void SetDateFormatPattern(System.Globalization.DateTimeFormatInfo format, System.String newPattern) { if (this[format] != null) ((DateTimeFormatProperties) this[format]).DateFormatPattern = newPattern; else { DateTimeFormatProperties tempProps = new DateTimeFormatProperties(); tempProps.DateFormatPattern = newPattern; Add(format, tempProps); } } public string GetDateFormatPattern(System.Globalization.DateTimeFormatInfo format) { if (this[format] == null) return "d-MMM-yy"; else return ((DateTimeFormatProperties) this[format]).DateFormatPattern; } public void SetTimeFormatPattern(System.Globalization.DateTimeFormatInfo format, System.String newPattern) { if (this[format] != null) ((DateTimeFormatProperties) this[format]).TimeFormatPattern = newPattern; else { DateTimeFormatProperties tempProps = new DateTimeFormatProperties(); tempProps.TimeFormatPattern = newPattern; Add(format, tempProps); } } public string GetTimeFormatPattern(System.Globalization.DateTimeFormatInfo format) { if (this[format] == null) return "h:mm:ss tt"; else return ((DateTimeFormatProperties) this[format]).TimeFormatPattern; } class DateTimeFormatProperties { public string DateFormatPattern = "d-MMM-yy"; public string TimeFormatPattern = "h:mm:ss tt"; } } } /*******************************/ public static string FormatDateTime(System.Globalization.DateTimeFormatInfo format, System.DateTime date) { string timePattern = DateTimeFormatManager.manager.GetTimeFormatPattern(format); string datePattern = DateTimeFormatManager.manager.GetDateFormatPattern(format); return date.ToString(datePattern + " " + timePattern, format); } /*******************************/ public static System.Globalization.DateTimeFormatInfo GetDateTimeFormatInstance(int dateStyle, int timeStyle, System.Globalization.CultureInfo culture) { System.Globalization.DateTimeFormatInfo format = culture.DateTimeFormat; switch (timeStyle) { case -1: DateTimeFormatManager.manager.SetTimeFormatPattern(format, ""); break; case 0: DateTimeFormatManager.manager.SetTimeFormatPattern(format, "h:mm:ss 'o clock' tt zzz"); break; case 1: DateTimeFormatManager.manager.SetTimeFormatPattern(format, "h:mm:ss tt zzz"); break; case 2: DateTimeFormatManager.manager.SetTimeFormatPattern(format, "h:mm:ss tt"); break; case 3: DateTimeFormatManager.manager.SetTimeFormatPattern(format, "h:mm tt"); break; } switch (dateStyle) { case -1: DateTimeFormatManager.manager.SetDateFormatPattern(format, ""); break; case 0: DateTimeFormatManager.manager.SetDateFormatPattern(format, "dddd, MMMM dd%, yyy"); break; case 1: DateTimeFormatManager.manager.SetDateFormatPattern(format, "MMMM dd%, yyy" ); break; case 2: DateTimeFormatManager.manager.SetDateFormatPattern(format, "d-MMM-yy" ); break; case 3: DateTimeFormatManager.manager.SetDateFormatPattern(format, "M/dd/yy"); break; } return format; } } --- NEW FILE: Velocity.cs --- namespace NVelocity.App { using System; using System.IO; using System.Text; using Commons.Collections; using NVelocity.Context; using NVelocity.Exception; using NVelocity.Runtime; using NVelocity.Runtime.Parser; using NVelocity.Runtime.Parser.Node; /// <summary> /// This class provides services to the application /// developer, such as : /// <ul> /// <li> Simple Velocity Runtime engine initialization methods. /// <li> Functions to apply the template engine to streams and strings /// to allow embedding and dynamic template generation. /// <li> Methods to access Velocimacros directly. /// </ul> /// <br><br> /// While the most common way to use NVelocity is via templates, as /// Velocity is a general-purpose template engine, there are other /// uses that NVelocity is well suited for, such as processing dynamically /// created templates, or processing content streams. /// <br><br> /// The methods herein were developed to allow easy access to the NVelocity /// facilities without direct spelunking of the internals. If there is /// something you feel is necessary to add here, please, send a patch. /// </summary> public class Velocity : RuntimeConstants { /// <summary> /// initialize the NVelocity runtime engine, using the default /// properties of the NVelocity distribution /// </summary> public static void Init() { RuntimeSingleton.init(); } /// <summary> /// initialize the Velocity runtime engine, using default properties /// plus the properties in the properties file passed in as the arg /// </summary> /// <param name="propsFilename"> /// file containing properties to use to initialize /// the Velocity runtime /// </param> public static void Init(String propsFilename) { RuntimeSingleton.init(propsFilename); } /// <summary> /// initialize the Velocity runtime engine, using default properties /// plus the properties in the passed in java.util.Properties object /// </summary> /// <param name="p"> /// Proprties object containing initialization properties /// </param> public static void Init(ExtendedProperties p) { RuntimeSingleton.init(p); } /// <summary> /// Set a Velocity Runtime property. /// </summary> /// <param name="String">key</param> /// <param name="Object">value</param> public static void SetProperty(String key, Object value_Renamed) { RuntimeSingleton.setProperty(key, value_Renamed); } /// <summary> /// Add a Velocity Runtime property. /// </summary> /// <param name="String">key</param> /// <param name="Object">value</param> public static void AddProperty(String key, Object value_Renamed) { RuntimeSingleton.addProperty(key, value_Renamed); } /// <summary> /// Clear a NVelocity Runtime property. /// </summary> /// <param name="key">of property to clear</param> public static void ClearProperty(String key) { RuntimeSingleton.clearProperty(key); } /// <summary> /// Set an entire configuration at once. This is /// useful in cases where the parent application uses /// the ExtendedProperties class and the velocity configuration /// is a subset of the parent application's configuration. /// </summary> /// <param name="ExtendedProperties">configuration</param> public static ExtendedProperties ExtendedProperties { set { RuntimeSingleton.Configuration = value; } } /// <summary> /// Get a Velocity Runtime property. /// </summary> /// <param name="key">property to retrieve</param> /// <returns>property value or null if the property not currently set</returns> public static Object GetProperty(String key) { return RuntimeSingleton.getProperty(key); } /// <summary> /// renders the input string using the context into the output writer. /// To be used when a template is dynamically constructed, or want to use /// Velocity as a token replacer. /// </summary> /// <param name="context">context to use in rendering input string /// </param> /// <param name="out"> Writer in which to render the output /// </param> /// <param name="logTag"> string to be used as the template name for log /// messages in case of error /// </param> /// <param name="instring">input string containing the VTL to be rendered /// </param> /// <returns>true if successful, false otherwise. If false, see /// Velocity runtime log /// </returns> public static bool Evaluate(IContext context, TextWriter out_Renamed, String logTag, String instring) { return Evaluate(context, out_Renamed, logTag, new StringReader(instring)); } /// <summary> /// Renders the input stream using the context into the output writer. /// To be used when a template is dynamically constructed, or want to /// use Velocity as a token replacer. /// </summary> /// <param name="context">context to use in rendering input string /// </param> /// <param name="out"> Writer in which to render the output /// </param> /// <param name="logTag"> string to be used as the template name for log messages /// in case of error /// </param> /// <param name="instream">input stream containing the VTL to be rendered /// </param> /// <returns>true if successful, false otherwise. If false, see /// Velocity runtime log /// </returns> /// <deprecated>Use /// {@link #evaluate( Context context, Writer writer, /// String logTag, Reader reader ) } /// </deprecated> public static bool Evaluate(IContext context, TextWriter writer, String logTag, Stream instream) { /* * first, parse - convert ParseException if thrown */ TextReader reader = null; String encoding = null; try { encoding = RuntimeSingleton.getString(RuntimeConstants_Fields.INPUT_ENCODING, RuntimeConstants_Fields.ENCODING_DEFAULT); reader = new StreamReader(new StreamReader(instream, Encoding.GetEncoding(encoding)).BaseStream); } catch (IOException uce) { String msg = "Unsupported input encoding : " + encoding + " for template " + logTag; throw new ParseErrorException(msg); } return Evaluate(context, writer, logTag, reader); } /// <summary> /// Renders the input reader using the context into the output writer. /// To be used when a template is dynamically constructed, or want to /// use Velocity as a token replacer. /// </summary> /// <param name="context">context to use in rendering input string</param> /// <param name="out"> Writer in which to render the output</param> /// <param name="logTag"> string to be used as the template name for log messages in case of error</param> /// <param name="reader">Reader containing the VTL to be rendered</param> /// <returns>true if successful, false otherwise. If false, see Velocity runtime log</returns> public static bool Evaluate(IContext context, TextWriter writer, String logTag, TextReader reader) { SimpleNode nodeTree = null; try { nodeTree = RuntimeSingleton.parse(reader, logTag); } catch (ParseException pex) { throw new ParseErrorException(pex.Message); } /* * now we want to init and render */ if (nodeTree != null) { InternalContextAdapterImpl ica = new InternalContextAdapterImpl(context); ica.PushCurrentTemplateName(logTag); try { try { nodeTree.init(ica, RuntimeSingleton.RuntimeServices); } catch (Exception e) { RuntimeSingleton.error("Velocity.evaluate() : init exception for tag = " + logTag + " : " + e); } /* * now render, and let any exceptions fly */ nodeTree.render(ica, writer); } finally { ica.PopCurrentTemplateName(); } return true; } return false; } /// <summary> /// Invokes a currently registered Velocimacro with the parms provided /// and places the rendered stream into the writer. /// <br> /// Note : currently only accepts args to the VM if they are in the context. /// </summary> /// <param name="vmName">name of Velocimacro to call /// </param> /// <param name="logTag">string to be used for template name in case of error /// </param> /// <param name="params[]">args used to invoke Velocimacro. In context key format : /// eg "foo","bar" (rather than "$foo","$bar") /// </param> /// <param name="context">Context object containing data/objects used for rendering. /// </param> /// <param name="writer"> Writer for output stream /// </param> /// <returns>true if Velocimacro exists and successfully invoked, false otherwise. /// </returns> public static bool InvokeVelocimacro(String vmName, String logTag, String[] params_Renamed, IContext context, TextWriter writer) { /* * check parms */ if (vmName == null || params_Renamed == null || context == null || writer == null || logTag == null) { RuntimeSingleton.error("Velocity.invokeVelocimacro() : invalid parameter"); return false; } /* * does the VM exist? */ if (!RuntimeSingleton.isVelocimacro(vmName, logTag)) { RuntimeSingleton.error("Velocity.invokeVelocimacro() : VM '" + vmName + "' not registered."); return false; } /* * now just create the VM call, and use evaluate */ StringBuilder construct = new StringBuilder("#"); construct.Append(vmName); construct.Append("("); for (int i = 0; i < params_Renamed.Length; i++) { construct.Append(" $"); construct.Append(params_Renamed[i]); } construct.Append(" )"); try { bool retval = Evaluate(context, writer, logTag, construct.ToString()); return retval; } catch (Exception e) { RuntimeSingleton.error("Velocity.invokeVelocimacro() : error " + e); } return false; } /// <summary> /// merges a template and puts the rendered stream into the writer /// </summary> /// <param name="templateName">name of template to be used in merge /// </param> /// <param name="context"> filled context to be used in merge /// </param> /// <param name="writer"> writer to write template into /// </param> /// <returns>true if successful, false otherwise. Errors /// logged to velocity log. /// </returns> /// <deprecated>Use /// {@link #mergeTemplate( String templateName, String encoding, /// Context context, Writer writer )} /// </deprecated> public static bool MergeTemplate(String templateName, IContext context, TextWriter writer) { return MergeTemplate(templateName, RuntimeSingleton.getString(RuntimeConstants_Fields.INPUT_ENCODING, RuntimeConstants_Fields.ENCODING_DEFAULT), context, writer); } /// <summary> /// merges a template and puts the rendered stream into the writer /// </summary> /// <param name="templateName">name of template to be used in merge /// </param> /// <param name="encoding">encoding used in template /// </param> /// <param name="context"> filled context to be used in merge /// </param> /// <param name="writer"> writer to write template into /// </param> /// <returns>true if successful, false otherwise. Errors /// logged to velocity log /// @since Velocity v1.1 /// </returns> public static bool MergeTemplate(String templateName, String encoding, IContext context, TextWriter writer) { Template template = RuntimeSingleton.getTemplate(templateName, encoding); if (template == null) { RuntimeSingleton.error("Velocity.parseTemplate() failed loading template '" + templateName + "'"); return false; } else { template.Merge(context, writer); return true; } } /// <summary> /// Returns a <code>Template</code> from the Velocity /// resource management system. /// </summary> /// <param name="name">The file name of the desired template. /// </param> /// <returns> The template. /// @throws ResourceNotFoundException if template not found /// from any available source. /// @throws ParseErrorException if template cannot be parsed due /// to syntax (or other) error. /// @throws Exception if an error occurs in template initialization /// </returns> public static Template GetTemplate(String name) { return RuntimeSingleton.getTemplate(name); } /// <summary> /// Returns a <code>Template</code> from the Velocity /// resource management system. /// </summary> /// <param name="name">The file name of the desired template. /// </param> /// <param name="encoding">The character encoding to use for the template. /// </param> /// <returns> The template. /// @throws ResourceNotFoundException if template not found /// from any available source. /// @throws ParseErrorException if template cannot be parsed due /// to syntax (or other) error. /// @throws Exception if an error occurs in template initialization /// @since Velocity v1.1 /// </returns> public static Template GetTemplate(String name, String encoding) { return RuntimeSingleton.getTemplate(name, encoding); } /// <summary> /// Determines if a template is accessable via the currently /// configured resource loaders. /// <br><br> /// Note that the current implementation will <b>not</b> /// change the state of the system in any real way - so this /// cannot be used to pre-load the resource cache, as the /// previous implementation did as a side-effect. /// <br><br> /// The previous implementation exhibited extreme lazyness and /// sloth, and the author has been flogged. /// </summary> /// <param name="templateName"> name of the temlpate to search for /// </param> /// <returns>true if found, false otherwise /// </returns> public static bool TemplateExists(String templateName) { return (RuntimeSingleton.getLoaderNameForResource(templateName) != null); } /// <summary> /// Log a warning message. /// </summary> /// <param name="Object">message to log /// </param> public static void Warn(Object message) { RuntimeSingleton.warn(message); } /// <summary> /// Log an info message. /// </summary> /// <param name="Object">message to log</param> public static void Info(Object message) { RuntimeSingleton.info(message); } /// <summary> /// Log an error message. /// </summary> /// <param name="Object">message to log</param> public static void Error(Object message) { RuntimeSingleton.error(message); } /// <summary> /// Log a debug message. /// </summary> /// <param name="Object">message to log</param> public static void Debug(Object message) { RuntimeSingleton.debug(message); } /// <summary> /// <p> /// Set the an ApplicationAttribue, which is an Object /// set by the application which is accessable from /// any component of the system that gets a RuntimeServices. /// This allows communication between the application /// environment and custom pluggable components of the /// Velocity engine, such as loaders and loggers. /// </p> /// <p> /// Note that there is no enfocement or rules for the key /// used - it is up to the application developer. However, to /// help make the intermixing of components possible, using /// the target Class name (e.g. com.foo.bar ) as the key /// might help avoid collision. /// </p> /// </summary> /// <param name="key">object 'name' under which the object is stored /// </param> /// <param name="value">object to store under this key /// </param> public static void SetApplicationAttribute(Object key, Object value_Renamed) { RuntimeSingleton.RuntimeInstance.setApplicationAttribute(key, value_Renamed); } } } --- NEW FILE: VelocityEngine.cs --- namespace NVelocity.App { using System; using System.IO; using System.Text; using Commons.Collections; using NVelocity.Context; using NVelocity.Exception; using NVelocity.Runtime; using NVelocity.Runtime.Parser; using NVelocity.Runtime.Parser.Node; /// <summary> /// <p> /// This class provides a separate new-able instance of the /// Velocity template engine. The alternative model for use /// is using the Velocity class which employs the singleton /// model. /// </p> /// <p> /// Please ensure that you call one of the init() variants. /// This is critical for proper behavior. /// </p> /// <p> Coming soon : Velocity will call /// the parameter-less init() at the first use of this class /// if the init() wasn't explicitly called. While this will /// ensure that Velocity functions, it almost certainly won't /// function in the way you intend, so please make sure to /// call init(). /// </p> /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a></author> public class VelocityEngine : RuntimeConstants { private RuntimeInstance ri = new RuntimeInstance(); public VelocityEngine() { } /// <summary> /// Set an entire configuration at once. This is /// useful in cases where the parent application uses /// the ExtendedProperties class and the velocity configuration /// is a subset of the parent application's configuration. /// </summary> /// <param name="ExtendedProperties">configuration /// </param> public virtual ExtendedProperties ExtendedProperties { set { ri.Configuration = value; } } /// <summary> /// initialize the Velocity runtime engine, using the default /// properties of the Velocity distribution /// </summary> public virtual void Init() { ri.init(); } /// <summary> /// initialize the Velocity runtime engine, using default properties /// plus the properties in the properties file passed in as the arg /// </summary> /// <param name="propsFilename">file containing properties to use to initialize /// the Velocity runtime</param> public virtual void Init(String propsFilename) { ri.init(propsFilename); } /// <summary> /// initialize the Velocity runtime engine, using default properties /// plus the properties in the passed in java.util.Properties object /// </summary> /// <param name="p"> Proprties object containing initialization properties</param> public virtual void Init(ExtendedProperties p) { ri.init(p); } /// <summary> /// Set a Velocity Runtime property. /// </summary> /// <param name="String">key</param> /// <param name="Object">value</param> public virtual void SetProperty(String key, Object value_Renamed) { ri.setProperty(key, value_Renamed); } /// <summary> /// Add a Velocity Runtime property. /// </summary> /// <param name="String">key /// </param> /// <param name="Object">value /// </param> public virtual void AddProperty(String key, Object value_Renamed) { ri.addProperty(key, value_Renamed); } /// <summary> /// Clear a Velocity Runtime property. /// </summary> /// <param name="key">of property to clear /// </param> public virtual void ClearProperty(String key) { ri.clearProperty(key); } /// <summary> /// Get a Velocity Runtime property. /// </summary> /// <param name="key">property to retrieve /// </param> /// <returns>property value or null if the property /// not currently set /// </returns> public virtual Object GetProperty(String key) { return ri.getProperty(key); } /// <summary> /// renders the input string using the context into the output writer. /// To be used when a template is dynamically constructed, or want to use /// Velocity as a token replacer. /// </summary> /// <param name="context">context to use in rendering input string /// </param> /// <param name="out"> Writer in which to render the output /// </param> /// <param name="logTag"> string to be used as the template name for log /// messages in case of error /// </param> /// <param name="instring">input string containing the VTL to be rendered /// </param> /// <returns>true if successful, false otherwise. If false, see /// Velocity runtime log /// </returns> public virtual bool Evaluate(IContext context, TextWriter out_Renamed, String logTag, String instring) { return Evaluate(context, out_Renamed, logTag, new StringReader(instring)); } /// <summary> /// Renders the input stream using the context into the output writer. /// To be used when a template is dynamically constructed, or want to /// use Velocity as a token replacer. /// </summary> /// <param name="context">context to use in rendering input string /// </param> /// <param name="out"> Writer in which to render the output /// </param> /// <param name="logTag"> string to be used as the template name for log messages /// in case of error /// </param> /// <param name="instream">input stream containing the VTL to be rendered /// </param> /// <returns>true if successful, false otherwise. If false, see /// Velocity runtime log /// </returns> /// <deprecated>Use /// {@link #evaluate( Context context, Writer writer, /// String logTag, Reader reader ) } /// </deprecated> public virtual bool Evaluate(IContext context, TextWriter writer, String logTag, Stream instream) { /* * first, parse - convert ParseException if thrown */ TextReader br = null; String encoding = null; try { encoding = ri.getString(RuntimeConstants_Fields.INPUT_ENCODING, RuntimeConstants_Fields.ENCODING_DEFAULT); br = new StreamReader(new StreamReader(instream, Encoding.GetEncoding(encoding)).BaseStream); } catch (IOException uce) { String msg = "Unsupported input encoding : " + encoding + " for template " + logTag; throw new ParseErrorException(msg); } return Evaluate(context, writer, logTag, br); } /// <summary> /// Renders the input reader using the context into the output writer. /// To be used when a template is dynamically constructed, or want to /// use Velocity as a token replacer. /// </summary> /// <param name="context">context to use in rendering input string /// </param> /// <param name="out"> Writer in which to render the output /// </param> /// <param name="logTag"> string to be used as the template name for log messages /// in case of error /// </param> /// <param name="reader">Reader containing the VTL to be rendered /// </param> /// <returns>true if successful, false otherwise. If false, see /// Velocity runtime log /// @since Velocity v1.1 /// </returns> public virtual bool Evaluate(IContext context, TextWriter writer, String logTag, TextReader reader) { SimpleNode nodeTree = null; try { nodeTree = ri.parse(reader, logTag); } catch (ParseException pex) { throw new ParseErrorException(pex.Message); } /* * now we want to init and render */ if (nodeTree != null) { InternalContextAdapterImpl ica = new InternalContextAdapterImpl(context); ica.PushCurrentTemplateName(logTag); try { try { nodeTree.init(ica, ri); } catch (Exception e) { ri.error("Velocity.evaluate() : init exception for tag = " + logTag + " : " + e); } /* * now render, and let any exceptions fly */ nodeTree.render(ica, writer); } finally { ica.PopCurrentTemplateName(); } return true; } return false; } /// <summary> /// Invokes a currently registered Velocimacro with the parms provided /// and places the rendered stream into the writer. /// Note : currently only accepts args to the VM if they are in the context. /// </summary> /// <param name="vmName">name of Velocimacro to call /// </param> /// <param name="logTag">string to be used for template name in case of error /// </param> /// <param name="params[]">args used to invoke Velocimacro. In context key format : /// eg "foo","bar" (rather than "$foo","$bar") /// </param> /// <param name="context">Context object containing data/objects used for rendering. /// </param> /// <param name="writer"> Writer for output stream /// </param> /// <returns>true if Velocimacro exists and successfully invoked, false otherwise. /// </returns> public virtual bool InvokeVelocimacro(String vmName, String logTag, String[] params_Renamed, IContext context, TextWriter writer) { /* * check parms */ if (vmName == null || params_Renamed == null || context == null || writer == null || logTag == null) { ri.error("VelocityEngine.invokeVelocimacro() : invalid parameter"); return false; } /* * does the VM exist? */ if (!ri.isVelocimacro(vmName, logTag)) { ri.error("VelocityEngine.invokeVelocimacro() : VM '" + vmName + "' not registered."); return false; } /* * now just create the VM call, and use evaluate */ StringBuilder construct = new StringBuilder("#"); construct.Append(vmName); construct.Append("("); for (int i = 0; i < params_Renamed.Length; i++) { construct.Append(" $"); construct.Append(params_Renamed[i]); } construct.Append(" )"); try { bool retval = Evaluate(context, writer, logTag, construct.ToString()); return retval; } catch (Exception e) { ri.error("VelocityEngine.invokeVelocimacro() : error " + e); throw e; } } /// <summary> /// merges a template and puts the rendered stream into the writer /// </summary> /// <param name="templateName">name of template to be used in merge /// </param> /// <param name="context"> filled context to be used in merge /// </param> /// <param name="writer"> writer to write template into /// </param> /// <returns>true if successful, false otherwise. Errors /// logged to velocity log. /// </returns> /// <deprecated>Use /// {@link #mergeTemplate( String templateName, String encoding, /// Context context, Writer writer )} /// </deprecated> public virtual bool MergeTemplate(String templateName, IContext context, TextWriter writer) { return MergeTemplate(templateName, ri.getString(RuntimeConstants_Fields.INPUT_ENCODING, RuntimeConstants_Fields.ENCODING_DEFAULT), context, writer); } /// <summary> /// merges a template and puts the rendered stream into the writer /// </summary> /// <param name="templateName">name of template to be used in merge /// </param> /// <param name="encoding">encoding used in template /// </param> /// <param name="context"> filled context to be used in merge /// </param> /// <param name="writer"> writer to write template into /// </param> /// <returns>true if successful, false otherwise. Errors /// logged to velocity log /// @since Velocity v1.1 /// </returns> public virtual bool MergeTemplate(String templateName, String encoding, IContext context, TextWriter writer) { Template template = ri.getTemplate(templateName, encoding); if (template == null) { ri.error("Velocity.parseTemplate() failed loading template '" + templateName + "'"); return false; } else { template.Merge(context, writer); return true; } } /// <summary> /// Returns a <code>Template</code> from the Velocity /// resource management system. /// </summary> /// <param name="name">The file name of the desired template. /// </param> /// <returns> The template. /// @throws ResourceNotFoundException if template not found /// from any available source. /// @throws ParseErrorException if template cannot be parsed due /// to syntax (or other) error. /// @throws Exception if an error occurs in template initialization /// </returns> public virtual Template GetTemplate(String name) { return ri.getTemplate(name); } /// <summary> /// Returns a <code>Template</code> from the Velocity /// resource management system. /// </summary> /// <param name="name">The file name of the desired template. /// </param> /// <param name="encoding">The character encoding to use for the template. /// </param> /// <returns> The template. /// @throws ResourceNotFoundException if template not found /// from any available source. /// @throws ParseErrorException if template cannot be parsed due /// to syntax (or other) error. /// @throws Exception if an error occurs in template initialization /// @since Velocity v1.1 /// </returns> public virtual Template GetTemplate(String name, String encoding) { return ri.getTemplate(name, encoding); } /// <summary> /// Determines if a template is accessable via the currently /// configured resource loaders. /// <br><br> /// Note that the current implementation will <b>not</b> /// change the state of the system in any real way - so this /// cannot be used to pre-load the resource cache, as the /// previous implementation did as a side-effect. /// <br><br> /// The previous implementation exhibited extreme lazyness and /// sloth, and the author has been flogged. /// </summary> /// <param name="templateName"> name of the temlpate to search for /// </param> /// <returns>true if found, false otherwise /// </returns> public virtual bool TemplateExists(String templateName) { return (ri.getLoaderNameForResource(templateName) != null); } /// <summary> /// Log a warning message. /// </summary> /// <param name="Object">message to log</param> public virtual void Warn(Object message) { ri.warn(message); } /// /// <summary> /// Log an info message. /// </summary> /// <param name="Object">message to log</param> public virtual void Info(Object message) { ri.info(message); } /// <summary> /// Log an error message. /// </summary> /// <param name="Object">message to log</param> public virtual void Error(Object message) { ri.error(message); } /// <summary> /// Log a debug message. /// </summary> /// <param name="Object">message to log</param> public virtual void Debug(Object message) { ri.debug(message); } /// <summary> /// <p> /// Set the an ApplicationAttribue, which is an Object /// set by the application which is accessable from /// any component of the system that gets a RuntimeServices. /// This allows communication between the application /// environment and custom pluggable components of the /// Velocity engine, such as loaders and loggers. /// </p> /// <p> /// Note that there is no enfocement or rules for the key /// used - it is up to the application developer. However, to /// help make the intermixing of components possible, using /// the target Class name (e.g. com.foo.bar ) as the key /// might help avoid collision. /// </p> /// </summary> /// <param name="key">object 'name' under which the object is stored</param> /// <param name="value">object to store under this key</param> public virtual void SetApplicationAttribute(Object key, Object value_Renamed) { ri.setApplicationAttribute(key, value_Renamed); } } } --- NEW FILE: FieldMethodizer.cs --- namespace NVelocity.App { using System; using System.Collections; using System.Reflection; /// <summary> /// <p>This is a small utility class allow easy access to static fields in a class, /// such as string constants. Velocity will not introspect for class /// fields (and won't in the future :), but writing setter/getter methods to do /// this really is a pain, so use this if you really have /// to access fields. /// /// <p>The idea it so enable access to the fields just like you would in Java. /// For example, in Java, you would access a static field like /// <blockquote><pre> /// MyClass.STRING_CONSTANT /// </pre></blockquote> /// and that is the same thing we are trying to allow here. /// /// <p>So to use in your Java code, do something like this : /// <blockquote><pre> /// context.put("runtime", new FieldMethodizer( "NVelocity.Runtime.Runtime" )); /// </pre></blockquote> /// and then in your template, you can access any of your static fields in this way : /// <blockquote><pre> /// $runtime.RUNTIME_LOG_WARN_STACKTRACE /// </pre></blockquote> /// /// <p>Right now, this class only methodizes <code>public static</code> fields. It seems /// that anything else is too dangerous. This class is for convenience accessing /// 'constants'. If you have fields that aren't <code>static</code> it may be better /// to handle them by explicitly placing them into the context. /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version>$Id: FieldMethodizer.cs,v 1.5 2005/11/16 07:01:48 intesar66 Exp $</version> public class FieldMethodizer { /// <summary> /// Hold the field objects by field name /// </summary> private Hashtable fieldHash = new Hashtable(); /// <summary> /// Hold the class objects by field name /// </summary> private Hashtable classHash = new Hashtable(); /// <summary> /// Allow object to be initialized without any data. You would use /// addObject() to add data later. /// </summary> public FieldMethodizer() { } /// <summary> /// Constructor that takes as it's arg the name of the class /// to methodize. /// </summary> /// <param name="s">Name of class to methodize.</param> public FieldMethodizer(String s) { try { addObject(s); } catch (Exception e) { Console.Out.WriteLine(e); } } /// <summary> /// Constructor that takes as it's arg a living /// object to methodize. Note that it will still /// only methodized the public static fields of /// the class. /// </summary> /// <param name="o">object to methodize.</param> public FieldMethodizer(Object o) { try { addObject(o); } catch (Exception e) { Console.Out.WriteLine(e); } } /// <summary> /// Add the Name of the class to methodize /// </summary> public virtual void addObject(String s) { Type type = Type.GetType(s); inspect(type); } /// <summary> Add an Object to methodize /// </summary> public virtual void addObject(Object o) { inspect(o.GetType()); } /// <summary> /// Accessor method to get the fields by name. /// </summary> /// <param name="fieldName">Name of static field to retrieve</param> /// <returns>The value of the given field.</returns> public virtual Object Get(String fieldName) { try { FieldInfo f = (FieldInfo) fieldHash[fieldName]; if (f != null) return f.GetValue((Type) classHash[fieldName]); } catch (Exception e) { } return null; } /// <summary> Method that retrieves all public static fields /// in the class we are methodizing. /// </summary> private void inspect(Type clas) { FieldInfo[] fields = clas.GetFields(); for (int i = 0; i < fields.Length; i++) { /* * only if public and static */ if (fields[i].IsPublic && fields[i].IsStatic) { fieldHash[fields[i].Name] = fields[i]; classHash[fields[i].Name] = clas; } } } } } |
From: Sean M. <int...@us...> - 2005-11-16 07:01:59
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/Exception In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.NVelocity/Exception Added Files: MethodInvocationException.cs ParseErrorException.cs ResourceNotFoundException.cs VelocityException.cs Log Message: --- NEW FILE: VelocityException.cs --- namespace NVelocity.Exception { 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> Base class for Velocity exceptions thrown to the /// application layer. /// * /// </summary> /// <author> <a href="mailto:kd...@am...">Kyle F. Downey</a> /// </author> /// <version> $Id: VelocityException.cs,v 1.5 2005/11/16 07:01:49 intesar66 Exp $ /// /// </version> public class VelocityException : Exception { public VelocityException(String exceptionMessage) : base(exceptionMessage) { } } } --- NEW FILE: MethodInvocationException.cs --- namespace NVelocity.Exception { 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> Application-level exception thrown when a reference method is /// invoked and an exception is thrown. /// <br> /// When this exception is thrown, a best effort will be made to have /// useful information in the exception's message. For complete /// information, consult the runtime log. /// * /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version> $Id: MethodInvocationException.cs,v 1.5 2005/11/16 07:01:49 intesar66 Exp $ /// /// </version> public class MethodInvocationException : VelocityException { public virtual String MethodName { get { return methodName; } } public virtual Exception WrappedThrowable { get { return wrapped; } } public virtual String ReferenceName { get { return referenceName; } set { referenceName = value; } } private String methodName = ""; private String referenceName = ""; //UPGRADE_NOTE: Exception 'java.lang.Throwable' was converted to ' ' which has different behavior. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1100"' private Exception wrapped = null; /// <summary> CTOR - wraps the passed in exception for /// examination later /// * /// </summary> /// <param name="message"> /// </param> /// <param name="e">Throwable that we are wrapping /// </param> /// <param name="methodName">name of method that threw the exception /// /// </param> //UPGRADE_NOTE: Exception 'java.lang.Throwable' was converted to ' ' which has different behavior. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1100"' public MethodInvocationException(String message, Exception e, String methodName) : base(message) { this.wrapped = e; this.methodName = methodName; } /// <summary> Returns the name of the method that threw the /// exception /// * /// </summary> /// <returns>String name of method /// /// </returns> /// <summary> returns the wrapped Throwable that caused this /// MethodInvocationException to be thrown /// /// </summary> /// <returns>Throwable thrown by method invocation /// /// </returns> //UPGRADE_NOTE: Exception 'java.lang.Throwable' was converted to ' ' which has different behavior. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1100"' /// <summary> Sets the reference name that threw this exception /// * /// </summary> /// <param name="reference">name of reference /// /// </param> /// <summary> Retrieves the name of the reference that caused the /// exception /// * /// </summary> /// <returns>name of reference /// /// </returns> } } --- NEW FILE: ResourceNotFoundException.cs --- namespace NVelocity.Exception { 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> Application-level exception thrown when a resource of any type /// isn't found by the Velocity engine. /// <br> /// When this exception is thrown, a best effort will be made to have /// useful information in the exception's message. For complete /// information, consult the runtime log. /// * /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <author> <a href="mailto:dl...@fi...">Daniel Rall</a> /// </author> /// <version> $Id: ResourceNotFoundException.cs,v 1.5 2005/11/16 07:01:49 intesar66 Exp $ /// /// </version> public class ResourceNotFoundException : VelocityException { public ResourceNotFoundException(String exceptionMessage) : base(exceptionMessage) { } } } --- NEW FILE: ParseErrorException.cs --- namespace NVelocity.Exception { 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> Application-level exception thrown when a resource of any type /// has a syntax or other error which prevents it from being parsed. /// <br> /// When this resource is thrown, a best effort will be made to have /// useful information in the exception's message. For complete /// information, consult the runtime log. /// * /// </summary> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a> /// </author> /// <version> $Id: ParseErrorException.cs,v 1.5 2005/11/16 07:01:49 intesar66 Exp $ /// /// </version> public class ParseErrorException : VelocityException { public ParseErrorException(String exceptionMessage) : base(exceptionMessage) { } } } |
From: Sean M. <int...@us...> - 2005-11-16 07:01:58
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.NVelocity Added Files: Adapdev.NVelocity.csproj SupportClass.cs VelocityContext.cs readme.txt Log Message: --- NEW FILE: VelocityContext.cs --- namespace NVelocity { using System; using System.Collections; using NVelocity.Context; /// <summary> /// General purpose implemention of the application Context /// interface for general application use. This class should /// be used in place of the original Context class. /// </summary> /// <seealso cref=" java.util.HashMap ) /// for data storage. /// /// This context implementation cannot be shared between threads /// without those threads synchronizing access between them, as /// the HashMap is not synchronized, nor are some of the fundamentals /// of AbstractContext. If you need to share a Context between /// threads with simultaneous access for some reason, please create /// your own and extend the interface Context /// /// "/> /// <seealso cref="NVelocity.Context.Context"/> /// <author> <a href="mailto:ge...@op...">Geir Magnusson Jr.</a></author> /// <author> <a href="mailto:jv...@ap...">Jason van Zyl</a></author> /// <author> <a href="mailto:fed...@ho...">Fedor Karpelevitch</a></author> /// <author> <a href="mailto:dl...@fi...">Daniel Rall</a></author> /// <version> $Id: VelocityContext.cs,v 1.5 2005/11/16 07:01:48 intesar66 Exp $</version> public class VelocityContext : AbstractContext { /// <summary> /// Storage for key/value pairs. /// </summary> private Hashtable context = null; /// <summary> /// Creates a new instance (with no inner context). /// </summary> public VelocityContext() : this(null, null) { } /// /// <summary> /// Creates a new instance with the provided storage (and no inner context). /// </summary> public VelocityContext(Hashtable context) : this(context, null) { } /// <summary> /// Chaining constructor, used when you want to /// wrap a context in another. The inner context /// will be 'read only' - put() calls to the /// wrapping context will only effect the outermost /// context /// </summary> /// <param name="innerContext">The <code>Context</code> implementation to wrap.</param> public VelocityContext(IContext innerContext) : this(null, innerContext) { } /// <summary> /// Initializes internal storage (never to <code>null</code>), and /// inner context. /// </summary> /// <param name="context">Internal storage, or <code>null</code> to /// create default storage. /// </param> /// <param name="innerContext">Inner context. /// /// </param> public VelocityContext(Hashtable context, IContext innerContext) : base(innerContext) { this.context = (context == null ? new Hashtable() : context); } /// <summary> /// retrieves value for key from internal /// storage /// </summary> /// <param name="key">name of value to get</param> /// <returns>value as object</returns> public override Object InternalGet(String key) { return context[key]; } /// <summary> /// stores the value for key to internal /// storage /// </summary> /// <param name="key">name of value to store</param> /// <param name="value">value to store</param> /// <returns>previous value of key as Object</returns> public override Object InternalPut(String key, Object value_Renamed) { return context[key] = value_Renamed; } /// <summary> /// determines if there is a value for the /// given key /// </summary> /// <param name="key">name of value to check</param> /// <returns>true if non-null value in store</returns> public override bool InternalContainsKey(Object key) { return context.ContainsKey(key); } /// <summary> /// returns array of keys /// </summary> /// <returns>keys as []</returns> public override Object[] InternalGetKeys() { throw new NotImplementedException(); //TODO //return context.keySet().toArray(); } /// <summary> /// remove a key/value pair from the /// internal storage /// </summary> /// <param name="key">name of value to remove</param> /// <returns>value removed</returns> public override Object InternalRemove(Object key) { Object o = context[key]; context.Remove(key); return o; } /// <summary> /// Clones this context object. /// </summary> /// <returns>A deep copy of this <code>Context</code>.</returns> public Object Clone() { VelocityContext clone = null; try { clone = (VelocityContext) base.MemberwiseClone(); clone.context = new Hashtable(context); } catch (System.Exception) { // ignore } return clone; } } } --- NEW FILE: SupportClass.cs --- namespace NVelocity { using System; using System.Collections; using System.Data; using System.Data.OleDb; using System.Globalization; using System.IO; public class SupportClass { public static sbyte[] ToSByteArray(byte[] byteArray) { sbyte[] sbyteArray = new sbyte[byteArray.Length]; for (int index = 0; index < byteArray.Length; index++) sbyteArray[index] = (sbyte) byteArray[index]; return sbyteArray; } /*******************************/ public static byte[] ToByteArray(sbyte[] sbyteArray) { byte[] byteArray = new byte[sbyteArray.Length]; for (int index = 0; index < sbyteArray.Length; index++) byteArray[index] = (byte) sbyteArray[index]; return byteArray; } /*******************************/ public static Object PutElement(Hashtable hashTable, Object key, Object newValue) { Object element = hashTable[key]; hashTable[key] = newValue; return element; } /*******************************/ public class TransactionManager { public static ConnectionHashTable manager = new ConnectionHashTable(); public class ConnectionHashTable : Hashtable { public OleDbCommand CreateStatement(OleDbConnection connection) { OleDbCommand command = connection.CreateCommand(); OleDbTransaction transaction; if (this[connection] != null) { ConnectionProperties Properties = ((ConnectionProperties) this[connection]); transaction = Properties.Transaction; command.Transaction = transaction; } else { ConnectionProperties TempProp = new ConnectionProperties(); TempProp.AutoCommit = false; TempProp.TransactionLevel = 0; command.Transaction = TempProp.Transaction; Add(connection, TempProp); } return command; } public void Commit(OleDbConnection connection) { if (this[connection] != null && ((ConnectionProperties) this[connection]).AutoCommit) { OleDbTransaction transaction = ((ConnectionProperties) this[connection]).Transaction; transaction.Commit(); } } public void RollBack(OleDbConnection connection) { if (this[connection] != null && ((ConnectionProperties) this[connection]).AutoCommit) { OleDbTransaction transaction = ((ConnectionProperties) this[connection]).Transaction; transaction.Rollback(); } } public void SetAutoCommit(OleDbConnection connection, bool boolean) { if (this[connection] != null) { ConnectionProperties Properties = ((ConnectionProperties) this[connection]); Properties.AutoCommit = boolean; if (!boolean) { OleDbTransaction transaction = Properties.Transaction; if (Properties.TransactionLevel == 0) { transaction = connection.BeginTransaction(); } else { transaction = connection.BeginTransaction(Properties.TransactionLevel); } } } else { ConnectionProperties TempProp = new ConnectionProperties(); TempProp.AutoCommit = boolean; TempProp.TransactionLevel = 0; if (boolean) TempProp.Transaction = connection.BeginTransaction(); Add(connection, TempProp); } } public OleDbCommand PrepareStatement(OleDbConnection connection, string sql) { OleDbCommand command = this.CreateStatement(connection); command.CommandText = sql; return command; } public OleDbCommand PrepareCall(OleDbConnection connection, string sql) { OleDbCommand command = this.CreateStatement(connection); command.CommandText = sql; return command; } public void SetTransactionIsolation(OleDbConnection connection, int level) { if (this[connection] != null) { ConnectionProperties Properties = ((ConnectionProperties) this[connection]); Properties.TransactionLevel = (IsolationLevel) level; } else { ConnectionProperties TempProp = new ConnectionProperties(); TempProp.AutoCommit = false; TempProp.TransactionLevel = (IsolationLevel) level; Add(connection, TempProp); } } public int GetTransactionIsolation(OleDbConnection connection) { if (this[connection] != null) { ConnectionProperties Properties = ((ConnectionProperties) this[connection]); if (Properties.TransactionLevel != 0) return (int) Properties.TransactionLevel; else return 2; } else return 2; } public bool GetAutoCommit(OleDbConnection connection) { if (this[connection] != null) { return ((ConnectionProperties) this[connection]).AutoCommit; } else return false; } private class ConnectionProperties { public bool AutoCommit; public OleDbTransaction Transaction; public IsolationLevel TransactionLevel; } } } /*******************************/ public class Tokenizer { private ArrayList elements; private string source; //The tokenizer uses the default delimiter set: the space character, the tab character, the newline character, and the carriage-return character private string delimiters = " \t\n\r"; public Tokenizer(string source) { this.elements = new ArrayList(); this.elements.AddRange(source.Split(this.delimiters.ToCharArray())); this.RemoveEmptyStrings(); this.source = source; } public Tokenizer(string source, string delimiters) { this.elements = new ArrayList(); this.delimiters = delimiters; this.elements.AddRange(source.Split(this.delimiters.ToCharArray())); this.RemoveEmptyStrings(); this.source = source; } public int Count { get { return (this.elements.Count); } } public bool HasMoreTokens() { return (this.elements.Count > 0); } public string NextToken() { string result; if (source == "") throw new System.Exception(); else { this.elements = new ArrayList(); this.elements.AddRange(this.source.Split(delimiters.ToCharArray())); RemoveEmptyStrings(); result = (string) this.elements[0]; this.elements.RemoveAt(0); this.source = this.source.Replace(result, ""); this.source = this.source.TrimStart(this.delimiters.ToCharArray()); return result; } } public string NextToken(string delimiters) { this.delimiters = delimiters; return NextToken(); } private void RemoveEmptyStrings() { //VJ++ does not treat empty strings as tokens for (int index = 0; index < this.elements.Count; index++) if ((string) this.elements[index] == "") { this.elements.RemoveAt(index); index--; } } } /*******************************/ public static long FileLength(FileInfo file) { if (Directory.Exists(file.FullName)) return 0; else return file.Length; } /*******************************/ public static void WriteStackTrace(System.Exception throwable, TextWriter stream) { stream.Write(throwable.StackTrace); stream.Flush(); } public class TextNumberFormat { // Declaration of fields private NumberFormatInfo numberFormat; private enum formatTypes { General, Number, Currency, Percent } ; private int numberFormatType; private bool groupingActivated; private string separator; private int digits; // CONSTRUCTORS public TextNumberFormat() { this.numberFormat = new NumberFormatInfo(); this.numberFormatType = (int) formatTypes.General; this.groupingActivated = true; this.separator = this.GetSeparator((int) formatTypes.General); this.digits = 3; } private TextNumberFormat(formatTypes theType, int digits) { this.numberFormat = NumberFormatInfo.CurrentInfo; this.numberFormatType = (int) theType; this.groupingActivated = true; this.separator = this.GetSeparator((int) theType); this.digits = digits; } private TextNumberFormat(formatTypes theType, CultureInfo cultureNumberFormat, int digits) { this.numberFormat = cultureNumberFormat.NumberFormat; this.numberFormatType = (int) theType; this.groupingActivated = true; this.separator = this.GetSeparator((int) theType); this.digits = digits; } public static TextNumberFormat getTextNumberInstance() { TextNumberFormat instance = new TextNumberFormat(formatTypes.Number, 3); return instance; } public static TextNumberFormat getTextNumberCurrencyInstance() { TextNumberFormat instance = new TextNumberFormat(formatTypes.Currency, 3); return instance; } public static TextNumberFormat getTextNumberPercentInstance() { TextNumberFormat instance = new TextNumberFormat(formatTypes.Percent, 3); return instance; } public static TextNumberFormat getTextNumberInstance(CultureInfo culture) { TextNumberFormat instance = new TextNumberFormat(formatTypes.Number, culture, 3); return instance; } public static TextNumberFormat getTextNumberCurrencyInstance(CultureInfo culture) { TextNumberFormat instance = new TextNumberFormat(formatTypes.Currency, culture, 3); return instance; } public static TextNumberFormat getTextNumberPercentInstance(CultureInfo culture) { TextNumberFormat instance = new TextNumberFormat(formatTypes.Percent, culture, 3); return instance; } public Object Clone() { return (Object) this; } public override bool Equals(Object textNumberObject) { return Object.Equals((Object) this, textNumberObject); } public string FormatDouble(double number) { if (this.groupingActivated) { return number.ToString(this.GetCurrentFormatString() + this.digits, this.numberFormat); } else { return (number.ToString(this.GetCurrentFormatString() + this.digits, this.numberFormat)).Replace(this.separator, ""); } } public string FormatLong(long number) { if (this.groupingActivated) { return number.ToString(this.GetCurrentFormatString() + this.digits, this.numberFormat); } else { return (number.ToString(this.GetCurrentFormatString() + this.digits, this.numberFormat)).Replace(this.separator, ""); } } public static CultureInfo[] GetAvailableCultures() { return CultureInfo.GetCultures(CultureTypes.AllCultures); } public override int GetHashCode() { return this.GetHashCode(); } private string GetCurrentFormatString() { string currentFormatString = "n"; //Default value switch (this.numberFormatType) { case (int) formatTypes.Currency: currentFormatString = "c"; break; case (int) formatTypes.General: currentFormatString = "n" + this.numberFormat.NumberDecimalDigits; break; case (int) formatTypes.Number: currentFormatString = "n" + this.numberFormat.NumberDecimalDigits; break; case (int) formatTypes.Percent: currentFormatString = "p"; break; } return currentFormatString; } private string GetSeparator(int numberFormatType) { string separatorItem = " "; //Default Separator switch (numberFormatType) { case (int) formatTypes.Currency: separatorItem = this.numberFormat.CurrencyGroupSeparator; break; case (int) formatTypes.General: separatorItem = this.numberFormat.NumberGroupSeparator; break; case (int) formatTypes.Number: separatorItem = this.numberFormat.NumberGroupSeparator; break; case (int) formatTypes.Percent: separatorItem = this.numberFormat.PercentGroupSeparator; break; } return separatorItem; } public bool GroupingUsed { get { return (this.groupingActivated); } set { this.groupingActivated = value; } } public int Digits { get { return this.digits; } set { this.digits = value; } } } /*******************************/ public class DateTimeFormatManager { public static DateTimeFormatHashTable manager = new DateTimeFormatHashTable(); public class DateTimeFormatHashTable : Hashtable { public void SetDateFormatPattern(DateTimeFormatInfo format, String newPattern) { if (this[format] != null) ((DateTimeFormatProperties) this[format]).DateFormatPattern = newPattern; else { DateTimeFormatProperties tempProps = new DateTimeFormatProperties(); tempProps.DateFormatPattern = newPattern; Add(format, tempProps); } } public string GetDateFormatPattern(DateTimeFormatInfo format) { if (this[format] == null) return "d-MMM-yy"; else return ((DateTimeFormatProperties) this[format]).DateFormatPattern; } public void SetTimeFormatPattern(DateTimeFormatInfo format, String newPattern) { if (this[format] != null) ((DateTimeFormatProperties) this[format]).TimeFormatPattern = newPattern; else { DateTimeFormatProperties tempProps = new DateTimeFormatProperties(); tempProps.TimeFormatPattern = newPattern; Add(format, tempProps); } } public string GetTimeFormatPattern(DateTimeFormatInfo format) { if (this[format] == null) return "h:mm:ss tt"; else return ((DateTimeFormatProperties) this[format]).TimeFormatPattern; } private class DateTimeFormatProperties { public string DateFormatPattern = "d-MMM-yy"; public string TimeFormatPattern = "h:mm:ss tt"; } } } /*******************************/ public static string FormatDateTime(DateTimeFormatInfo format, DateTime date) { string timePattern = DateTimeFormatManager.manager.GetTimeFormatPattern(format); string datePattern = DateTimeFormatManager.manager.GetDateFormatPattern(format); return date.ToString(datePattern + " " + timePattern, format); } /*******************************/ public static DateTimeFormatInfo GetDateTimeFormatInstance(int dateStyle, int timeStyle, CultureInfo culture) { DateTimeFormatInfo format = culture.DateTimeFormat; switch (timeStyle) { case -1: DateTimeFormatManager.manager.SetTimeFormatPattern(format, ""); break; case 0: DateTimeFormatManager.manager.SetTimeFormatPattern(format, "h:mm:ss 'o clock' tt zzz"); break; case 1: DateTimeFormatManager.manager.SetTimeFormatPattern(format, "h:mm:ss tt zzz"); break; case 2: DateTimeFormatManager.manager.SetTimeFormatPattern(format, "h:mm:ss tt"); break; case 3: DateTimeFormatManager.manager.SetTimeFormatPattern(format, "h:mm tt"); break; } switch (dateStyle) { case -1: DateTimeFormatManager.manager.SetDateFormatPattern(format, ""); break; case 0: DateTimeFormatManager.manager.SetDateFormatPattern(format, "dddd, MMMM dd%, yyy"); break; case 1: DateTimeFormatManager.manager.SetDateFormatPattern(format, "MMMM dd%, yyy"); break; case 2: DateTimeFormatManager.manager.SetDateFormatPattern(format, "d-MMM-yy"); break; case 3: DateTimeFormatManager.manager.SetDateFormatPattern(format, "M/dd/yy"); break; } return format; } } } --- NEW FILE: readme.txt --- Adapdev.NVelocity is a modified version of the NVelocity project (http://nvelocity.sourceforge.net/). The following changes have taken place: - Switched to Adapdev.NET library version - Signed with Adapdev.NET key - Removed Html portions of library - Removed logging portions of library - Fixed issue with relative file path references in #parse call --- NEW FILE: Adapdev.NVelocity.csproj --- <VisualStudioProject> <CSHARP ProjectType = "Local" ProductVersion = "7.10.3077" SchemaVersion = "2.0" ProjectGuid = "{75D57D5C-250A-447C-80BC-2FF9DC8A14D2}" > <Build> <Settings ApplicationIcon = "" AssemblyKeyContainerName = "" AssemblyName = "Adapdev.NVelocity" AssemblyOriginatorKeyFile = "" DefaultClientScript = "JScript" DefaultHTMLPageLayout = "Grid" DefaultTargetSchema = "IE50" DelaySign = "false" OutputType = "Library" PreBuildEvent = "" PostBuildEvent = "" RootNamespace = "Adapdev.NVelocity" 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 = "log4net" AssemblyName = "log4net" HintPath = "..\..\lib\log4net.dll" /> </References> </Build> <Files> <Include> <File RelPath = "AdapdevAssemblyInfo.cs" Link = "..\AdapdevAssemblyInfo.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "readme.txt" BuildAction = "Content" /> <File RelPath = "SupportClass.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Template.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "VelocityContext.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "App\AppSupportClass.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "App\FieldMethodizer.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "App\Velocity.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "App\VelocityEngine.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "App\Events\EventCartridge.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "App\Events\EventHandler.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "App\Events\MethodExceptionEventHandler.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "App\Events\NullSetEventHandler.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "App\Events\ReferenceInsertionEventHandler.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "App\Tools\VelocityFormatter.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Commons\Collections\CollectionsUtil.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Commons\Collections\ExtendedProperties.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Commons\Collections\PropertiesReader.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Commons\Collections\PropertiesTokenizer.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Commons\Collections\StringTokenizer.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Context\AbstractContext.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Context\IContext.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Context\InternalContextAdapter.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Context\InternalContextAdapterImpl.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Context\InternalContextBase.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Context\InternalEventContext.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Context\InternalHousekeepingContext.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Context\InternalWrapperContext.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Context\VMContext.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Dvsl\Dvsl.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Dvsl\DvslContext.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Dvsl\DvslNode.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Dvsl\DvslNodeContext.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Dvsl\DvslNodeImpl.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Dvsl\TemplateHandler.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Dvsl\Transformer.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Dvsl\TransformTool.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Dvsl\Directive\MatchDirective.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Dvsl\Directive\NameDirective.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Dvsl\Resource\defaultroot.dvsl" BuildAction = "None" /> <File RelPath = "Exception\MethodInvocationException.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Exception\ParseErrorException.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Exception\ResourceNotFoundException.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Exception\VelocityException.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "IO\VelocityWriter.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\RuntimeConstants.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\RuntimeInstance.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\RuntimeServices.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\RuntimeSingleton.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\VelocimacroFactory.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\VelocimacroManager.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Defaults\directive.properties" BuildAction = "None" /> <File RelPath = "Runtime\Defaults\nvelocity.properties" BuildAction = "None" /> <File RelPath = "Runtime\Directive\Directive.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Directive\DirectiveConstants.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Directive\Foreach.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Directive\Include.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Directive\Literal.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Directive\Macro.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Directive\Parse.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Directive\ParseDirectiveException.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Directive\VelocimacroProxy.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Directive\VMProxyArg.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Exception\NodeException.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Exception\ReferenceException.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\CharStream.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\JJTParserState.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\ParseException.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Parser.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\ParserConstants.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\ParserTokenManager.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\ParserTreeConstants.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Token.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\TokenMgrError.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\VelocityCharStream.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\AbstractExecutor.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTAddNode.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTAndNode.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTAssignment.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTBlock.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTComment.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTDirective.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTDivNode.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTElseIfStatement.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTElseStatement.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTEQNode.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTEscape.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTEscapedDirective.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTExpression.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTFalse.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTGENode.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTGTNode.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTIdentifier.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTIfStatement.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTIncludeStatement.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTIntegerRange.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTLENode.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTLTNode.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTMethod.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTModNode.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTMulNode.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTNENode.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTNotNode.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTNumberLiteral.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTObjectArray.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTOrNode.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTParameters.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTprocess.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTReference.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTSetDirective.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTStringLiteral.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTSubtractNode.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTText.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTTrue.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTVariable.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ASTWord.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\BooleanPropertyExecutor.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\GetExecutor.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\INode.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\NodeUtils.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\ParserVisitor.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\PropertyExecutor.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Parser\Node\SimpleNode.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Resource\ContentResource.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Resource\Resource.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Resource\ResourceCache.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Resource\ResourceCacheImpl.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Resource\ResourceFactory.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Resource\ResourceManager.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Resource\ResourceManagerImpl.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Resource\Loader\FileResourceLoader.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Resource\Loader\ResourceLoader.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Resource\Loader\ResourceLoaderFactory.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Resource\Loader\ResourceLocator.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Visitor\BaseVisitor.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Visitor\NodeViewMode.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Runtime\Visitor\VMReferenceMungeVisitor.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Tool\DataInfo.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Tool\IToolInfo.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Tool\ToolLoader.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Util\Iterator.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Util\SimplePool.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Util\StringUtils.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Util\Introspection\AmbiguousException.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Util\Introspection\ClassMap.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Util\Introspection\IntrospectionCacheData.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Util\Introspection\Introspector.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Util\Introspection\IntrospectorBase.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Util\Introspection\MethodMap.cs" SubType = "Code" BuildAction = "Compile" /> <File RelPath = "Util\Introspection\Twonk.cs" SubType = "Code" BuildAction = "Compile" /> </Include> </Files> </CSHARP> </VisualStudioProject> |
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.Data/Sql In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.Data/Sql Added Files: AccessCriteria.cs AccessDeleteQuery.cs AccessInsertQuery.cs AccessSelectQuery.cs AccessUpdateQuery.cs Criteria.cs CriteriaFactory.cs DeleteQuery.cs DialectConstants.cs ICriteria.cs IDeleteQuery.cs IInsertQuery.cs INonSelectQuery.cs IQuery.cs ISelectQuery.cs IUpdateQuery.cs InsertQuery.cs MySqlCriteria.cs MySqlDeleteQuery.cs MySqlInsertQuery.cs MySqlSelectQuery.cs MySqlUpdateQuery.cs OracleCriteria.cs OracleDeleteQuery.cs OracleInsertQuery.cs OracleSelectQuery.cs OracleUpdateQuery.cs QueryConstants.cs QueryFactory.cs QueryHelper.cs SelectQuery.cs SqlDeleteQuery.cs SqlInsertQuery.cs SqlSelectQuery.cs SqlServerCriteria.cs SqlUpdateQuery.cs UpdateQuery.cs Log Message: --- NEW FILE: ICriteria.cs --- namespace Adapdev.Data.Sql { using System.Collections; /// <summary> /// Summary description for ICriteria. /// </summary> public interface ICriteria { void AddAnd(); void AddAndCriteria(ICriteria pc); void AddCriteriaSeparator(CriteriaType ct); void AddBetween(string columnName, object value1, object value2); void AddEqualTo(string columnName, object columnValue); void AddEqualTo(string tableName, string columnName, object columnValue); void AddEqualTo(string columnName); void AddExists(IQuery subQuery); void AddGreaterThanOrEqualTo(string columnName, object columnValue); void AddGreaterThan(string columnName, object columnValue); void AddIn(string columnName, IQuery subQuery); void AddIn(string columnName, ICollection values); void AddIsNull(string columnName); void AddLessThanOrEqualTo(string columnName, object columnValue); void AddLessThan(string columnName, object columnValue); void AddLike(string columnName, object columnValue); void AddNotBetween(string columnName, object value1, object value2); void AddNotEqualTo(string columnName, object columnValue); void AddNotExists(IQuery subQuery); void AddNotIn(string columnName, ICollection values); void AddNotIn(string columnName, IQuery subQuery); void AddNotLike(string columnName, object columnValue); void AddNotNull(string columnName); void AddOr(); void AddOrCriteria(ICriteria pc); void AddSql(string sql); string GetText(); DbProviderType DbProviderType { get; set; } } } --- NEW FILE: OracleCriteria.cs --- namespace Adapdev.Data.Sql { using System.Collections; using System.Text; using Adapdev.Text; /// <summary> /// Summary description for ICriteria. /// </summary> public class OracleCriteria : Criteria { public OracleCriteria() : base(DbType.ORACLE, DbProviderType.ORACLE) { } public OracleCriteria(string sql) : base(DbType.ORACLE, DbProviderType.ORACLE, sql) { } } } --- NEW FILE: QueryHelper.cs --- namespace Adapdev.Data.Sql { using System; using System.Data; using Adapdev.Text; /// <summary> /// Provides common routines for building queries /// </summary> public class QueryHelper { /// <summary> /// Surrounds the object with the proper, datastore-specific markup. /// </summary> /// <param name="o"></param> /// <param name="type"></param> /// <returns></returns> /// <example> /// If the passed in object is a date, and the DbType is Access, then the returned value would be #date#. /// In contrast, if the DbType is SqlServer, then the returned value would be 'date'. /// </example> public static string DressUp(object o, Adapdev.Data.DbType type) { string ro = ""; if (Util.IsNumeric(o)) { ro = o.ToString(); } else if (Util.IsDateTime(o)) { ro = QueryHelper.GetDateDelimeter(type) + o.ToString() + QueryHelper.GetDateDelimeter(type); } // else if(o is Boolean) // { // ro = o.ToString().ToLower(); // } else { ro = QueryHelper.GetStringDelimeter(type) + o.ToString() + QueryHelper.GetStringDelimeter(type); } return ro; } /// <summary> /// Gets the proper date delimiter for the specified DbType /// </summary> /// <param name="type"></param> /// <returns></returns> public static char GetDateDelimeter(Adapdev.Data.DbType type) { switch (type) { case Adapdev.Data.DbType.ACCESS: return DialectConstants.ACCESS_DATE; case Adapdev.Data.DbType.SQLSERVER: return DialectConstants.SQLSERVER_DATE; case Adapdev.Data.DbType.ORACLE: return DialectConstants.ORACLE_DATE; case Adapdev.Data.DbType.MYSQL: return DialectConstants.MYSQL_DATE; default: throw new Exception("DbType " + type + " not supported currently."); } } /// <summary> /// Gets the specified /// </summary> /// <param name="type"></param> /// <returns></returns> public static char GetPreDelimeter(Adapdev.Data.DbType type) { switch (type) { case Adapdev.Data.DbType.ACCESS: return DialectConstants.ACCESS_PREDELIM; case Adapdev.Data.DbType.SQLSERVER: return DialectConstants.SQLSERVER_PREDELIM; case Adapdev.Data.DbType.ORACLE: return DialectConstants.ORACLE_PREDELIM; case Adapdev.Data.DbType.MYSQL: return DialectConstants.MYSQL_PREDELIM; default: throw new Exception("DbType " + type + " not supported currently."); } } /// <summary> /// /// </summary> /// <param name="type"></param> /// <returns></returns> public static char GetPostDelimeter(Adapdev.Data.DbType type) { switch (type) { case Adapdev.Data.DbType.ACCESS: return DialectConstants.ACCESS_POSTDELIM; case Adapdev.Data.DbType.SQLSERVER: return DialectConstants.SQLSERVER_POSTDELIM; case Adapdev.Data.DbType.ORACLE: return DialectConstants.ORACLE_POSTDELIM; case Adapdev.Data.DbType.MYSQL: return DialectConstants.MYSQL_POSTDELIM; default: throw new Exception("DbType " + type + " not supported currently."); } } /// <summary> /// Gets the datastore-specific string delimiter /// </summary> /// <param name="type"></param> /// <returns></returns> public static char GetStringDelimeter(Adapdev.Data.DbType type) { switch (type) { case Adapdev.Data.DbType.ACCESS: return DialectConstants.ACCESS_STRING; case Adapdev.Data.DbType.SQLSERVER: return DialectConstants.SQLSERVER_STRING; case Adapdev.Data.DbType.ORACLE: return DialectConstants.ORACLE_STRING; case Adapdev.Data.DbType.MYSQL: return DialectConstants.MYSQL_STRING; default: throw new Exception("DbType " + type + " not supported currently."); } } /// <summary> /// Gets the provider type specific parameter name /// </summary> /// <param name="columnName"></param> /// <param name="provider"></param> /// <returns></returns> public static string GetParameterName(string columnName, DbProviderType provider) { switch (provider) { case DbProviderType.SQLSERVER: columnName = StringUtil.RemoveSpaces(columnName); return "@" + columnName; case DbProviderType.ORACLE: columnName = StringUtil.RemoveSpaces(columnName); return ":" + columnName; case DbProviderType.OLEDB: return "?"; case DbProviderType.MYSQL: columnName = StringUtil.RemoveSpaces(columnName); return "?" + columnName; default: throw new Exception("DbProviderType " + provider + " is not currently supported."); } } public static string GetSqlServerLastInsertedCommand(string table) { return "SELECT IDENT_CURRENT('" + table + "');"; } public static string GetSqlServerLastInsertedScopeCommand() { return "SELECT SCOPE_IDENTITY();"; } public static string GetAccessLastInsertedCommand(string table, string column) { string s = "SELECT MAX([" + column + "]) FROM [" + table + "];"; Console.WriteLine(s); return s; } public static string GetOracleLastInsertedCommand(string table, string column) { string s = "SELECT MAX(" + column + ") FROM " + table + ";"; Console.WriteLine(s); return s; } public static string GetMySqlLastInsertedCommand(string table, string column) { string s = "SELECT `" + column + "` FROM `" + table + "` ORDER BY `" + column + "` DESC LIMIT 1"; Console.WriteLine(s); return s; } } } --- NEW FILE: DeleteQuery.cs --- namespace Adapdev.Data.Sql { using System.Text; public abstract class DeleteQuery : IDeleteQuery { protected string _table = ""; protected StringBuilder sb = new StringBuilder(); protected ICriteria criteria = null; protected DbType type = DbType.SQLSERVER; protected DbProviderType provider = DbProviderType.SQLSERVER; public DeleteQuery(DbType type, DbProviderType provider) { this.type = type; this.provider = provider; } public DeleteQuery(DbType type, DbProviderType provider, string tableName) : this(type, provider) { this.SetTable(tableName); } public void SetCriteria(ICriteria c) { criteria = c; } public void SetTable(string tableName) { this._table = QueryHelper.GetPreDelimeter(this.type) + tableName + QueryHelper.GetPostDelimeter(this.type); } public ICriteria CreateCriteria() { return CriteriaFactory.CreateCriteria(this.type); } public virtual string GetText() { return "DELETE FROM " + this._table + this.GetCriteria(); } protected string GetCriteria() { if (this.criteria == null) return ""; else return criteria.GetText(); } public DbProviderType DbProviderType { get { return this.provider; } set { this.provider = value; } } } } --- NEW FILE: SqlInsertQuery.cs --- namespace Adapdev.Data.Sql { /// <summary> /// Summary description for SqlInsertQuery. /// </summary> public class SqlInsertQuery : InsertQuery { public SqlInsertQuery() : base(DbType.SQLSERVER, DbProviderType.SQLSERVER) { } public SqlInsertQuery(string tableName) : base(DbType.SQLSERVER, DbProviderType.SQLSERVER, tableName) { } } } --- NEW FILE: MySqlSelectQuery.cs --- using System; namespace Adapdev.Data.Sql { /// <summary> /// Summary description for MySqlSelectQuery. /// </summary> public class MySqlSelectQuery : SelectQuery { public MySqlSelectQuery():base(DbType.MYSQL, DbProviderType.MYSQL){} public MySqlSelectQuery(string table):base(DbType.MYSQL, DbProviderType.MYSQL, table){} protected override string GetLimit() { if (maxRecords > 0) { return " LIMIT " + maxRecords; } return ""; } public override string GetText() { return "SELECT " + this.GetColumns() + " FROM " + this._table + this._join + this.GetCriteria() + this.GetOrderBy() + this.GetGroupBy() + this.GetLimit(); } } } --- NEW FILE: SqlUpdateQuery.cs --- namespace Adapdev.Data.Sql { /// <summary> /// Summary description for UpdateQuery. /// </summary> public class SqlUpdateQuery : UpdateQuery { public SqlUpdateQuery() : base(DbType.SQLSERVER, DbProviderType.SQLSERVER) { } public SqlUpdateQuery(string tableName) : base(DbType.SQLSERVER, DbProviderType.SQLSERVER, tableName) { } } } --- NEW FILE: OracleDeleteQuery.cs --- namespace Adapdev.Data.Sql { /// <summary> /// Summary description for SqlDeleteQuery. /// </summary> public class OracleDeleteQuery : DeleteQuery { public OracleDeleteQuery() : base(DbType.ORACLE, DbProviderType.ORACLE) { } public OracleDeleteQuery(string tableName) : base(DbType.ORACLE, DbProviderType.ORACLE, tableName) { } } } --- NEW FILE: ISelectQuery.cs --- namespace Adapdev.Data.Sql { /// <summary> /// Summary description for ISelectQuery. /// </summary> public interface ISelectQuery : IQuery { /// <summary> /// Adds the specified column /// </summary> /// <param name="columnName">The name of the column</param> void Add(string columnName); /// <summary> /// Adds the specified table.column /// </summary> /// <param name="tableName">Name of the table.</param> /// <param name="columnName">Name of the column.</param> void Add(string tableName, string columnName); /// <summary> /// Adds the column alias. /// </summary> /// <param name="tableName">Name of the table.</param> /// <param name="columnName">Name of the column.</param> /// <param name="alias">Alias.</param> void AddColumnAlias(string tableName, string columnName, string alias); /// <summary> /// Adds the column alias. /// </summary> /// <param name="columnName">Name of the column.</param> /// <param name="alias">Alias.</param> void AddColumnAlias(string columnName, string alias); /// <summary> /// Creates a SELECT * FROM statement, so that individual column names /// don't have to be added /// </summary> void AddAll(); /// <summary> /// Adds a COUNT([columnName]) statement in the datastore specific format /// </summary> /// <param name="columnName"></param> void AddCount(string columnName); /// <summary> /// Adds a COUNT(*) statement in the datastore specific format /// </summary> void AddCountAll(); /// <summary> /// Adds a ORDER BY [columnName] statement in the datastore specific format /// </summary> /// <param name="columnName"></param> void AddOrderBy(string columnName); /// <summary> /// Adds a ORDER BY [table].[column] statement in the datastore specific format /// </summary> /// <param name="tableName"></param> /// <param name="columnName"></param> void AddOrderBy(string tableName, string columnName); /// <summary> /// Adds a ORDER BY [column1], [column2]... statement in the datastore specific format /// </summary> /// <param name="columns"></param> void AddOrderBy(params string[] columns); /// <summary> /// Adds a GROUP BY [columnName] statement in the datastore specific format /// </summary> /// <param name="columnName"></param> void AddGroupBy(string columnName); /// <summary> /// Adds a GROUP BY [column1], [column2]... statement in the datastore specific format /// </summary> /// <param name="columns"></param> void AddGroupBy(params string[] columns); /// <summary> /// Adds a SELECT ... FROM [table] [JoinType] [secondTable] ON [firstTableColumn] = [secondTableColumn] /// </summary> /// <param name="secondTable">The name of the second table to join on</param> /// <param name="firstTableColumn">The name of the first table's join column</param> /// <param name="secondTableColumn">The name of the second table's join column</param> /// <param name="type">The join type</param> void AddJoin(string secondTable, string firstTableColumn, string secondTableColumn, JoinType type); /// <summary> /// Set's the maximum number of records to retrieve /// </summary> /// <param name="maxRecords"></param> void SetLimit(int maxRecords); OrderBy OrderBy { get; set; } } public enum OrderBy { ASCENDING, DESCENDING } public enum JoinType { LEFT, RIGHT, INNER } } --- NEW FILE: AccessUpdateQuery.cs --- using System; namespace Adapdev.Data.Sql { /// <summary> /// Summary description for AccessUpdateQuery. /// </summary> public class AccessUpdateQuery : UpdateQuery { public AccessUpdateQuery():base(DbType.ACCESS, DbProviderType.OLEDB){} public AccessUpdateQuery(string table):base(DbType.ACCESS, DbProviderType.OLEDB, table){} } } --- NEW FILE: SqlSelectQuery.cs --- namespace Adapdev.Data.Sql { public class SqlSelectQuery : SelectQuery { public SqlSelectQuery() : base(DbType.SQLSERVER, DbProviderType.SQLSERVER) { } public SqlSelectQuery(string tableName) : base(DbType.SQLSERVER, DbProviderType.SQLSERVER, tableName) { } } } --- NEW FILE: OracleUpdateQuery.cs --- namespace Adapdev.Data.Sql { /// <summary> /// Summary description for UpdateQuery. /// </summary> public class OracleUpdateQuery : UpdateQuery { public OracleUpdateQuery() : base(DbType.ORACLE, DbProviderType.ORACLE) { } public OracleUpdateQuery(string tableName) : base(DbType.ORACLE, DbProviderType.ORACLE, tableName) { } } } --- NEW FILE: AccessCriteria.cs --- namespace Adapdev.Data.Sql { /// <summary> /// Summary description for AccessCriteria. /// </summary> public class AccessCriteria : Criteria { public AccessCriteria() : base(DbType.ACCESS, DbProviderType.OLEDB) { } public AccessCriteria(string sql) : base(DbType.ACCESS, DbProviderType.OLEDB, sql) { } } } --- NEW FILE: CriteriaFactory.cs --- namespace Adapdev.Data.Sql { using System; /// <summary> /// Summary description for CriteriaFactory. /// </summary> public class CriteriaFactory { public static ICriteria CreateCriteria(DbType type) { switch (type) { case DbType.ACCESS: return new AccessCriteria(); case DbType.SQLSERVER: return new SqlServerCriteria(); case DbType.ORACLE: return new OracleCriteria(); case DbType.MYSQL: return new MySqlCriteria(); default: throw new Exception("DbType " + type + " not supported currently."); } } } } --- NEW FILE: INonSelectQuery.cs --- namespace Adapdev.Data.Sql { /// <summary> /// Represents a query that does not return records /// </summary> public interface INonSelectQuery : IQuery { } } --- NEW FILE: SqlDeleteQuery.cs --- namespace Adapdev.Data.Sql { /// <summary> /// Summary description for SqlDeleteQuery. /// </summary> public class SqlDeleteQuery : DeleteQuery { public SqlDeleteQuery() : base(DbType.SQLSERVER, DbProviderType.SQLSERVER) { } public SqlDeleteQuery(string tableName) : base(DbType.SQLSERVER, DbProviderType.SQLSERVER, tableName) { } } } --- NEW FILE: IUpdateQuery.cs --- namespace Adapdev.Data.Sql { /// <summary> /// Summary description for IUpdateQuery. /// </summary> public interface IUpdateQuery : INonSelectQuery { /// <summary> /// Adds the columnName to the update query /// </summary> /// <param name="columnName"></param> /// <remarks>Since no value is passed in, the datastore specific parameter representation /// will be added</remarks> void Add(string columnName); /// <summary> /// Adds the column name and value to the update query /// </summary> /// <param name="columnName"></param> /// <param name="columnValue"></param> void Add(string columnName, object columnValue); } } --- NEW FILE: InsertQuery.cs --- namespace Adapdev.Data.Sql { using System.Text; using Adapdev.Text; /// <summary> /// Summary description for UpdateQuery. /// </summary> public abstract class InsertQuery : IInsertQuery { protected string _table = ""; protected StringBuilder sbn = new StringBuilder(); protected StringBuilder sbv = new StringBuilder(); protected string[] cnames = new string[100]; protected string[] cvalues = new string[100]; protected int cindex = 0; protected ICriteria criteria = null; protected DbType type = DbType.SQLSERVER; protected DbProviderType provider = DbProviderType.SQLSERVER; public InsertQuery(DbType type, DbProviderType provider) { this.type = type; this.provider = provider; } public InsertQuery(DbType type, DbProviderType provider, string tableName) : this(type, provider) { this.SetTable(tableName); } public void SetCriteria(ICriteria c) { criteria = c; } public void Add(string columnName) { cnames[cindex] = columnName; cvalues[cindex] = QueryHelper.GetParameterName(columnName, this.provider); cindex++; } public void Add(string columnName, object columnValue) { cnames[cindex] = columnName; cvalues[cindex] = QueryHelper.DressUp(columnValue, this.type); cindex++; } public void SetTable(string tableName) { this._table = QueryHelper.GetPreDelimeter(this.type) + tableName + QueryHelper.GetPostDelimeter(this.type); } public ICriteria CreateCriteria() { return CriteriaFactory.CreateCriteria(this.type); } public virtual string GetText() { return "INSERT INTO " + this._table + " ( " + this.GetColumnNames() + " ) VALUES ( " + this.GetColumnValues() + " ) " + this.GetCriteria(); } protected string GetColumnNames() { sbn.Remove(0, sbn.Length); for (int i = 0; i <= cindex; i++) { if (cnames[i] != null && cnames[i].Length > 0) { sbn.Append(QueryHelper.GetPreDelimeter(this.type) + cnames[i] + QueryHelper.GetPostDelimeter(this.type) + ", "); } } return StringUtil.RemoveFinalComma(this.sbn.ToString()); } protected string GetColumnValues() { sbv.Remove(0, sbv.Length); for (int i = 0; i <= cindex; i++) { if (cnames[i] != null && cnames[i].Length > 0) { sbv.Append(cvalues[i] + ", "); } } return StringUtil.RemoveFinalComma(this.sbv.ToString()); } protected string GetCriteria() { if (this.criteria == null) return ""; else return criteria.GetText(); } public DbProviderType DbProviderType { get { return this.provider; } set { this.provider = value; } } } } --- NEW FILE: SelectQuery.cs --- namespace Adapdev.Data.Sql { using System; using System.Collections; using System.Text; using Adapdev.Text; public abstract class SelectQuery : ISelectQuery { protected string _table = ""; protected StringBuilder sb = new StringBuilder(); protected Queue order = new Queue(); protected Queue group = new Queue(); protected OrderBy ob = OrderBy.ASCENDING; protected ICriteria criteria = null; protected DbType type = DbType.SQLSERVER; protected DbProviderType provider = DbProviderType.SQLSERVER; protected int maxRecords = 0; protected string _join = ""; public SelectQuery(DbType type, DbProviderType provider) { this.type = type; this.provider = provider; } public SelectQuery(DbType type, DbProviderType provider, string tableName): this(type, provider) { this.SetTable(tableName); } public void SetCriteria(ICriteria c) { criteria = c; } public void Add(string columnName) { sb.Append(" "); sb.Append(QueryHelper.GetPreDelimeter(this.type)); sb.Append(columnName); sb.Append(QueryHelper.GetPostDelimeter(this.type)); sb.Append(","); } public void Add(string tableName, string columnName) { sb.Append(" "); sb.Append(QueryHelper.GetPreDelimeter(this.type)); sb.Append(tableName); sb.Append(QueryHelper.GetPostDelimeter(this.type)); sb.Append("."); sb.Append(QueryHelper.GetPreDelimeter(this.type)); sb.Append(columnName); sb.Append(QueryHelper.GetPostDelimeter(this.type)); sb.Append(","); } public void AddColumnAlias(string columnName, string alias) { sb.Append(" "); sb.Append(QueryHelper.GetPreDelimeter(this.type)); sb.Append(columnName); sb.Append(QueryHelper.GetPostDelimeter(this.type)); sb.Append(" AS "); sb.Append(alias); sb.Append(","); } public void AddColumnAlias(string tableName, string columnName, string alias) { sb.Append(" "); sb.Append(QueryHelper.GetPreDelimeter(this.type)); sb.Append(tableName); sb.Append(QueryHelper.GetPostDelimeter(this.type)); sb.Append("."); sb.Append(QueryHelper.GetPreDelimeter(this.type)); sb.Append(columnName); sb.Append(QueryHelper.GetPostDelimeter(this.type)); sb.Append(" AS "); sb.Append(alias); sb.Append(","); } public void AddAll() { sb.Append(" * "); } public virtual void AddCount(string columnName) { sb.Append(" COUNT(" + QueryHelper.GetPreDelimeter(this.type) + columnName + QueryHelper.GetPostDelimeter(this.type) + ") "); } public virtual void AddCountAll() { sb.Append(" COUNT(*) "); } public void AddOrderBy(string columnName) { order.Enqueue(QueryHelper.GetPreDelimeter(this.type) + columnName + QueryHelper.GetPostDelimeter(this.type)); } public void AddOrderBy(string tableName, string columnName) { order.Enqueue(QueryHelper.GetPreDelimeter(this.type) + tableName + QueryHelper.GetPostDelimeter(this.type) + "." + QueryHelper.GetPreDelimeter(this.type) + columnName + QueryHelper.GetPostDelimeter(this.type)); } public void AddOrderBy(string tableName, params string[] columns) { foreach (string s in columns) { this.AddOrderBy(tableName, s); } } public void AddOrderBy(params string[] columns) { foreach (string s in columns) { this.AddOrderBy(s); } } public void AddGroupBy(string columnName) { group.Enqueue(QueryHelper.GetPreDelimeter(this.type) + columnName + QueryHelper.GetPostDelimeter(this.type)); } public void AddGroupBy(params string[] columns) { foreach (string s in columns) { this.AddGroupBy(s); } } public virtual void AddJoin(string secondTable, string firstTableColumn, string secondTableColumn, JoinType type) { this._join = String.Format(" {0} {1} ON {2}.{3} = {4}.{5} ", this.GetJoinType(type), QueryHelper.GetPreDelimeter(this.type) + secondTable + QueryHelper.GetPostDelimeter(this.type), QueryHelper.GetPreDelimeter(this.type) + this._table + QueryHelper.GetPostDelimeter(this.type), QueryHelper.GetPreDelimeter(this.type) + firstTableColumn + QueryHelper.GetPostDelimeter(this.type), QueryHelper.GetPreDelimeter(this.type) + secondTable + QueryHelper.GetPostDelimeter(this.type), QueryHelper.GetPreDelimeter(this.type) + secondTableColumn + QueryHelper.GetPostDelimeter(this.type)); } public void SetTable(string tableName) { this._table = QueryHelper.GetPreDelimeter(this.type) + tableName + QueryHelper.GetPostDelimeter(this.type); } public virtual string GetText() { return "SELECT " + this.GetLimit() + this.GetColumns() + " FROM " + this._table + this._join + this.GetCriteria() + this.GetOrderBy() + this.GetGroupBy(); } /// <summary> /// The DbProviderType for this query. Necessary to determine how to /// represent dates, parameters, etc. /// </summary> public DbProviderType DbProviderType { get { return this.provider; } set { this.provider = value; } } public OrderBy OrderBy { get { return this.ob; } set { this.ob = value; } } public void SetLimit(int maxRecords) { this.maxRecords = maxRecords; } public ICriteria CreateCriteria() { return CriteriaFactory.CreateCriteria(this.type); } protected string GetColumns() { return StringUtil.RemoveFinalComma(this.sb.ToString()); } protected virtual string GetOrderBy() { StringBuilder sbo = new StringBuilder(); if (order.Count > 0) { sbo.Append(" ORDER BY "); IEnumerator enumerator = order.GetEnumerator(); while (enumerator.MoveNext()) { sbo.Append(enumerator.Current + ", "); } string s = StringUtil.RemoveFinalComma(sbo.ToString()); s += this.TranslateOrderBy(); return s; } return ""; } protected virtual string GetGroupBy() { StringBuilder sbo = new StringBuilder(); if (group.Count > 0) { sbo.Append(" GROUP BY "); IEnumerator enumerator = group.GetEnumerator(); while (enumerator.MoveNext()) { sbo.Append(enumerator.Current + ", "); } return StringUtil.RemoveFinalComma(sbo.ToString()); } return ""; } protected virtual string GetLimit() { if (this.maxRecords > 0) { return " TOP " + this.maxRecords; } return ""; } protected string GetCriteria() { if (this.criteria == null) return ""; else return criteria.GetText(); } protected string GetJoinType(JoinType type) { switch (type) { case JoinType.INNER: return "INNER JOIN"; case JoinType.LEFT: return "LEFT OUTER JOIN"; case JoinType.RIGHT: return "RIGHT OUTER JOIN"; default: throw new Exception("JoinType " + type + " not supported."); } } protected virtual string TranslateOrderBy() { if (this.ob == OrderBy.DESCENDING) { return " DESC "; } else { return " ASC "; } } } } --- NEW FILE: QueryFactory.cs --- namespace Adapdev.Data.Sql { using System; /// <summary> /// Creates datastore specific query implementations /// </summary> public class QueryFactory { public QueryFactory() { } public static IUpdateQuery CreateUpdateQuery(string db) { return CreateUpdateQuery(DbTypeConverter.Convert(db)); } public static IUpdateQuery CreateUpdateQuery(string db, DbProviderType provider) { IUpdateQuery query = QueryFactory.CreateUpdateQuery(db); query.DbProviderType = provider; return query; } public static IUpdateQuery CreateUpdateQuery(DbType db) { switch (db) { case DbType.ACCESS: return new AccessUpdateQuery(); case DbType.SQLSERVER: return new SqlUpdateQuery(); case DbType.ORACLE: return new OracleUpdateQuery(); case DbType.MYSQL: return new MySqlUpdateQuery(); default: throw new System.NotImplementedException("DbType " + db + " not supported currently."); } } public static IUpdateQuery CreateUpdateQuery(DbType db, DbProviderType provider) { IUpdateQuery query = QueryFactory.CreateUpdateQuery(db); query.DbProviderType = provider; return query; } public static ISelectQuery CreateSelectQuery(string db) { return CreateSelectQuery(DbTypeConverter.Convert(db)); } public static ISelectQuery CreateSelectQuery(DbType db) { switch (db) { case DbType.ACCESS: return new AccessSelectQuery(); case DbType.SQLSERVER: return new SqlSelectQuery(); case DbType.ORACLE: return new OracleSelectQuery(); case DbType.MYSQL: return new MySqlSelectQuery(); default: throw new System.NotImplementedException("DbType " + db + " not supported currently."); } } public static ISelectQuery CreateSelectQuery(DbType db, DbProviderType provider) { ISelectQuery query = QueryFactory.CreateSelectQuery(db); query.DbProviderType = provider; return query; } public static IDeleteQuery CreateDeleteQuery(string db) { return CreateDeleteQuery(DbTypeConverter.Convert(db)); } public static IDeleteQuery CreateDeleteQuery(string db, DbProviderType provider) { IDeleteQuery query = QueryFactory.CreateDeleteQuery(db); query.DbProviderType = provider; return query; } public static IDeleteQuery CreateDeleteQuery(DbType db) { switch (db) { case DbType.ACCESS: return new AccessDeleteQuery(); case DbType.SQLSERVER: return new SqlDeleteQuery(); case DbType.ORACLE: return new OracleDeleteQuery(); case DbType.MYSQL: return new MySqlDeleteQuery(); default: throw new System.NotImplementedException("DbType " + db + " not supported currently."); } } public static IDeleteQuery CreateDeleteQuery(DbType db, DbProviderType provider) { IDeleteQuery query = QueryFactory.CreateDeleteQuery(db); query.DbProviderType = provider; return query; } public static IInsertQuery CreateInsertQuery(string db) { return CreateInsertQuery(DbTypeConverter.Convert(db)); } public static IInsertQuery CreateInsertQuery(string db, DbProviderType provider) { IInsertQuery query = QueryFactory.CreateInsertQuery(db); query.DbProviderType = provider; return query; } public static IInsertQuery CreateInsertQuery(DbType db) { switch (db) { case DbType.ACCESS: return new AccessInsertQuery(); case DbType.SQLSERVER: return new SqlInsertQuery(); case DbType.ORACLE: return new OracleInsertQuery(); case DbType.MYSQL: return new MySqlInsertQuery(); default: throw new System.NotImplementedException("DbType " + db + " not supported currently."); } } public static IInsertQuery CreateInsertQuery(DbType db, DbProviderType provider) { IInsertQuery query = QueryFactory.CreateInsertQuery(db); query.DbProviderType = provider; return query; } } } --- NEW FILE: MySqlCriteria.cs --- namespace Adapdev.Data.Sql { using System.Collections; using System.Text; using Adapdev.Text; /// <summary> /// Summary description for MySqlCriteria. /// </summary> public class MySqlCriteria : Criteria { public MySqlCriteria() : base(DbType.MYSQL, DbProviderType.MYSQL) { } public MySqlCriteria(string sql) : base(DbType.MYSQL, DbProviderType.MYSQL, sql) { } } } --- NEW FILE: MySqlInsertQuery.cs --- using System; namespace Adapdev.Data.Sql { /// <summary> /// Summary description for MySqlInsertQuery. /// </summary> public class MySqlInsertQuery : InsertQuery { public MySqlInsertQuery():base(DbType.MYSQL, DbProviderType.MYSQL){} public MySqlInsertQuery(string table):base(DbType.MYSQL, DbProviderType.MYSQL, table){} } } --- NEW FILE: AccessInsertQuery.cs --- using System; namespace Adapdev.Data.Sql { /// <summary> /// Summary description for AccessInsertQuery. /// </summary> public class AccessInsertQuery : InsertQuery { public AccessInsertQuery():base(DbType.ACCESS, DbProviderType.OLEDB){} public AccessInsertQuery(string table):base(DbType.ACCESS, DbProviderType.OLEDB, table){} } } --- NEW FILE: Criteria.cs --- namespace Adapdev.Data.Sql { using System.Collections; using System.Text; using Adapdev.Text; /// <summary> /// Summary description for Criteria. /// </summary> public abstract class Criteria : ICriteria { protected StringBuilder sb = new StringBuilder(); protected DbType type = DbType.SQLSERVER; protected DbProviderType provider = DbProviderType.SQLSERVER; public Criteria(DbType type, DbProviderType provider) { this.type = type; this.provider = provider; } public Criteria(DbType type, DbProviderType provider, string sql): this(type, provider) { sql = sql.Replace("WHERE", ""); this.AddSql(sql); } public void AddAnd() { this.AddCriteriaSeparator(CriteriaType.AND); } public virtual void AddAndCriteria(ICriteria c) { this.AddAnd(); sb.Append("("); sb.Append(c.GetText()); sb.Append(") "); } public virtual void AddCriteriaSeparator(CriteriaType ct) { if (ct == CriteriaType.AND) sb.Append(" AND "); else sb.Append(" OR "); } public virtual void AddBetween(string columnName, object value1, object value2) { sb.Append(" "); sb.Append(QueryHelper.GetPreDelimeter(this.type)); sb.Append(columnName); sb.Append(QueryHelper.GetPostDelimeter(this.type)); sb.Append(" BETWEEN "); sb.Append(QueryHelper.DressUp(value1,this.type)); sb.Append(" AND "); sb.Append(QueryHelper.DressUp(value2,this.type)); sb.Append(" "); } public virtual void AddEqualTo(string columnName, object columnValue) { sb.Append(" "); sb.Append(QueryHelper.GetPreDelimeter(this.type)); sb.Append(columnName); sb.Append(QueryHelper.GetPostDelimeter(this.type)); sb.Append(" = "); sb.Append(QueryHelper.DressUp(columnValue,this.type)); sb.Append(" "); } public virtual void AddEqualTo(string tableName, string columnName, object columnValue) { sb.Append(" "); sb.Append(QueryHelper.GetPreDelimeter(this.type)); sb.Append(tableName); sb.Append(QueryHelper.GetPostDelimeter(this.type)); sb.Append("."); sb.Append(QueryHelper.GetPreDelimeter(this.type)); sb.Append(columnName); sb.Append(QueryHelper.GetPostDelimeter(this.type)); sb.Append(" = "); sb.Append(QueryHelper.DressUp(columnValue,this.type)); sb.Append(" "); } public void AddEqualTo(string columnName) { sb.Append(" "); sb.Append(QueryHelper.GetPreDelimeter(this.type)); sb.Append(columnName); sb.Append(QueryHelper.GetPostDelimeter(this.type)); sb.Append(" = "); sb.Append(QueryHelper.GetParameterName(columnName, this.DbProviderType)); sb.Append(" "); } public virtual void AddExists(IQuery subQuery) { } public virtual void AddGreaterThanOrEqualTo(string columnName, object columnValue) { sb.Append(" "); sb.Append(QueryHelper.GetPreDelimeter(this.type)); sb.Append(columnName); sb.Append(QueryHelper.GetPostDelimeter(this.type)); sb.Append(" >= "); sb.Append(QueryHelper.DressUp(columnValue,this.type)); sb.Append(" "); } public virtual void AddGreaterThan(string columnName, object columnValue) { sb.Append(" "); sb.Append(QueryHelper.GetPreDelimeter(this.type)); sb.Append(columnName); sb.Append(QueryHelper.GetPostDelimeter(this.type)); sb.Append(" > "); sb.Append(QueryHelper.DressUp(columnValue,this.type)); sb.Append(" "); } public virtual void AddIn(string columnName, IQuery subQuery) { sb.Append(" IN ("); sb.Append(subQuery.GetText()); sb.Append(") "); } public virtual void AddIn(string columnName, ICollection values) { StringBuilder sbo = new StringBuilder(); sb.Append(columnName); sb.Append(" IN ("); IEnumerator enumerator = values.GetEnumerator(); while (enumerator.MoveNext()) { sbo.Append(QueryHelper.DressUp(enumerator.Current, this.type) + ", "); } sb.Append(StringUtil.RemoveFinalComma(sbo.ToString())); sb.Append(") "); } public virtual void AddIsNull(string columnName) { sb.Append(" "); sb.Append(QueryHelper.GetPreDelimeter(this.type)); sb.Append(columnName); sb.Append(QueryHelper.GetPostDelimeter(this.type)); sb.Append(" IS NULL "); } public virtual void AddLessThanOrEqualTo(string columnName, object columnValue) { sb.Append(" "); sb.Append(QueryHelper.GetPreDelimeter(this.type)); sb.Append(columnName); sb.Append(QueryHelper.GetPostDelimeter(this.type)); sb.Append(" <= "); sb.Append(QueryHelper.DressUp(columnValue,this.type)); sb.Append(" "); } public virtual void AddLessThan(string columnName, object columnValue) { sb.Append(" "); sb.Append(QueryHelper.GetPreDelimeter(this.type)); sb.Append(columnName); sb.Append(QueryHelper.GetPostDelimeter(this.type)); sb.Append(" < "); sb.Append(QueryHelper.DressUp(columnValue,this.type)); sb.Append(" "); } public virtual void AddLike(string columnName, object columnValue) { sb.Append(" "); sb.Append(QueryHelper.GetPreDelimeter(this.type)); sb.Append(columnName); sb.Append(QueryHelper.GetPostDelimeter(this.type)); sb.Append(" LIKE "); sb.Append(QueryHelper.DressUp(columnValue,this.type)); sb.Append(" "); } public virtual void AddNotBetween(string columnName, object value1, object value2) { sb.Append(" "); sb.Append(QueryHelper.GetPreDelimeter(this.type)); sb.Append(columnName); sb.Append(QueryHelper.GetPostDelimeter(this.type)); sb.Append(" NOT BETWEEN "); sb.Append(QueryHelper.DressUp(value1, this.type)); sb.Append(" AND "); sb.Append(QueryHelper.DressUp(value2, this.type)); sb.Append(" "); } public virtual void AddNotEqualTo(string columnName, object columnValue) { sb.Append(" "); sb.Append(QueryHelper.GetPreDelimeter(this.type)); sb.Append(columnName); sb.Append(QueryHelper.GetPostDelimeter(this.type)); sb.Append(" <> "); sb.Append(QueryHelper.DressUp(columnValue,this.type)); sb.Append(" "); } public virtual void AddNotExists(IQuery subQuery) { sb.Append(" EXISTS (" + subQuery.GetText() + ") "); } public virtual void AddNotIn(string columnName, ICollection values) { StringBuilder sbo = new StringBuilder(); sb.Append(" NOT IN ("); IEnumerator enumerator = values.GetEnumerator(); while (enumerator.MoveNext()) { sbo.Append(QueryHelper.DressUp(enumerator.Current, this.type) + ", "); } sb.Append(StringUtil.RemoveFinalComma(sbo.ToString())); sb.Append(")"); } public virtual void AddNotIn(string columnName, IQuery subQuery) { sb.Append(" NOT IN (" + subQuery.GetText() + ") "); } public virtual void AddNotLike(string columnName, object columnValue) { sb.Append(" "); sb.Append(QueryHelper.GetPreDelimeter(this.type)); sb.Append(columnName); sb.Append(QueryHelper.GetPostDelimeter(this.type)); sb.Append(" NOT LIKE "); sb.Append(QueryHelper.DressUp(columnValue,this.type)); sb.Append(" "); } public virtual void AddNotNull(string columnName) { sb.Append(" "); sb.Append(QueryHelper.GetPreDelimeter(this.type)); sb.Append(columnName); sb.Append(QueryHelper.GetPostDelimeter(this.type)); sb.Append(" NOT IS NULL "); } public void AddOr() { this.AddCriteriaSeparator(CriteriaType.OR); } public void AddOrCriteria(ICriteria c) { this.AddOr(); sb.Append("(" + c.GetText() + ")"); } public virtual void AddSql(string sql) { sb.Append(sql); } public virtual string GetText() { if (sb.Length > 2) { return " WHERE " + sb.ToString(); } else { return ""; } } public DbProviderType DbProviderType { get { return this.provider; } set { this.provider = value; } } } public enum CriteriaType { AND, OR } } --- NEW FILE: IQuery.cs --- namespace Adapdev.Data.Sql { using System; /// <summary> /// Represents a query /// </summary> public interface IQuery { /// <summary> /// Sets the criteria to use for the query /// </summary> /// <param name="c"></param> void SetCriteria(ICriteria c); /// <summary> /// Specifies the table to use for the query /// </summary> /// <param name="tableName"></param> void SetTable(string tableName); /// <summary> /// Returns a datastore specific ICriteria implementation /// </summary> /// <returns></returns> ICriteria CreateCriteria(); /// <summary> /// Returns the text form of the query /// </summary> /// <returns></returns> string GetText(); /// <summary> /// The DbProviderType for this query. Necessary to determine how to /// represent dates, parameters, etc. /// </summary> DbProviderType DbProviderType { get; set; } } } --- NEW FILE: AccessSelectQuery.cs --- using System; namespace Adapdev.Data.Sql { /// <summary> /// Summary description for AccessSelectQuery. /// </summary> public class AccessSelectQuery : SelectQuery { public AccessSelectQuery():base(DbType.ACCESS, DbProviderType.OLEDB){} public AccessSelectQuery(string table):base(DbType.ACCESS, DbProviderType.OLEDB, table){} } } --- NEW FILE: QueryConstants.cs --- namespace Adapdev.Data.Sql { /// <summary> /// Summary description for Constants. /// </summary> public class Constants { private Constants() { } public const char SQLSERVER_STRING = '\''; public const char SQLSERVER_DATE = '\''; public const char ACCESS_STRING = '\''; public const char ACCESS_DATE = '#'; public const char ORACLE_STRING = '\''; public const char ORACLE_DATE = '\''; public const char MYSQL_STRING = '\''; public const char MYSQL_DATE = '\''; } } --- NEW FILE: AccessDeleteQuery.cs --- using System; namespace Adapdev.Data.Sql { /// <summary> /// Summary description for AccessDeleteQuery. /// </summary> public class AccessDeleteQuery : DeleteQuery { public AccessDeleteQuery():base(DbType.ACCESS, DbProviderType.OLEDB){} public AccessDeleteQuery(string table):base(DbType.ACCESS, DbProviderType.OLEDB, table){} } } --- NEW FILE: UpdateQuery.cs --- namespace Adapdev.Data.Sql { using System.Text; using Adapdev.Text; /// <summary> /// Summary description for UpdateQuery. /// </summary> public abstract class UpdateQuery : IUpdateQuery { protected string _table = ""; protected StringBuilder sb = new StringBuilder(); protected ICriteria criteria = null; protected DbType type = DbType.SQLSERVER; protected DbProviderType provider = DbProviderType.SQLSERVER; public UpdateQuery(DbType type, DbProviderType provider) { this.type = type; this.provider = provider; } public UpdateQuery(DbType type, DbProviderType provider, string tableName) : this(type, provider) { this.SetTable(tableName); } public void SetCriteria(ICriteria c) { criteria = c; } public void Add(string columnName) { sb.Append(" " + QueryHelper.GetPreDelimeter(this.type) + columnName + QueryHelper.GetPostDelimeter(this.type) + " = " + QueryHelper.GetParameterName(columnName, this.provider) + ","); } public void Add(string columnName, object columnValue) { sb.Append(" " + QueryHelper.GetPreDelimeter(this.type) + columnName + QueryHelper.GetPostDelimeter(this.type) + " = " + QueryHelper.DressUp(columnValue, this.type) + ","); } public void SetTable(string tableName) { this._table = QueryHelper.GetPreDelimeter(this.type) + tableName + QueryHelper.GetPostDelimeter(this.type); } public ICriteria CreateCriteria() { return CriteriaFactory.CreateCriteria(this.type); } public virtual string GetText() { return "UPDATE " + this._table + " SET " + this.GetColumns() + this.GetCriteria(); } protected string GetColumns() { return StringUtil.RemoveFinalComma(this.sb.ToString()); } protected string GetCriteria() { if (this.criteria == null) return ""; else return criteria.GetText(); } public DbProviderType DbProviderType { get { return this.provider; } set { this.provider = value; } } } } --- NEW FILE: MySqlUpdateQuery.cs --- using System; namespace Adapdev.Data.Sql { /// <summary> /// Summary description for MySqlUpdateQuery. /// </summary> public class MySqlUpdateQuery : UpdateQuery { public MySqlUpdateQuery():base(DbType.MYSQL, DbProviderType.MYSQL){} public MySqlUpdateQuery(string table):base(DbType.MYSQL, DbProviderType.MYSQL, table){} } } --- NEW FILE: SqlServerCriteria.cs --- namespace Adapdev.Data.Sql { using System.Collections; using System.Text; using Adapdev.Text; /// <summary> /// Summary description for ICriteria. /// </summary> public class SqlServerCriteria : Criteria { public SqlServerCriteria() : base(DbType.SQLSERVER, DbProviderType.SQLSERVER) { } public SqlServerCriteria(string sql) : base(DbType.SQLSERVER, DbProviderType.SQLSERVER, sql) { } } } --- NEW FILE: IInsertQuery.cs --- namespace Adapdev.Data.Sql { /// <summary> /// Summary description for IInsertQuery. /// </summary> public interface IInsertQuery : INonSelectQuery { /// <summary> /// Adds the columnName to the insert query /// </summary> /// <param name="columnName"></param> /// <remarks>Since no value is passed in, the datastore specific parameter representation /// will be added</remarks> void Add(string columnName); /// <summary> /// Adds the column name and value to the insert query /// </summary> /// <param name="columnName"></param> /// <param name="columnValue"></param> void Add(string columnName, object columnValue); } } --- NEW FILE: IDeleteQuery.cs --- namespace Adapdev.Data.Sql { /// <summary> /// Summary description for IDeleteQuery. /// </summary> public interface IDeleteQuery : INonSelectQuery { } } --- NEW FILE: MySqlDeleteQuery.cs --- using System; namespace Adapdev.Data.Sql { /// <summary> /// Summary description for MySqlDeleteQuery. /// </summary> public class MySqlDeleteQuery : DeleteQuery { public MySqlDeleteQuery():base(DbType.MYSQL, DbProviderType.MYSQL){} public MySqlDeleteQuery(string table):base(DbType.MYSQL, DbProviderType.MYSQL, table){} } } --- NEW FILE: DialectConstants.cs --- namespace Adapdev.Data.Sql { /// <summary> /// Summary description for DialectConstants. /// </summary> public class DialectConstants { public const char ACCESS_PREDELIM = '['; public const char ACCESS_POSTDELIM = ']'; public const char ACCESS_DATE = '#'; public const char ACCESS_STRING = '\''; public const char SQLSERVER_PREDELIM = '['; public const char SQLSERVER_POSTDELIM = ']'; public const char SQLSERVER_DATE = '\''; public const char SQLSERVER_STRING = '\''; public const char ORACLE_PREDELIM = ' '; public const char ORACLE_POSTDELIM = ' '; public const char ORACLE_DATE = '\''; public const char ORACLE_STRING = '\''; public const char MYSQL_PREDELIM = '`'; public const char MYSQL_POSTDELIM = '`'; public const char MYSQL_DATE = '\''; public const char MYSQL_STRING = '\''; } } --- NEW FILE: OracleInsertQuery.cs --- namespace Adapdev.Data.Sql { /// <summary> /// Summary description for SqlInsertQuery. /// </summary> public class OracleInsertQuery : InsertQuery { public OracleInsertQuery() : base(DbType.ORACLE, DbProviderType.ORACLE) { } public OracleInsertQuery(string tableName) : base(DbType.ORACLE, DbProviderType.ORACLE, tableName) { } } } --- NEW FILE: OracleSelectQuery.cs --- namespace Adapdev.Data.Sql { public class OracleSelectQuery : SelectQuery { public OracleSelectQuery() : base(DbType.ORACLE, DbProviderType.ORACLE) { } public OracleSelectQuery(string tableName) : base(DbType.ORACLE, DbProviderType.ORACLE, tableName) { } protected override string GetLimit() { if(this.maxRecords > 0) { return " ROWNUM <= " + this.maxRecords; } return ""; } public override string GetText() { string sql = "SELECT " + this.GetColumns() + " FROM " + this._table + this._join + this.GetCriteria(); if(this.maxRecords > 0) { if(sql.ToLower().IndexOf("where") < 1) sql+= " WHERE "; else sql += " AND "; sql += this.GetLimit(); } sql += this.GetOrderBy() + this.GetGroupBy(); return sql; } } } |
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/Dvsl In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.NVelocity/Dvsl Added Files: Dvsl.cs DvslContext.cs DvslNode.cs DvslNodeContext.cs DvslNodeImpl.cs TransformTool.cs Transformer.cs Log Message: --- NEW FILE: Transformer.cs --- namespace NVelocity.Dvsl { using System; using System.Collections; using System.IO; using System.Xml; using NVelocity.App; using NVelocity.Context; /// <summary> <p> /// Class responsible for actual transformation /// of documents. /// </p> /// <p> /// Note that this class is <em>not</em> threadsafe. /// </p> /// </summary> /// <author> <a href="mailto:ge...@ap...">Geir Magnusson Jr.</a></author> internal class Transformer : TransformTool { /// <summary> /// Instance of VelocityEngine we are currently using. /// This must be reset with a stylesheeet change /// </summary> private VelocityEngine ve = null; /// <summary> /// basic context passed to us - can contain tools /// and such for use. Is protected from change via /// wrapping /// </summary> private IContext baseContext; /// <summary> /// context used during processing. Wraps the baseContext /// </summary> private DVSLNodeContext currentContext; private TemplateHandler templateHandler = null; /// <summary> /// HashMap to hold application values /// </summary> private Hashtable appValue = new Hashtable(); /// <summary> /// Sole public CTOR. We rely on the caller to give us a /// VelocityEngine ready with all macros registered. /// The context is the callers context with all tools and /// style drek. /// </summary> public Transformer(VelocityEngine ve, TemplateHandler th, IContext context, Hashtable applicationValues, bool validate) { this.ve = ve; this.baseContext = context; this.templateHandler = th; appValue = applicationValues; } /// <summary> /// Method that performs the transformation on /// a document /// </summary> /// <param name="reader">XML document char stream</param> /// <param name="writer">Writer to output transformation to</param> internal virtual long Transform(TextReader reader, TextWriter writer) { /* * parse the document */ XmlDocument document = new XmlDocument(); document.Load(reader); return Transform(document, writer); } internal virtual long Transform(XmlDocument dom4jdoc, TextWriter writer) { /* * wrap the document. We do this as we let the dom4j package * decide if we have a match against "/", so we need document * to do that */ DvslNode root = new DvslNodeImpl(dom4jdoc); return Transform(root, writer); } protected internal virtual long Transform(DvslNode root, TextWriter writer) { /* * wrap in a context to keep subsequent documents from * interacting with each other */ currentContext = new DVSLNodeContext(baseContext); long start = (DateTime.Now.Ticks - 621355968000000000)/10000; /* * push 'this' into the context as our TransformTool * and invoke the transformation */ currentContext.Put("context", this); Invoke(root, writer); long end = (DateTime.Now.Ticks - 621355968000000000)/10000; return end - start; } private void Invoke(DvslNode element, TextWriter writer) { String[] arr = new String[] {}; currentContext.PushNode(element); templateHandler.Render(element, currentContext, writer); currentContext.PopNode(); } public virtual Object Get(String key) { return currentContext.Get(key); } public virtual String ApplyTemplates(DvslNode node, String xpath) { /* * get the nodes that was asked for */ IList nodeset = node.SelectNodes(xpath); StringWriter sw = new StringWriter(); for (int i = 0; i < nodeset.Count; i++) { DvslNode n = (DvslNode) nodeset[i]; Invoke(n, sw); } return sw.ToString(); } public virtual String ApplyTemplates(DvslNode node) { StringWriter sw = new StringWriter(); Invoke(node, sw); return sw.ToString(); } public virtual String ApplyTemplates() { return ApplyTemplates(currentContext.PeekNode(), "*|@*|text()|comment()|processing-instruction()"); } public virtual String ApplyTemplates(String path) { DvslNode node = currentContext.PeekNode(); return ApplyTemplates(node, path); } public virtual String Copy() { /* * fakie, for now */ DvslNode node = currentContext.PeekNode(); return node.Copy(); } public virtual Object GetAppValue(Object key) { return appValue[key]; } public virtual Object PutAppValue(Object key, Object value) { return appValue[key] = value; } } } --- NEW FILE: DvslNodeContext.cs --- namespace NVelocity.Dvsl { using System; using System.Collections; using NVelocity.Context; /// <summary> <p> /// Context implementation that is the outer context /// during the transformation. Holds the node stack /// and also protects the 'special' context elements /// like 'node' /// </p> /// <p> /// There are special elements like 'node', which is /// readonly and corresponds to the current node, and /// 'attrib', which corresponds to a map of attributes /// for the current node. /// </p> /// </summary> /// <author> <a href="mailto:ge...@ap...">Geir Magnusson Jr.</a></author> internal class DVSLNodeContext : VelocityContext { /// <summary> /// Magic context entity that corresponds /// to the current node /// </summary> private const String NODE = "node"; /// <summary> /// Magic context entity that corresponds to /// a Map of attributes for the current node /// </summary> private const String ATTRIB = "attrib"; /// <summary> /// Used to hold the nodes as we get invoked from /// within the document for applyTemplates() duties /// </summary> private Stack nodeStack = new Stack(); protected internal Hashtable ctx = new Hashtable(); public DVSLNodeContext(IContext context) : base(context) { } public DVSLNodeContext() { } /// <summary> /// retrieves value for key from internal storage /// </summary> /// <param name="key">name of value to get</param> /// <returns>value as object</returns> public override Object InternalGet(String key) { Object o = null; /* * special token : NODE * * returns current node */ if (key.Equals(NODE)) { return PeekNode(); } /* * ATTRIB - returns attribute map */ if (key.Equals(ATTRIB)) { DvslNode n = PeekNode(); return n.AttribMap; } /* * start with local storage */ return ctx[key]; } /// <summary> /// stores the value for key to internal /// storage /// </summary> /// <param name="key">name of value to store /// </param> /// <param name="value">value to store /// </param> /// <returns>previous value of key as Object /// </returns> public override Object InternalPut(String key, Object value) { /* * protect both NODE and ATTRIB for now. We * might want to let people set ATTRIB, but * I suspect not */ if (key.Equals(NODE)) return null; if (key.Equals(ATTRIB)) return null; return ctx[key] = value; } /// <summary> /// determines if there is a value for the /// given key /// </summary> /// <param name="key">name of value to check /// </param> /// <returns>true if non-null value in store /// </returns> public override bool InternalContainsKey(Object key) { return ctx.ContainsKey(key); } /// <summary> /// returns array of keys /// $$$ GMJ todo /// </summary> /// <returns>keys as [] /// </returns> public override Object[] InternalGetKeys() { return null; } /// <summary> /// remove a key/value pair from the internal storage /// </summary> /// <param name="key">name of value to remove</param> /// <returns>value removed</returns> public override Object InternalRemove(Object key) { Object o = ctx[key]; ctx.Remove(key); return o; } /* === routines to manage current node stack === */ internal virtual DvslNode PushNode(DvslNode n) { nodeStack.Push(n); return n; } internal virtual DvslNode PeekNode() { return (DvslNode) nodeStack.Peek(); } internal virtual DvslNode PopNode() { return (DvslNode) nodeStack.Pop(); } internal virtual void ClearNode() { nodeStack.Clear(); return; } } } --- NEW FILE: DvslContext.cs --- namespace NVelocity.Dvsl { using System; using System.Collections; using NVelocity.Context; /// <summary> /// Context implementation that handles wrapping several /// contexts simultaneously. The style context gets /// special treatment, getting checked first. /// </summary> /// <author> <a href="mailto:ge...@ap...">Geir Magnusson Jr.</a></author> internal class DvslContext : VelocityContext { protected internal IContext styleContext = null; protected internal IList contextList = new ArrayList(); /// <summary> /// Used to hold the nodes as we get invoked from /// within the document for applyTemplates() duties /// </summary> private Stack nodeStack = new Stack(); protected internal Hashtable ctx = new Hashtable(); public DvslContext() { } public virtual DvslNode PushNode(DvslNode n) { nodeStack.Push(n); return n; } public virtual DvslNode PeekNode() { return (DvslNode) nodeStack.Peek(); } public virtual DvslNode PopNode() { return (DvslNode) nodeStack.Pop(); } public virtual void ClearNode() { nodeStack.Clear(); return; } public virtual void ClearContexts() { styleContext = null; contextList.Clear(); } public virtual void AddContext(IContext c) { if (c != null) contextList.Add(c); } /// <summary> /// retrieves value for key from internal storage /// </summary> /// <param name="key">name of value to get</param> /// <returns>value as object</returns> public override Object InternalGet(String key) { Object o = null; /* * special tokens */ if (key.Equals("node")) { return PeekNode(); } /* * start with local storage */ o = ctx[key]; if (o != null) return o; /* * if that doesn't work, try style first * then others */ if (styleContext != null) { o = styleContext.Get(key); if (o != null) return o; } for (int i = 0; i < contextList.Count; i++) { IContext c = (IContext) contextList[i]; o = c.Get(key); if (o != null) return o; } return null; } /// <summary> /// stores the value for key to internal storage /// </summary> /// <param name="key">name of value to store</param> /// <param name="value">value to store</param> /// <returns>previous value of key as Object</returns> public override Object InternalPut(String key, Object value) { if (key.Equals("node")) return null; return ctx[key] = value; } /// <summary> /// determines if there is a value for the given key /// </summary> /// <param name="key">name of value to check</param> /// <returns>true if non-null value in store</returns> public override bool InternalContainsKey(Object key) { /* * start with local storage */ if (ctx.ContainsKey(key)) return true; /* * if that doesn't work, try style first * then others */ if (styleContext != null && styleContext.ContainsKey(key)) return true; for (int i = 0; i < contextList.Count; i++) { IContext c = (IContext) contextList[i]; if (c.ContainsKey(key)) return true; } return false; } /// <summary> /// returns array of keys /// /// $$$ GMJ todo /// /// </summary> /// <returns>keys as []</returns> public override Object[] InternalGetKeys() { return null; } /// <summary> /// remove a key/value pair from the /// internal storage /// </summary> /// <param name="key">name of value to remove</param> /// <returns>value removed</returns> public override Object InternalRemove(Object key) { Object o = ctx[key]; ctx.Remove(key); return o; } public virtual IContext StyleContext { set { styleContext = value; } } } } --- NEW FILE: TransformTool.cs --- namespace NVelocity.Dvsl { using System; /// <summary> /// This is the tool interface exposed to the stylesheet. /// </summary> /// <author> <a href="mailto:ge...@ap...">Geir Magnusson Jr.</a></author> public interface TransformTool { /// <summary> /// Applies templates in the current stylesheet /// to the nodeset returned by the XPath expression /// </summary> /// <param name="xpath">XPath expression to select nodes</param> /// <returns>The rendered result</returns> String ApplyTemplates(String xpath); String ApplyTemplates(DvslNode node); String ApplyTemplates(DvslNode node, String xpath); String ApplyTemplates(); String Copy(); Object Get(String key); Object GetAppValue(Object key); Object PutAppValue(Object key, Object value); } } --- NEW FILE: Dvsl.cs --- namespace NVelocity.Dvsl { using System; using System.Collections; using System.IO; using System.Xml; using Commons.Collections; using NVelocity.App; using NVelocity.Context; using NVelocity.Runtime; /// <summary> /// Main DVSL class - use this as the helper class for apps /// </summary> /// <author> <a href="mailto:ge...@ap...">Geir Magnusson Jr.</a></author> /// <author> <a href="mailto:bi...@pr...">Bill Burton.</a></author> public class Dvsl { private static String TOOL_PROP_PREFIX = "toolbox.tool."; private static String STRING_PROP_PREFIX = "toolbox.string."; private static String INTEGER_PROP_PREFIX = "toolbox.integer."; private static String TOOLBOX_NAME = "toolbox.contextname."; private VelocityEngine ve = null; private XmlDocument currentDocument = null; private StreamWriter currentWriter = null; private IContext toolContext; private IContext userContext; private IContext styleContext; private DvslContext baseContext = new DvslContext(); private Transformer transformer; private bool ready = false; private Hashtable velConfig = null; private FileInfo logFile; private Hashtable appVals = new Hashtable(); private TemplateHandler templateHandler = new TemplateHandler(); internal bool validate = false; /// <summary> /// lets the user specify a filename for logging. /// </summary> public virtual FileInfo LogFile { set { this.logFile = value; if (velConfig == null) { velConfig = new Hashtable(); } velConfig[RuntimeConstants_Fields.RUNTIME_LOG] = value.FullName; } } /// <summary> /// lets the user pass a java.util.Properties containing /// properties for the configuration of the VelocityEngine /// used by DVSL /// </summary> public virtual Hashtable VelocityConfig { set { if (velConfig != null) { foreach (Object key in velConfig.Keys) { value.Add(key, velConfig[key]); } } velConfig = value; } } /// <summary> /// Sets the user context. The user context is /// a Velocity Context containing user-supplied /// objects and data that are to be made available /// in the template /// </summary> /// <param name="ctx">User context of data</param> public virtual IContext UserContext { set { ready = false; userContext = value; } } /// <summary> /// Uses a validating parser on all input documents /// </summary> /// <param name="">validate</param> public virtual bool ValidatingParser { set { validate = value; } } /// <summary> /// <p>Loads the toolbox from the input Properties.</p> /// <p>Currently supports specification of the Toolbox /// name in the context, creating classes, and string /// and integer values. Ex : /// </p> /// /// <pre> /// toolbox.contextname = floyd /// toolbox.tool.footool = Footool /// toolbox.string.mystring = Hello there! /// toolbox.integer.myint = 7 /// toolbox.string.sourcebase = ./xdocs/ /// </pre> /// /// <p> /// So in template, this toolbox and it's values would /// be accessed as : /// </p> /// <pre> /// $context.floyd.footool.getFoo() /// $context.floyd.mystring /// $context.floyd.myint /// </pre> /// </summary> public virtual ExtendedProperties Toolbox { set { ready = false; /* * for each key that looks like * toolbox.tool.<token> = class */ Hashtable toolbox = new Hashtable(); String toolboxname = "toolbox"; IEnumerator it = value.Keys; while (it.MoveNext()) { String key = it.Current.ToString(); String val = value.GetString(key); if (key.StartsWith(TOOL_PROP_PREFIX)) { String toolname = key.Substring(TOOL_PROP_PREFIX.Length); Type type = Type.GetType(val); Object o = Activator.CreateInstance(type); toolbox[toolname] = o; } else if (key.StartsWith(INTEGER_PROP_PREFIX)) { String toolname = key.Substring(INTEGER_PROP_PREFIX.Length); int i = 0; try { i = Int32.Parse(val); } catch (Exception ee) { } toolbox[toolname] = i; } else if (key.StartsWith(STRING_PROP_PREFIX)) { String toolname = key.Substring(STRING_PROP_PREFIX.Length); toolbox[toolname] = val; } else if (key.StartsWith(TOOLBOX_NAME)) { toolboxname = val; } } toolContext = new VelocityContext(); toolContext.Put(toolboxname, toolbox); } } /// <summary> /// Convenience function. See... /// </summary> public virtual void SetStylesheet(String value) { SetStylesheet(new FileInfo(value)); } /// <summary> /// Convenience function. See... /// </summary> public virtual void SetStylesheet(FileInfo value) { StreamReader fr = null; try { fr = new StreamReader(value.FullName); SetStylesheet(fr); } catch (Exception e) { throw; } finally { if (fr != null) { fr.Close(); } } } /// <summary> /// <p> /// Sets the stylesheet for this transformation set /// </p> /// /// <p> /// Note that don't need this for each document you want /// to transform. Just do it once, and transform away... /// </p> /// </summary> /// <param name="styleReader">Reader with stylesheet char stream</param> public virtual void SetStylesheet(TextReader value) { ready = false; /* * now initialize Velocity - we need to do that * on change of stylesheet */ ve = new VelocityEngine(); /* * if there are user properties, set those first - carefully */ if (velConfig != null) { ConfigureVelocityEngine(ve, velConfig); } /* * register our template() directive */ ve.SetProperty("userdirective", "NVelocity.Dvsl.Directive.MatchDirective;NVelocity"); ve.Init(); /* * add our template accumulator */ ve.SetApplicationAttribute("NVelocity.Dvsl.TemplateHandler", templateHandler); /* * load and render the stylesheet * * this sets stylesheet specific context * values */ StringWriter junkWriter = new StringWriter(); styleContext = new VelocityContext(); ve.Evaluate(styleContext, junkWriter, "DVSL:stylesheet", value); /* * now run the base template through for the rules */ // TODO - use ResourceLocator or something else - I don't like the path to the resource Stream s = this.GetType().Assembly.GetManifestResourceStream("NVelocity.Dvsl.Resource.defaultroot.dvsl"); if (s == null) { Console.Out.WriteLine("DEFAULT TRANSFORM RULES NOT FOUND "); } else { ve.Evaluate(new VelocityContext(), junkWriter, "defaultroot.dvsl", new StreamReader(s)); s.Close(); } /* * need a new transformer, as it depends on the * velocity engine */ transformer = new Transformer(ve, templateHandler, baseContext, appVals, validate); } /// <summary> /// <p> /// Add mapped properties from hashtable on VelocityEngine. /// </p> /// <p> /// If you are going to use this, ensure you do it *before* setting /// the stylesheet, as that creates the VelocityEngine /// </p> /// </summary> private void ConfigureVelocityEngine(VelocityEngine ve, Hashtable map) { if (ve == null || map == null) { return; } foreach (DictionaryEntry entry in map) { ve.SetProperty((String) entry.Key, entry.Value); } } /// <summary> /// sets up all the context goodies /// </summary> protected internal virtual void MakeReady() { /* * put all the contexts together */ baseContext.ClearContexts(); baseContext.AddContext(userContext); baseContext.AddContext(toolContext); baseContext.StyleContext = styleContext; ready = true; } /// <summary> /// does the transformation of the inputstream into /// the output writer /// </summary> protected internal virtual long XForm(TextReader reader, TextWriter writer) { if (!ready) { MakeReady(); } return transformer.Transform(reader, writer); } protected internal virtual long XForm(XmlDocument dom4jdoc, TextWriter writer) { if (!ready) { MakeReady(); } return transformer.Transform(dom4jdoc, writer); } public virtual long Transform(FileInfo f, TextWriter writer) { StreamReader reader = null; try { reader = new StreamReader(f.FullName); return XForm(reader, writer); } catch (Exception e) { throw e; } finally { if (reader != null) { reader.Close(); } } } public virtual long Transform(TextReader reader, TextWriter writer) { return XForm(reader, writer); } public virtual long Transform(Stream stream, TextWriter writer) { return XForm(new StreamReader(stream), writer); } /// <summary> /// Transforms the given dom4j Document into the writer. /// </summary> /// <param name="dom4jdoc">dom4j Document object</param> /// <param name="writer">Writer for output</param> public virtual long Transform(XmlDocument dom4jdoc, TextWriter writer) { return XForm(dom4jdoc, writer); } public virtual long Transform(String infile, TextWriter writer) { StreamReader reader = null; try { reader = new StreamReader(infile); return XForm(reader, writer); } catch (Exception e) { throw e; } finally { if (reader != null) { reader.Close(); } } } /// <summary> /// Gets the application value for the specified key /// </summary> /// <param name="key">key to use to retrieve value</param> /// <returns>value if found, null otherwise</returns> public virtual Object GetAppValue(Object key) { return appVals[key]; } /// <summary> /// Sets the application value for the specified key /// </summary> /// <param name="key">key to use to store value</param> /// <param name="value">value to be stored</param> /// <returns>old value if any, null otherwise</returns> public virtual Object PutAppValue(Object key, Object value) { return appVals[key] = value; } /// <summary> /// <p> /// Allows command-line access. /// </p> /// <p> /// Usage : Dvsl.exe -STYLE stylesheeet [-IN infile] [-OUT outfile] [-TOOL toolboxname] /// </p> /// </summary> [STAThread] public static void Main(String[] args) { Dvsl dvsl = new Dvsl(); TextReader reader = Console.In; String infile = null; String style = null; String outfile = null; TextWriter writer = Console.Out; String toolfile = null; for (int i = 0; i < args.Length; i++) { if (args[i].Equals("-IN")) infile = args[++i]; else if (args[i].Equals("-OUT")) outfile = args[++i]; else if (args[i].Equals("-STYLE")) style = args[++i]; else if (args[i].Equals("-TOOL")) toolfile = args[++i]; } if (style == null) { Console.Out.WriteLine("usage :need to specify a stylesheet. "); Console.Out.WriteLine("Dvsl.exe -STYLE stylesheeet [-IN infile] [-OUT outfile] [-TOOL toolboxname]"); return; } if (style != null) dvsl.SetStylesheet(style); if (toolfile != null) { ExtendedProperties p = new ExtendedProperties(); Stream fis = new FileStream(toolfile, FileMode.Open, FileAccess.Read); p.Load(fis); dvsl.Toolbox = p; } if (infile != null) reader = new StreamReader(infile); if (outfile != null) writer = new StreamWriter(outfile); long time = dvsl.Transform(reader, writer); writer.Flush(); } } } --- NEW FILE: DvslNodeImpl.cs --- namespace NVelocity.Dvsl { using System; using System.Collections; using System.IO; using System.Xml; /// <summary> /// wrapper class for .Net nodes to implement the /// DVSLNode interface for template use /// </summary> /// <author> <a href="mailto:ge...@ap...">Geir Magnusson Jr.</a></author> public class DvslNodeImpl : DvslNode { protected internal XmlNode element = null; protected internal Hashtable attributes = null; /// <summary> /// this is a bit yecchy - need to revamp /// </summary> public DvslNodeImpl(XmlElement e) { element = e; } public DvslNodeImpl(XmlDocument e) { element = e; } public DvslNodeImpl(XmlText e) { element = e; } public DvslNodeImpl(XmlAttribute e) { element = e; } public DvslNodeImpl(XmlComment e) { element = e; } public DvslNodeImpl(XmlCDataSection e) { element = e; } public DvslNodeImpl() { } public virtual Object NodeImpl { get { return element; } } public virtual Hashtable AttribMap { get { /* * $$$ GMJ sync issue? yes. Do I care? */ if (attributes == null) { attributes = new Hashtable(); } /* * only Elements have attributes */ if (element is XmlElement) { XmlElement e = (XmlElement) element; foreach (XmlAttribute at in e.Attributes) { attributes[at.Name] = at.Value; } } return attributes; } } /// <summary> /// returns the name of the node /// </summary> public virtual String Name { get { return element.Name; } } /// <summary> /// returns a specificed attributeattribute /// </summary> public virtual String Attribute(String attribute) { if (element is XmlElement) { return ((XmlElement) element).Attributes[attribute].Value; } return null; } /// <summary> /// returns a list of nodes that satisfy the xpath /// </summary> public virtual IList SelectNodes(String xpath) { XmlNodeList l = element.SelectNodes(xpath); IList list = new ArrayList(); for (int i = 0; i < l.Count; i++) { XmlNode n = l[i]; if (n != null) { DvslNode dn = MakeDvslNode(n); if (dn != null) { list.Add(dn); } } } return list; } public virtual DvslNode SelectSingleNode(String xpath) { XmlNode n = element.SelectSingleNode(xpath); return MakeDvslNode(n); } public virtual DvslNode Get(String xpath) { return SelectSingleNode(xpath); } public virtual String Value { get { return element.InnerText; } } public virtual Object ValueOf(String xpath) { Object o = element.CreateNavigator().Evaluate(xpath); return o; } public override String ToString() { return Value; } public virtual IList Children() { IList list = new ArrayList(); if (element.NodeType == XmlNodeType.Element) { XmlNodeList nodes = ((XmlElement) element).ChildNodes; for (int i = 0; i < nodes.Count; i++) list.Add(MakeDvslNode(nodes[i])); } return list; } /// <summary> /// assumes a list of DVSLNodes /// </summary> public virtual String Copy(IList nodes) { if (nodes == null) return ""; StringWriter sw = new StringWriter(); for (int i = 0; i < nodes.Count; i++) { DvslNode dn = (DvslNode) nodes[i]; sw.Write(((XmlNode) dn.NodeImpl).OuterXml); } return sw.ToString(); } public virtual String Copy() { return element.OuterXml; } public virtual String Render() { try { StringWriter sw = new StringWriter(); XmlTextWriter tw = new XmlTextWriter(sw); element.WriteContentTo(tw); return tw.ToString(); } catch (Exception e) { } return ""; } public virtual String Attrib(String name) { if (element is XmlElement) { XmlAttribute attrib = ((XmlElement) element).Attributes[name]; if (attrib != null) { return attrib.Value; } } return null; } /// <summary> /// will recast all of this later /// </summary> private DvslNode MakeDvslNode(XmlNode n) { if (n == null) { return null; } if (n.NodeType == XmlNodeType.Element) { return new DvslNodeImpl((XmlElement) n); } else if (n.NodeType == XmlNodeType.Text) { return new DvslNodeImpl((XmlText) n); } else if (n.NodeType == XmlNodeType.Attribute) { return new DvslNodeImpl((XmlAttribute) n); } else if (n.NodeType == XmlNodeType.Comment) { return new DvslNodeImpl((XmlComment) n); } else if (n.NodeType == XmlNodeType.CDATA) { return new DvslNodeImpl((XmlCDataSection) n); } else if (n.NodeType == XmlNodeType.ProcessingInstruction) { // not a supported node type return null; } //TODO: log the unknown node type so that it can be determined is something is missing return null; } } } --- NEW FILE: DvslNode.cs --- namespace NVelocity.Dvsl { using System; using System.Collections; /// <summary> /// wrapper interface for nodes exposed in the /// template. Isolates the in-VSL DOM from that /// of the underlying implementation /// </summary> /// <author> <a href="mailto:ge...@ap...">Geir Magnusson Jr.</a></author> public interface DvslNode { /// <summary> /// returns the name of the node /// </summary> String Name { get; } /// <summary> /// returns the 'value' of the node /// </summary> String Value { get; } /// <summary> /// returns the value of the XPath /// expression /// </summary> Object ValueOf(String xpath); /// <summary> /// returns attribute /// </summary> String Attrib(String attribute); /// <summary> /// returns a list of nodes that satisfy /// the xpath /// </summary> IList SelectNodes(String xpath); /// <summary> returns a single node that satisfies /// the xpath /// </summary> DvslNode SelectSingleNode(String xpath); DvslNode Get(String xpath); /// <summary> /// renders a deep copy of the XML tree /// below the current node to the output /// </summary> String Copy(); /// <summary> /// renders a deep copy of the nodes in /// the list ot the output /// </summary> String Copy(IList nodeList); /// <summary> /// returns a list of all children of the current node /// </summary> IList Children(); /// <summary> /// returns the 'value' of the node /// </summary> String ToString(); /// <summary> /// returns the object corresponding to the node /// in the implementaion that we are using. /// use only with the greatest of care /// </summary> Object NodeImpl { get; } Hashtable AttribMap { get; } } } |
From: Sean M. <int...@us...> - 2005-11-16 07:01:58
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/App/Tools In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.NVelocity/App/Tools Added Files: VelocityFormatter.cs Log Message: --- NEW FILE: VelocityFormatter.cs --- namespace NVelocity.App.Tools { /* * Copyright (c) 2001 The Java Apache Project. 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. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the Java Apache * Project for use in the Apache JServ servlet engine project * <http://java.apache.org/>." * * 4. The names "Apache JServ", "Apache JServ Servlet Engine", "Turbine", * "Apache Turbine", "Turbine Project", "Apache Turbine Project" and * "Java Apache Project" must not be used to endorse or promote products * derived from this software without prior written permission. * * 5. Products derived from this software may not be called "Apache JServ" * nor may "Apache" nor "Apache JServ" appear in their names without * prior written permission of the Java Apache Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the Java Apache * Project for use in the Apache JServ servlet engine project * <http://java.apache.org/>." * * THIS SOFTWARE IS PROVIDED BY THE JAVA APACHE PROJECT "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 JAVA APACHE PROJECT 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 Java Apache Group. For more information * on the Java Apache Project and the Apache JServ Servlet Engine project, * please see <http://java.apache.org/>. * */ // Java Core Classes using System; using System.Collections; using System.Globalization; using System.Text; using NVelocity.Context; /// <summary> Formatting tool for inserting into the Velocity WebContext. Can /// format dates or lists of objects. /// * /// <p>Here's an example of some uses: /// * /// <code><pre> /// $formatter.formatShortDate($object.Date) /// $formatter.formatLongDate($db.getRecord(232).getDate()) /// $formatter.formatArray($array) /// $formatter.limitLen(30, $object.Description) /// </pre></code> /// /// </summary> /// <author> <a href="se...@so...">Sean Legassick</a> /// </author> /// <author> <a href="dl...@co...">Daniel Rall</a> /// </author> /// <version> $Id: VelocityFormatter.cs,v 1.5 2005/11/16 07:01:48 intesar66 Exp $ /// /// </version> public class VelocityFormatter { private void InitBlock() { nf = SupportClass.TextNumberFormat.getTextNumberInstance(); } internal IContext context = null; //UPGRADE_NOTE: The initialization of 'nf' was moved to method 'InitBlock'. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1005"' internal SupportClass.TextNumberFormat nf; /// <summary> Constructor needs a backpointer to the context. /// * /// </summary> /// <param name="context">A Context. /// /// </param> public VelocityFormatter(IContext context) { InitBlock(); this.context = context; } /// <summary> Formats a date in 'short' style. /// * /// </summary> /// <param name="date">A Date. /// </param> /// <returns>A String. /// /// </returns> public virtual String formatShortDate(DateTime date) { return SupportClass.FormatDateTime(SupportClass.GetDateTimeFormatInstance(3, -1, CultureInfo.CurrentCulture), date); } /// <summary> Formats a date in 'long' style. /// * /// </summary> /// <param name="date">A Date. /// </param> /// <returns>A String. /// /// </returns> public virtual String formatLongDate(DateTime date) { return SupportClass.FormatDateTime(SupportClass.GetDateTimeFormatInstance(1, -1, CultureInfo.CurrentCulture), date); } /// <summary> Formats a date/time in 'short' style. /// * /// </summary> /// <param name="date">A Date. /// </param> /// <returns>A String. /// /// </returns> public virtual String formatShortDateTime(DateTime date) { return SupportClass.FormatDateTime(SupportClass.GetDateTimeFormatInstance(3, 3, CultureInfo.CurrentCulture), date); } /// <summary> Formats a date/time in 'long' style. /// * /// </summary> /// <param name="date">A Date. /// </param> /// <returns>A String. /// /// </returns> public virtual String formatLongDateTime(DateTime date) { return SupportClass.FormatDateTime(SupportClass.GetDateTimeFormatInstance(1, 1, CultureInfo.CurrentCulture), date); } /// <summary> Formats an array into the form "A, B and C". /// * /// </summary> /// <param name="array">An Object. /// </param> /// <returns>A String. /// /// </returns> public virtual String formatArray(Object array) { return formatArray(array, ", ", " and "); } /// <summary> Formats an array into the form /// "A<delim>B<delim>C". /// * /// </summary> /// <param name="array">An Object. /// </param> /// <param name="delim">A String. /// </param> /// <returns>A String. /// /// </returns> public virtual String formatArray(Object array, String delim) { return formatArray(array, delim, delim); } /// <summary> Formats an array into the form /// "A<delim>B<finaldelim>C". /// * /// </summary> /// <param name="array">An Object. /// </param> /// <param name="delim">A String. /// </param> /// <param name="finalDelim">A String. /// </param> /// <returns>A String. /// /// </returns> public virtual String formatArray(Object array, String delim, String finaldelim) { // TODO: if this is not right - it will blow up Array a = (Array) array; StringBuilder sb = new StringBuilder(); int arrayLen = ((double[]) array).Length; for (int i = 0; i < arrayLen; i++) { // Use the Array.get method as this will automatically // wrap primitive types in a suitable Object-derived // wrapper if necessary. //UPGRADE_TODO: The equivalent in .NET for method 'java.Object.toString' may return a different value. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1043"' //UPGRADE_ISSUE: Method 'java.lang.reflect.Array.get' was not converted. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1000_javalangreflectArrayget_javalangObject_int"' //TODO: not sure if this is right //sb.Append(Array.get(array, i).ToString()); sb.Append(a.GetValue(i).ToString()); if (i < arrayLen - 2) { sb.Append(delim); } else if (i < arrayLen - 1) { sb.Append(finaldelim); } } return sb.ToString(); } /// <summary> Formats a vector into the form "A, B and C". /// * /// </summary> /// <param name="vector">A Vector. /// </param> /// <returns>A String. /// /// </returns> public virtual String formatVector(ArrayList vector) { return formatVector(vector, ", ", " and "); } /// <summary> Formats a vector into the form "A<delim>B<delim>C". /// * /// </summary> /// <param name="vector">A Vector. /// </param> /// <param name="delim">A String. /// </param> /// <returns>A String. /// /// </returns> public virtual String formatVector(ArrayList vector, String delim) { return formatVector(vector, delim, delim); } /// <summary> Formats a vector into the form /// "Adelim>B<finaldelim>C". /// * /// </summary> /// <param name="vector">A Vector. /// </param> /// <param name="delim">A String. /// </param> /// <param name="finalDelim">A String. /// </param> /// <returns>A String. /// /// </returns> public virtual String formatVector(ArrayList vector, String delim, String finaldelim) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < vector.Count; i++) { //UPGRADE_TODO: The equivalent in .NET for method 'java.Object.toString' may return a different value. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1043"' sb.Append(vector[i].ToString()); if (i < vector.Count - 2) { sb.Append(delim); } else if (i < vector.Count - 1) { sb.Append(finaldelim); } } return sb.ToString(); } /// <summary> Limits 'string' to 'maxlen' characters. If the string gets /// curtailed, "..." is appended to it. /// * /// </summary> /// <param name="maxlen">An int with the maximum length. /// </param> /// <param name="string">A String. /// </param> /// <returns>A String. /// /// </returns> public virtual String limitLen(int maxlen, String string_Renamed) { return limitLen(maxlen, string_Renamed, "..."); } /// <summary> Limits 'string' to 'maxlen' character. If the string gets /// curtailed, 'suffix' is appended to it. /// * /// </summary> /// <param name="maxlen">An int with the maximum length. /// </param> /// <param name="string">A String. /// </param> /// <param name="suffix">A String. /// </param> /// <returns>A String. /// /// </returns> public virtual String limitLen(int maxlen, String string_Renamed, String suffix) { String ret = string_Renamed; if (string_Renamed.Length > maxlen) { ret = string_Renamed.Substring(0, (maxlen - suffix.Length) - (0)) + suffix; } return ret; } /// <summary> Class that returns alternating values in a template. It stores /// a list of alternate Strings, whenever alternate() is called it /// switches to the next in the list. The current alternate is /// retrieved through toString() - i.e. just by referencing the /// object in a Velocity template. For an example of usage see the /// makeAlternator() method below. /// </summary> //UPGRADE_NOTE: Field 'EnclosingInstance' was added to class 'VelocityAlternator' to access its enclosing instance. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1019"' public class VelocityAlternator { private void InitBlock(VelocityFormatter enclosingInstance) { this.enclosingInstance = enclosingInstance; } private VelocityFormatter enclosingInstance; public VelocityFormatter Enclosing_Instance { get { return enclosingInstance; } } protected internal String[] alternates = null; protected internal int current = 0; /// <summary> Constructor takes an array of Strings. /// * /// </summary> /// <param name="alternates">A String[]. /// /// </param> public VelocityAlternator(VelocityFormatter enclosingInstance, String[] alternates) { InitBlock(enclosingInstance); this.alternates = alternates; } /// <summary> Alternates to the next in the list. /// * /// </summary> /// <returns>The current alternate in the sequence. /// /// </returns> public virtual String alternate() { current++; current %= alternates.Length; return ""; } /// <summary> Returns the current alternate. /// * /// </summary> /// <returns>A String. /// /// </returns> public override String ToString() { return alternates[current]; } } /// <summary> As VelocityAlternator, but calls <code>alternate()</code> /// automatically on rendering in a template. /// </summary> //UPGRADE_NOTE: Field 'EnclosingInstance' was added to class 'VelocityAutoAlternator' to access its enclosing instance. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1019"' public class VelocityAutoAlternator : VelocityAlternator { private void InitBlock(VelocityFormatter enclosingInstance) { this.enclosingInstance = enclosingInstance; } private VelocityFormatter enclosingInstance; new public VelocityFormatter Enclosing_Instance { get { return enclosingInstance; } } /// <summary> Constructor takes an array of Strings. /// * /// </summary> /// <param name="alternates">A String[]. /// /// </param> public VelocityAutoAlternator(VelocityFormatter enclosingInstance, String[] alternates) : base(enclosingInstance, alternates) { InitBlock(enclosingInstance); } /// <summary> Returns the current alternate, and automatically alternates /// to the next alternate in its sequence (trigged upon /// rendering). /// * /// </summary> /// <returns>The current alternate in the sequence. /// /// </returns> public override String ToString() { String s = alternates[current]; alternate(); return s; } } /// <summary> Makes an alternator object that alternates between two values. /// * /// <p>Example usage in a Velocity template: /// * /// <code><pre> /// <table> /// $formatter.makeAlternator("rowcolor", "#c0c0c0", "#e0e0e0") /// #foreach $item in $items /// #begin /// <tr><td bgcolor="$rowcolor">$item.Name</td></tr> /// $rowcolor.alternate() /// #end /// </table> /// </pre></code> /// * /// </summary> /// <param name="name">The name for the alternator int the context. /// </param> /// <param name="alt1">The first alternate. /// </param> /// <param name="alt2">The second alternate. /// </param> /// <returns>The newly created instance. /// /// </returns> public virtual String makeAlternator(String name, String alt1, String alt2) { String[] alternates = new String[] {alt1, alt2}; context.Put(name, new VelocityAlternator(this, alternates)); return ""; } /// <summary> Makes an alternator object that alternates between three /// values. /// * /// </summary> /// <seealso cref=" #makeAlternator(String name, String alt1, String alt2) /// /// "/> public virtual String makeAlternator(String name, String alt1, String alt2, String alt3) { String[] alternates = new String[] {alt1, alt2, alt3}; context.Put(name, new VelocityAlternator(this, alternates)); return ""; } /// <summary> Makes an alternator object that alternates between four values. /// * /// </summary> /// <seealso cref=" #makeAlternator(String name, String alt1, String alt2) /// /// "/> public virtual String makeAlternator(String name, String alt1, String alt2, String alt3, String alt4) { String[] alternates = new String[] {alt1, alt2, alt3, alt4}; context.Put(name, new VelocityAlternator(this, alternates)); return ""; } /// <summary> Makes an alternator object that alternates between two values /// automatically. /// * /// </summary> /// <seealso cref=" #makeAlternator(String name, String alt1, String alt2) /// /// "/> public virtual String makeAutoAlternator(String name, String alt1, String alt2) { String[] alternates = new String[] {alt1, alt2}; context.Put(name, new VelocityAutoAlternator(this, alternates)); return ""; } /// <summary> Returns a default value if the object passed is null. /// </summary> public virtual Object isNull(Object o, Object dflt) { if (o == null) { return dflt; } else { return o; } } } } |
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/Commons/Collections In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.NVelocity/Commons/Collections Added Files: CollectionsUtil.cs ExtendedProperties.cs PropertiesReader.cs PropertiesTokenizer.cs StringTokenizer.cs Log Message: --- NEW FILE: StringTokenizer.cs --- namespace Commons.Collections { using System; using System.Collections; public class StringTokenizer { private ArrayList elements; private string source; //The tokenizer uses the default delimiter set: the space character, the tab character, the newline character, and the carriage-return character private string delimiters = " \t\n\r"; public StringTokenizer(string source) { this.elements = new ArrayList(); this.elements.AddRange(source.Split(this.delimiters.ToCharArray())); this.RemoveEmptyStrings(); this.source = source; } public StringTokenizer(string source, string delimiters) { this.elements = new ArrayList(); this.delimiters = delimiters; this.elements.AddRange(source.Split(this.delimiters.ToCharArray())); this.RemoveEmptyStrings(); this.source = source; } public int Count { get { return (this.elements.Count); } } public bool HasMoreTokens() { return (this.elements.Count > 0); } public string NextToken() { string result; if (source == "") { throw new Exception(); } else { this.elements = new ArrayList(); this.elements.AddRange(this.source.Split(delimiters.ToCharArray())); RemoveEmptyStrings(); result = (string) this.elements[0]; this.elements.RemoveAt(0); this.source = this.source.Replace(result, ""); this.source = this.source.TrimStart(this.delimiters.ToCharArray()); return result; } } public string NextToken(string delimiters) { this.delimiters = delimiters; return NextToken(); } private void RemoveEmptyStrings() { //VJ++ does not treat empty strings as tokens for (int index = 0; index < this.elements.Count; index++) if ((string) this.elements[index] == "") { this.elements.RemoveAt(index); index--; } } } } --- NEW FILE: PropertiesTokenizer.cs --- namespace Commons.Collections { using System; using System.Text; /// <summary> This class divides into tokens a property value. Token /// separator is "," but commas into the property value are escaped /// using the backslash in front. /// </summary> internal class PropertiesTokenizer : StringTokenizer { /// <summary> The property delimiter used while parsing (a comma). /// </summary> internal const String DELIMITER = ","; /// <summary> Constructor. /// </summary> /// <param name="string">A String. /// </param> public PropertiesTokenizer(String string_Renamed) : base(string_Renamed, DELIMITER) { } /// <summary> Check whether the object has more tokens. /// </summary> /// <returns>True if the object has more tokens. /// </returns> //UPGRADE_TODO: The equivalent of method java.util.StringTokenizer.hasMoreTokens is not an override method. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca5065"' public bool HasMoreTokens() { return base.HasMoreTokens(); } /// <summary> Get next token. /// </summary> /// <returns>A String. /// </returns> //UPGRADE_TODO: The equivalent of method java.util.StringTokenizer.nextToken is not an override method. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca5065"' public String NextToken() { StringBuilder buffer = new StringBuilder(); while (HasMoreTokens()) { String token = base.NextToken(); if (token.EndsWith("\\")) { buffer.Append(token.Substring(0, (token.Length - 1) - (0))); buffer.Append(DELIMITER); } else { buffer.Append(token); break; } } return buffer.ToString().Trim(); } } } --- NEW FILE: CollectionsUtil.cs --- namespace Commons.Collections { using System; using System.Collections; /// <summary> /// Static utility methods for collections /// </summary> public class CollectionsUtil { public static Object PutElement(Hashtable hashTable, Object key, Object newValue) { Object element = hashTable[key]; hashTable[key] = newValue; return element; } } } --- NEW FILE: ExtendedProperties.cs --- namespace Commons.Collections { using System; using System.Collections; using System.IO; using System.Text; /// <summary> This class extends normal Java properties by adding the possibility /// to use the same key many times concatenating the value strings /// instead of overwriting them. /// /// <p>The Extended Properties syntax is explained here: /// /// <ul> /// <li> /// Each property has the syntax <code>key = value</code> /// </li> /// <li> /// The <i>key</i> may use any character but the equal sign '='. [...1664 lines suppressed...] /// </param> /// <returns>ExtendedProperties configuration created from the /// properties object. /// /// </returns> public static ExtendedProperties ConvertProperties(ExtendedProperties p) { ExtendedProperties c = new ExtendedProperties(); for (IEnumerator e = (IEnumerator) p.Keys; e.MoveNext(); ) { String key = (String) e.Current; String value = p.GetProperty(key).ToString(); c.SetProperty(key, value); } return c; } } } --- NEW FILE: PropertiesReader.cs --- namespace Commons.Collections { using System; using System.IO; using System.Text; /// <summary> This class is used to read properties lines. These lines do /// not terminate with new-line chars but rather when there is no /// backslash sign a the end of the line. This is used to /// concatenate multiple lines for readability. /// </summary> internal class PropertiesReader : StreamReader { /// <summary> Constructor. /// * /// </summary> /// <param name="reader">A Reader. /// /// </param> public PropertiesReader(StreamReader reader) : base(reader.BaseStream) { } /// <summary> Read a property. /// * /// </summary> /// <returns>A String. /// </returns> /// <exception cref="">IOException. /// /// </exception> public virtual String ReadProperty() { StringBuilder buffer = new StringBuilder(); try { while (true) { String line = ReadLine().Trim(); if ((line.Length != 0) && (line[0] != '#')) { if (line.EndsWith("\\")) { line = line.Substring(0, (line.Length - 1) - (0)); buffer.Append(line); } else { buffer.Append(line); break; } } } } catch (NullReferenceException e) { return null; } return buffer.ToString(); } } } |
From: Sean M. <int...@us...> - 2005-11-16 07:01:58
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.Data/Mappings In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.Data/Mappings Added Files: ProviderInfo.cs Log Message: --- NEW FILE: ProviderInfo.cs --- namespace Adapdev.Data.Mappings { /// <summary> /// Represents the provider specific information for a database column type /// </summary> public class ProviderInfo { /// <summary> /// The numeric provider-specific id /// </summary> public string Id; /// <summary> /// The provider-specific name /// </summary> public string Name; /// <summary> /// The object equivalent for the provider-specific type /// </summary> public string Object; /// <summary> /// The prefix for data /// </summary> public string Prefix; /// <summary> /// The postfix for data /// </summary> public string Postfix; /// <summary> /// The default value /// </summary> public string Default; /// <summary> /// The test default value /// </summary> public string TestDefault; } } |
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.Data In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.Data Added Files: AbstractDAO.cs Adapdev.Data.csproj CommandTextViewer.cs ConnectionStringBuilder.cs DataReaderDebugger.cs DataSetDebugger.cs DbConnectionProvider.cs DbConnectionProviders.cs DbConnectionType.cs DbConnectionTypes.cs DbConstants.cs DbProviderFactory.cs DbProviderType.cs DbProviderTypeConverter.cs DbType.cs DbTypeConverter.cs IDataAccessObject.cs IDataReaderMapper.cs IDataSetAccessObject.cs IDataSetMapper.cs IDbDataAccessObject.cs IDbDataSetAccessObject.cs ITransferObject.cs ProviderInfoManager.cs Log Message: --- NEW FILE: DataReaderDebugger.cs --- using System; using System.Data; using System.Text; namespace Adapdev.Data { /// <summary> /// Summary description for DataReaderDebugger. /// </summary> public class DataReaderDebugger { private IDataReader _reader = null; public DataReaderDebugger(IDataReader reader) { this._reader = reader; } public string Text { get { StringBuilder sb = new StringBuilder(); do { int i = _reader.FieldCount; for(int j = 0; j < i; j++) { sb.Append(this._reader.GetName(j) + "|"); } sb.Append(Environment.NewLine); while(this._reader.Read()) { for(int j = 0; j < i; j++) { sb.Append(this._reader.GetValue(j).ToString() + "|"); } sb.Append(Environment.NewLine); } sb.Append(Environment.NewLine); } while(this._reader.NextResult()); return sb.ToString(); } } } } --- NEW FILE: DbProviderFactory.cs --- namespace Adapdev.Data { using System; using System.Data; using System.Data.Common; using System.Data.OleDb; using System.Data.SqlClient; using System.Data.OracleClient; using MySql.Data.MySqlClient; /// <summary> /// Provides database neutral access to ADO.NET classes /// </summary> public class DbProviderFactory { #region IDbCommand /// <summary> /// Creates an IDbCommand implementation for the specified DbProviderType /// </summary> /// <param name="DbProviderType">The DbProviderType to use</param> /// <returns></returns> public static IDbCommand CreateCommand(DbProviderType DbProviderType) { switch (DbProviderType) { case DbProviderType.SQLSERVER: return new SqlCommand(); case DbProviderType.ORACLE: return new OracleCommand(); case DbProviderType.MYSQL: return new MySqlCommand(); default: return new OleDbCommand(); } } #endregion #region IDbConnection /// <summary> /// Creates an IDbConnection implementation for the specified DbProviderType /// </summary> /// <param name="DbProviderType"></param> /// <returns></returns> public static IDbConnection CreateConnection(DbProviderType DbProviderType) { switch (DbProviderType) { case DbProviderType.SQLSERVER: return new SqlConnection(); case DbProviderType.ORACLE: return new OracleConnection(); case DbProviderType.MYSQL: return new MySqlConnection(); default: return new OleDbConnection(); } } #endregion #region DbDataAdapter public static DbDataAdapter CreateDataAdapter(DbProviderType DbProviderType, IDbCommand command, IDbConnection connection) { switch (DbProviderType) { case DbProviderType.SQLSERVER: SqlDataAdapter sqlda = new SqlDataAdapter(); sqlda.SelectCommand = (SqlCommand) command; command.Connection = connection; return sqlda; case DbProviderType.ORACLE: OracleDataAdapter orada = new OracleDataAdapter(); orada.SelectCommand = (OracleCommand) command; command.Connection = connection; return orada; case DbProviderType.MYSQL: MySqlDataAdapter mysqlda = new MySqlDataAdapter(); mysqlda.SelectCommand = (MySqlCommand) command; command.Connection = connection; return mysqlda; default: OleDbDataAdapter oleda = new OleDbDataAdapter(); oleda.SelectCommand = (OleDbCommand) command; command.Connection = connection; return oleda; } } #endregion #region IDataReader public static IDataReader CreateDataReader(string connectionString, IDbCommand command, DbProviderType DbProviderType) { IDbConnection connection = DbProviderFactory.CreateConnection(DbProviderType); connection.ConnectionString = connectionString; return CreateDataReader(connection, command, DbProviderType); } public static IDataReader CreateDataReader(string connectionString, string command, DbProviderType DbProviderType) { IDbConnection connection = DbProviderFactory.CreateConnection(DbProviderType); connection.ConnectionString = connectionString; IDbCommand cmd = DbProviderFactory.CreateCommand(DbProviderType); cmd.CommandText = command; return CreateDataReader(connection, cmd, DbProviderType); } public static IDataReader CreateDataReader(IDbConnection connection, string command, DbProviderType DbProviderType) { IDbCommand cmd = DbProviderFactory.CreateCommand(DbProviderType); cmd.CommandText = command; return CreateDataReader(connection, cmd, DbProviderType); } public static IDataReader CreateDataReader(IDbConnection connection, IDbCommand command, DbProviderType DbProviderType) { return CreateDataReader(connection, command, CommandBehavior.Default, DbProviderType); } public static IDataReader CreateDataReader(IDbConnection connection, IDbCommand command, CommandBehavior behavior, DbProviderType DbProviderType) { IDataReader reader = null; command.Connection = connection; reader = command.ExecuteReader(behavior); return reader; } #endregion #region DataSet public static DataSet CreateDataSet(string connectionString, IDbCommand command, DbProviderType DbProviderType) { IDbConnection connection = DbProviderFactory.CreateConnection(DbProviderType); connection.ConnectionString = connectionString; return CreateDataSet(connection, command, DbProviderType); } public static DataSet CreateDataSet(IDbConnection connection, IDbCommand command, DbProviderType DbProviderType) { DataSet ds = new DataSet(); DbDataAdapter da = DbProviderFactory.CreateDataAdapter(DbProviderType, command, connection); connection.Open(); da.Fill(ds); connection.Close(); return ds; } #endregion #region DataTable public static DataTable CreateDataTable(string connection, IDbCommand command, DbProviderType DbProviderType) { throw new NotImplementedException(); } #endregion } } --- NEW FILE: AbstractDAO.cs --- namespace Adapdev.Data { using System; using System.Collections; using System.Data; using System.Data.Common; using System.Data.OleDb; using System.Data.SqlClient; using Adapdev.Data.Sql; /// <summary> /// AbstractDAO provides the required base functionality to create a full-featured /// Data Access Object. /// </summary> /// public abstract class AbstractDAO : IDbDataAccessObject, IDbDataSetAccessObject, IDataReaderMapper { private DbProviderType provider = DbProviderType.SQLSERVER; private DbType db = DbType.SQLSERVER; private string connectionString = ""; private string table = ""; #region Constructors /// <summary> /// Constructor /// </summary> /// <param name="providerType">The specified provider type</param> /// <param name="databaseType">The specified database type</param> /// <param name="tableName">The table being accessed</param> /// <param name="connectionString">The specified connection string</param> public AbstractDAO(DbProviderType providerType, DbType databaseType, string tableName, string connectionString) { this.provider = providerType; this.db = databaseType; this.table = tableName; this.connectionString = connectionString; } #endregion #region IDataAccessObject Members /// <summary> /// Saves the specified object to the datastore /// </summary> /// <param name="o"></param> /// public void Save(object o) { using(IDbConnection connection = this.CreateConnection()) { connection.Open(); this.ExecuteNonQuery(this.CreateInsertCommand(o), connection); this.CustomSave(o, connection); } } /// <summary> /// Saves the specified object to the datastore, using the specified open connection /// </summary> /// <param name="o">The object to save</param> /// <param name="conn">The open connection to use</param> /// <remarks>The IDbConnection must already be open</remarks> public void Save(object o, IDbConnection conn) { this.ExecuteNonQuery(this.CreateInsertCommand(o), conn); this.CustomSave(o, conn); } /// <summary> /// Saves the specified object to the datastore, using the specified open connection /// </summary> /// <param name="o">The object to save</param> /// <param name="conn">The open connection to use</param> /// <param name="transaction">The transaction to execute under</param> /// <remarks>The IDbConnection must already be open</remarks> public void Save(object o, IDbConnection conn, IDbTransaction transaction) { this.ExecuteNonQuery(this.CreateInsertCommand(o), conn, transaction); this.CustomSave(o, conn, transaction); } /// <summary> /// Deletes the specified object by its id /// </summary> /// <param name="id">The id for the object to delete</param> public void Delete(object id) { this.ExecuteNonQuery(this.CreateDeleteOneCommand(id)); } /// <summary> /// Deletes the specified object by its id /// </summary> /// <param name="id">The id for the object to delete</param> /// <param name="conn">The open connection to use</param> /// <remarks>The IDbConnection must already be open</remarks> public void Delete(object id, IDbConnection conn) { this.ExecuteNonQuery(this.CreateDeleteOneCommand(id), conn); } /// <summary> /// Deletes the specified object by its id /// </summary> /// <param name="id">The id for the object to delete</param> /// <param name="conn">The open connection to use</param> /// <param name="transaction">The transaction to execute under</param> /// <remarks>The IDbConnection must already be open</remarks> public void Delete(object id, IDbConnection conn, IDbTransaction transaction) { this.ExecuteNonQuery(this.CreateDeleteOneCommand(id), conn, transaction); } /// <summary> /// Updates the underlying datastore /// </summary> /// <param name="o">The object to use for the update</param> public void Update(object o) { this.ExecuteNonQuery(this.CreateUpdateCommand(o)); } /// <summary> /// Updates the underlying datastore /// </summary> /// <param name="o">The object to use for the update</param> /// <param name="conn">The open connection to use</param> /// <remarks>The IDbConnection must already be open</remarks> public void Update(object o, IDbConnection conn) { this.ExecuteNonQuery(this.CreateUpdateCommand(o), conn); } /// <summary> /// Updates the underlying datastore /// </summary> /// <param name="o">The object to use for the update</param> /// <param name="conn">The open connection to use</param> /// <param name="transaction">The transaction to execute under</param> /// <remarks>The IDbConnection must already be open</remarks> public void Update(object o, IDbConnection conn, IDbTransaction transaction) { this.ExecuteNonQuery(this.CreateUpdateCommand(o), conn, transaction); } /// <summary> /// Selects all records in the underlying datastore /// </summary> /// <returns></returns> public IList SelectAll() { IList c; using (IDbConnection conn = this.CreateConnection()) { conn.Open(); c = this.SelectAll(conn); } return c; } /// <summary> /// Selects all records in the underlying datastore, using the specified open IDbConnection /// </summary> /// <param name="conn">The open IDbConnection to use</param> /// <returns></returns> public IList SelectAll(IDbConnection conn) { IList c; IDataReader dr = DbProviderFactory.CreateDataReader(conn, this.CreateSelectAllCommand(), this.provider); c = this.MapObjects(dr); dr.Close(); return c; } /// <summary> /// Selects a set number of records in the underlying datastore /// </summary> /// <param name="maxRecords">The number of records to return</param> /// <returns></returns> public IList SelectAllWithLimit(int maxRecords) { return this.SelectAllWithLimit(maxRecords, OrderBy.ASCENDING); } /// <summary> /// Selects a set number of records in the underlying datastore, /// using the specified open IDbConnection /// </summary> /// <param name="maxRecords">The number of records to return</param> /// <param name="connection">The open IDbConnection to use</param> /// <returns></returns> public IList SelectAllWithLimit(int maxRecords, IDbConnection connection) { return this.SelectAllWithLimit(maxRecords, OrderBy.ASCENDING, connection); } /// <summary> /// Selects a set number of records in the underlying datastore /// </summary> /// <param name="maxRecords">The number of records to return</param> /// <param name="order">The order the records should be returned</param> /// <param name="orderColumns">The columns to order by</param> /// <returns></returns> public IList SelectAllWithLimit(int maxRecords, OrderBy order, params string[] orderColumns) { ISelectQuery query = QueryFactory.CreateSelectQuery(this.db); query.SetTable(this.table); query.SetLimit(maxRecords); query.OrderBy = order; query.AddAll(); foreach (string s in orderColumns) { query.AddOrderBy(s); } return this.Select(query); } /// <summary> /// Selects a set number of records in the underlying datastore /// </summary> /// <param name="maxRecords">The number of records to return</param> /// <param name="order">The order the records should be returned</param> /// <param name="connection">The open IDbConnection to use</param> /// <param name="orderColumns">The columns to order by</param> /// <returns></returns> public IList SelectAllWithLimit(int maxRecords, OrderBy order, IDbConnection connection, params string[] orderColumns) { ISelectQuery query = QueryFactory.CreateSelectQuery(this.db); query.SetTable(this.table); query.SetLimit(maxRecords); query.OrderBy = order; query.AddAll(); foreach (string s in orderColumns) { query.AddOrderBy(s); } return this.Select(query, connection); } /// <summary> /// Selects records using the specified query /// </summary> /// <param name="query">The query to use</param> /// <returns></returns> public IList Select(ISelectQuery query) { return this.Select(this.CreateCommand(query.GetText())); } /// <summary> /// Selects records using the specified query /// </summary> /// <param name="query">The query to use</param> /// <param name="connection">The open IDbConnection</param> /// <returns></returns> public IList Select(ISelectQuery query, IDbConnection connection) { return this.Select(this.CreateCommand(query.GetText()), connection); } /// <summary> /// Selects records using the specified command /// </summary> /// <param name="cmd">The command to use</param> /// <returns></returns> public IList Select(IDbCommand cmd) { IList c; using (IDbConnection conn = this.CreateConnection()) { conn.Open(); c = this.Select(cmd, conn); } return c; } /// <summary> /// Selects records using the specified command /// </summary> /// <param name="cmd">The command to use</param> /// <param name="conn">The open IDbConnection to use</param> /// <returns></returns> public IList Select(IDbCommand cmd, IDbConnection conn) { IList c; IDataReader dr = DbProviderFactory.CreateDataReader(conn, cmd, this.provider); c = this.MapObjects(dr); dr.Close(); return c; } /// <summary> /// Selects records using the specified command /// </summary> /// <param name="command">The command to use</param> /// <returns></returns> public IList Select(string command) { return this.Select(this.CreateCommand(command)); } /// <summary> /// Selects records using the specified command /// </summary> /// <param name="command">The command to use</param> /// <param name="conn">The open IDbConnection to use</param> /// <returns></returns> public IList Select(string command, IDbConnection conn) { return this.Select(this.CreateCommand(command), conn); } /// <summary> /// Selects a specific record, using the passed in id /// </summary> /// <param name="id">The id for the record to select</param> /// <returns></returns> public object SelectById(object id) { return this.SelectOne(id); } /// <summary> /// Selects a specific record, using the passed in id /// </summary> /// <param name="id">The id for the record to select</param> /// <param name="connection">The open IDbConnection to use</param> /// <returns></returns> public object SelectById(object id, IDbConnection connection) { return this.SelectOne(id, connection); } /// <summary> /// Selects a specific record, using the passed in id /// </summary> /// <param name="id">The id for the record to select</param> /// <returns></returns> /// [Obsolete("Deprecated. Please use SelectById")] public object SelectOne(object id) { object o; using (IDbConnection conn = this.CreateConnection()) { conn.Open(); o = this.SelectOne(id, conn); } return o; } /// <summary> /// Selects a specific record, using the passed in id /// </summary> /// <param name="id">The id for the record to select</param> /// <param name="conn">The open IDbConnection to use</param> /// <returns></returns> [Obsolete("Deprecated. Please use SelectById")] public object SelectOne(object id, IDbConnection conn) { object o = null; IDataReader dr = DbProviderFactory.CreateDataReader(conn, this.CreateSelectOneCommand(id), this.provider); while (dr.Read()) { o = this.MapObject(dr); break; } dr.Close(); return o; } /// <summary> /// Executes the specified command /// </summary> /// <param name="cmd">The command to use</param> public void ExecuteNonQuery(IDbCommand cmd) { using (IDbConnection conn = this.CreateConnection()) { cmd.Connection = conn; conn.Open(); cmd.ExecuteNonQuery(); } } /// <summary> /// Executes the specified command /// </summary> /// <param name="cmd">The command to use</param> /// <param name="conn">The open IDbConnection to use</param> public void ExecuteNonQuery(IDbCommand cmd, IDbConnection conn) { cmd.Connection = conn; cmd.ExecuteNonQuery(); } /// <summary> /// Executes the specified command /// </summary> /// <param name="cmd">The command to use</param> /// <param name="conn">The open IDbConnection to use</param> /// <param name="transaction">The transaction to execute under</param> public void ExecuteNonQuery(IDbCommand cmd, IDbConnection conn, IDbTransaction transaction) { cmd.Connection = conn; cmd.Transaction = transaction; cmd.ExecuteNonQuery(); } /// <summary> /// Executes the specified query /// </summary> /// <param name="query">The query to use</param> public void ExecuteNonQuery(INonSelectQuery query) { this.ExecuteNonQuery(this.CreateCommand(query.GetText())); } /// <summary> /// Executes the specified query /// </summary> /// <param name="query">The query to use</param> /// <param name="connection">The open IDbConnection to use</param> public void ExecuteNonQuery(INonSelectQuery query, IDbConnection connection) { this.ExecuteNonQuery(this.CreateCommand(query.GetText()), connection); } /// <summary> /// Executse the specified command /// </summary> /// <param name="command">The command to use</param> public void ExecuteNonQuery(string command) { this.ExecuteNonQuery(this.CreateCommand(command)); } /// <summary> /// Executes the specified command /// </summary> /// <param name="command">The command to use</param> /// <param name="connection">The open IDbConnection to use</param> public void ExecuteNonQuery(string command, IDbConnection connection) { this.ExecuteNonQuery(this.CreateCommand(command), connection); } /// <summary> /// Executes the specified command /// </summary> /// <param name="command">The command to use</param> /// <param name="connection">The open IDbConnection to use</param> /// <param name="transaction">The transaction to execute under</param> public void ExecuteNonQuery(string command, IDbConnection connection, IDbTransaction transaction) { this.ExecuteNonQuery(this.CreateCommand(command), connection, transaction); } #endregion #region IDataSetAccessObject Members /// <summary> /// Saves the specified DataSet /// </summary> /// <param name="ds">The DataSet to save</param> /// <returns>Number of modified records</returns> public int SaveDS(DataSet ds) { int i; using (IDbConnection conn = this.CreateConnection()) { conn.Open(); i = this.SaveDS(ds, conn); } return i; } /// <summary> /// Saves the specified DataSet /// </summary> /// <param name="ds">The DataSet to save</param> /// <param name="conn">The open IDbConnection to use</param> /// <returns>Number of modified records</returns> public virtual int SaveDS(DataSet ds, IDbConnection conn) { DbDataAdapter da = DbProviderFactory.CreateDataAdapter(this.Provider, this.CreateSelectAllCommand(), conn); int modified = 0; DataSet modifiedDS = ds.GetChanges(); if (modifiedDS != null) { if (this.Provider == DbProviderType.SQLSERVER) { SqlCommandBuilder cb = new SqlCommandBuilder((SqlDataAdapter) da); foreach (DataTable dt in modifiedDS.Tables) { modified += da.Update(modifiedDS, dt.TableName); } } else { OleDbCommandBuilder cb = new OleDbCommandBuilder((OleDbDataAdapter) da); foreach (DataTable dt in modifiedDS.Tables) { modified += da.Update(modifiedDS, dt.TableName); } } return modified; } else { return 0; } } /// <summary> /// Selects all records /// </summary> /// <returns></returns> public DataSet SelectAllDS() { return this.CreateDataSet(this.CreateSelectAllCommand()); } /// <summary> /// Selects all records /// </summary> /// <param name="conn">The open IDbConnection to use</param> /// <returns></returns> public DataSet SelectAllDS(IDbConnection conn) { return this.GetDataSet(this.CreateSelectAllCommand(), conn); } /// <summary> /// Creates a DataSet using the given command /// </summary> /// <param name="cmd">The command to execute</param> /// <returns></returns> public DataSet SelectDS(IDbCommand cmd) { return this.CreateDataSet(cmd); } /// <summary> /// Creates a DataSet using the given command /// </summary> /// <param name="sql">The sql command to execute</param> /// <returns></returns> public DataSet SelectDS(string sql) { return this.SelectDS(this.CreateCommand(sql)); } /// <summary> /// Creates a DataSet using the given command /// </summary> /// <param name="sql">The sql command to execute</param> /// <param name="conn">The open IDbConnection to use</param> /// <returns></returns> public DataSet SelectDS(string sql, IDbConnection conn) { return this.GetDataSet(this.CreateCommand(sql), conn); } /// <summary> /// Creates a DataSet using the given command /// </summary> /// <param name="cmd">The command to execute</param> /// <param name="conn">The open IDbConnection to use</param> /// <returns></returns> public DataSet SelectDS(IDbCommand cmd, IDbConnection conn) { return this.GetDataSet(cmd, conn); } /// <summary> /// Returns one record wrapped in a DataSet /// </summary> /// <param name="id">The id of the record to select</param> /// <returns></returns> public DataSet SelectDatasetById(object id) { return this.SelectOneDS(id); } /// <summary> /// Returns one record wrapped in a DataSet /// </summary> /// <param name="id">The id of the record to select</param> /// <param name="conn">The open IDbConnection to use</param> /// <returns></returns> public DataSet SelectDatasetById(object id, IDbConnection conn) { return this.SelectOneDS(id, conn); } /// <summary> /// Returns one record wrapped in a DataSet /// </summary> /// <param name="id">The id of the record to select</param> /// <returns></returns> /// [Obsolete("Deprecated. Please use SelectDataSetById")] public DataSet SelectOneDS(object id) { return this.CreateDataSet(this.CreateSelectOneCommand(id)); } /// <summary> /// Returns one record wrapped in a DataSet /// </summary> /// <param name="id">The id of the record to select</param> /// <param name="conn">The open IDbConnection to use</param> /// <returns></returns> [Obsolete("Deprecated. Please use SelectDataSetById")] public DataSet SelectOneDS(object id, IDbConnection conn) { return this.GetDataSet(this.CreateSelectOneCommand(id), conn); } #endregion #region IDataReaderMapper Members /// <summary> /// Maps a collection of objects, using the specified DataReader /// </summary> /// <param name="dr">The DataReader to use for the object mapping</param> /// <returns></returns> public IList MapObjects(IDataReader dr) { ArrayList al = new ArrayList(); while (dr.Read()) { al.Add(this.MapObject(dr)); } return al; } #endregion #region Other Members /// <summary> /// Gets the total count of records /// </summary> /// <returns></returns> public int GetCount() { return this.GetCount(null); } /// <summary> /// Gets the total count of records /// </summary> /// <param name="criteria">The criteria to query with</param> /// <returns></returns> public int GetCount(ICriteria criteria) { int count = 0; ISelectQuery query = QueryFactory.CreateSelectQuery(this.db); query.SetTable(this.table); query.AddCountAll(); if (criteria != null) { query.SetCriteria(criteria); } using (IDbConnection conn = this.CreateConnection()) { conn.Open(); IDataReader dr = DbProviderFactory.CreateDataReader(conn, this.CreateCommand(query.GetText()), this.provider); if (dr.Read()) { count = dr.GetInt32(0); } dr.Close(); } return count; } /// <summary> /// Creates the correct ISelectQuery implementation for the specified database /// </summary> /// <returns></returns> public ISelectQuery CreateSelectQuery() { ISelectQuery query = QueryFactory.CreateSelectQuery(this.db, this.provider); query.SetTable(this.Table); return query; } /// <summary> /// Creates the correct IDeleteQuery implementation for the specified database /// </summary> /// <returns></returns> public IDeleteQuery CreateDeleteQuery() { IDeleteQuery query = QueryFactory.CreateDeleteQuery(this.db, this.provider); query.SetTable(this.Table); return query; } /// <summary> /// Creates the correct IInsertQuery implementation for the specified database /// </summary> /// <returns></returns> public IInsertQuery CreateInsertQuery() { IInsertQuery query = QueryFactory.CreateInsertQuery(this.db, this.provider); query.SetTable(this.Table); return query; } /// <summary> /// Creates the correct IUpdateQuery implementation for the specified database /// </summary> /// <returns></returns> public IUpdateQuery CreateUpdateQuery() { IUpdateQuery query = QueryFactory.CreateUpdateQuery(this.db, this.provider); query.SetTable(this.Table); return query; } #endregion #region Properties /// <summary> /// The connection string /// </summary> public string ConnectionString { get { return this.connectionString; } set { this.connectionString = value; } } /// <summary> /// The database provider type /// </summary> public DbProviderType Provider { get { return this.provider; } set { this.provider = value; } } /// <summary> /// The database type /// </summary> public DbType Db { get { return this.db; } set { this.db = value; } } /// <summary> /// The name of the table /// </summary> public string Table { get { return this.table; } set { this.table = value; } } #endregion #region Helper Methods /// <summary> /// Creates a DataSet, using the given command /// </summary> /// <param name="cmd">The command to execute</param> /// <returns></returns> protected DataSet CreateDataSet(IDbCommand cmd) { return DbProviderFactory.CreateDataSet(this.connectionString, cmd, this.provider); } /// <summary> /// Creates a DataSet, using the given command /// </summary> /// <param name="cmd">The command to execute</param> /// <returns></returns> protected DataSet CreateDataSet(string cmd) { return DbProviderFactory.CreateDataSet(this.connectionString, this.CreateCommand(cmd), this.provider); } /// <summary> /// Creates a DataSet, using the given command /// </summary> /// <param name="cmd">The command to execute</param> /// <param name="conn">The open connection to use</param> /// <returns></returns> protected DataSet GetDataSet(IDbCommand cmd, IDbConnection conn) { return DbProviderFactory.CreateDataSet(conn, cmd, this.provider); } /// <summary> /// Creates a connection with the proper connection string filled in /// </summary> /// <returns></returns> public IDbConnection CreateConnection() { IDbConnection connection = DbProviderFactory.CreateConnection(this.provider); connection.ConnectionString = this.connectionString; return connection; } /// <summary> /// Creates a command for the correct database provider /// and sets the connection /// </summary> /// <param name="command">The command to execute</param> /// <returns></returns> public IDbCommand CreateCommand(string command) { IDbCommand cmd = DbProviderFactory.CreateCommand(this.provider); cmd.CommandText = command; cmd.Connection = this.CreateConnection(); return cmd; } /// <summary> /// Creates a command to select all records /// </summary> /// <returns></returns> protected IDbCommand CreateSelectAllCommand() { IDbCommand command = DbProviderFactory.CreateCommand(this.provider); ISelectQuery s = QueryFactory.CreateSelectQuery(this.db); s.AddAll(); s.SetTable(this.Table); command.CommandText = s.GetText(); return command; } /// <summary> /// Creates a command to delete all records /// </summary> /// <returns></returns> protected IDbCommand CreateDeleteAllCommand() { IDbCommand command = DbProviderFactory.CreateCommand(this.provider); IDeleteQuery s = QueryFactory.CreateDeleteQuery(this.db, this.provider); s.SetTable(this.Table); command.CommandText = s.GetText(); return command; } #endregion #region Custom Items /// <summary> /// Used for custom actions when Save is called. Allows for retrieval /// of autoinsert fields, etc. using the open connection. /// </summary> /// <param name="o"></param> /// <param name="connection"></param> protected virtual void CustomSave(object o, IDbConnection connection){} protected virtual void CustomSave(object o, IDbConnection connection, IDbTransaction transaction){} #endregion #region Abstract Items /// <summary> /// Maps an individual object to a DataReader row /// </summary> /// <param name="dr"></param> /// <returns></returns> protected abstract object MapObject(IDataReader dr); /// <summary> /// Selects one record, using the specified id /// </summary> /// <param name="id">The id of the record to select</param> /// <returns></returns> protected abstract IDbCommand CreateSelectOneCommand(object id); /// <summary> /// Updates a record, using the values from the specified object /// </summary> /// <param name="o"></param> /// <returns></returns> protected abstract IDbCommand CreateUpdateCommand(object o); /// <summary> /// Inserts a record, using the values from the specified object /// </summary> /// <param name="o"></param> /// <returns></returns> protected abstract IDbCommand CreateInsertCommand(object o); /// <summary> /// Deletes one record, using the specified id /// </summary> /// <param name="id"></param> /// <returns></returns> protected abstract IDbCommand CreateDeleteOneCommand(object id); #endregion } } --- NEW FILE: ITransferObject.cs --- namespace Adapdev.Data { /// <summary> /// Represents a Transfer Object (an object that can be passed between /// application layers and between remote applications, and is focused purely /// on holding data). /// </summary> /// <remarks>See Martin Fowler's Patterns of Enterprise Applications, or the J2EE /// Core Patterns for more information</remarks> public interface ITransferObject { } } --- NEW FILE: DbConstants.cs --- namespace Adapdev.Data { /// <summary> /// Provides string representation of database names /// </summary> public class DbConstants { public const string SQLSERVER = "sqlserver"; public const string ORACLE = "oracle"; public const string ACCESS = "access"; public const string MYSQL = "mysql"; public const string DB2 = "db2"; } } --- NEW FILE: DbProviderTypeConverter.cs --- namespace Adapdev.Data { using System; /// <summary> /// Summary description for DbProviderTypeConverter. /// </summary> public class DbProviderTypeConverter { public static DbProviderType Convert(string s) { switch (s.Trim().ToLower()) { case "unknown": return DbProviderType.UNKNOWN; case "db2": return DbProviderType.DB2; case "mysql": return DbProviderType.MYSQL; case "odbc": return DbProviderType.ODBC; case "oledb": return DbProviderType.OLEDB; case "oracle": return DbProviderType.ORACLE; case "sqlserver": case "sqlclient": return DbProviderType.SQLSERVER; default: throw new Exception("DbProviderType " + s + " not found."); } } public static string Convert(DbProviderType t) { switch (t) { case DbProviderType.UNKNOWN: return "UNKNOWN"; case DbProviderType.ODBC: return "ODBC"; case DbProviderType.OLEDB: return "OLEDB"; case DbProviderType.ORACLE: return "ORACLE"; case DbProviderType.SQLSERVER: return "SQLSERVER"; case DbProviderType.MYSQL: return "MYSQL"; case DbProviderType.DB2: return "DB2"; default: throw new Exception("DbProviderType " + t.ToString() + " not found."); } } } } --- NEW FILE: DbTypeConverter.cs --- namespace Adapdev.Data { using System; /// <summary> /// Converts strings to their corresponding DbType /// </summary> public class DbTypeConverter { public static DbType Convert(string s) { switch (s.Trim().ToLower()) { case "unknown": return DbType.UNKNOWN; case "access": return DbType.ACCESS; case "db2": return DbType.DB2; case "mysql": return DbType.MYSQL; case "oracle": return DbType.ORACLE; case "sqlserver": case "sqlclient": return DbType.SQLSERVER; default: throw new Exception("DbType " + s + " not found."); } } public static string Convert(DbType t) { switch (t) { case DbType.UNKNOWN: return "UNKNOWN"; case DbType.ACCESS: return "ACCESS"; case DbType.DB2: return "DB2"; case DbType.MYSQL: return "MYSQL"; case DbType.ORACLE: return "ORACLE"; case DbType.SQLSERVER: return "SQLSERVER"; default: throw new Exception("DbType " + t.ToString() + " not found."); } } } } --- NEW FILE: IDataReaderMapper.cs --- namespace Adapdev.Data { using System.Collections; using System.Data; /// <summary> /// Summary description for IDataReaderMapper. /// </summary> public interface IDataReaderMapper { IList MapObjects(IDataReader dr); } } --- NEW FILE: IDataSetAccessObject.cs --- namespace Adapdev.Data { using System.Data; /// <summary> /// Provides DataSet-centric data access /// </summary> public interface IDataSetAccessObject { /// <summary> /// Persists a DataSet to the underlying datastore /// </summary> /// <param name="ds">The DataSet to persist</param> /// <returns></returns> int SaveDS(DataSet ds); /// <summary> /// Returns a DataSet populated with the record that matches the passed in id /// </summary> /// <param name="id">The id of the record to retrieve</param> /// <returns></returns> DataSet SelectOneDS(object id); /// <summary> /// Returns a DataSet populated with all records from the underlying datastore /// </summary> /// <returns></returns> DataSet SelectAllDS(); } } --- NEW FILE: IDataAccessObject.cs --- namespace Adapdev.Data { using System.Collections; /// <summary> /// Provides access to an underlying datastore /// </summary> public interface IDataAccessObject { /// <summary> /// Saves the specified object to the underlying datastore /// </summary> /// <param name="o">The object to persist</param> void Save(object o); /// <summary> /// Deletes the specified object from the underlying datastore, using /// the passed in id /// </summary> /// <param name="id">The id of the object to delete</param> void Delete(object id); /// <summary> /// Updates the specified object in the underlying datastore /// </summary> /// <param name="o">The object to update</param> void Update(object o); /// <summary> /// Selects an IList of objects that match the specified string criteria /// </summary> /// <param name="s">The criteria to use (for example, an XPath statement, SQL query, etc.)</param> /// <returns></returns> IList Select(string s); /// <summary> /// Retrieves all objects in the underlying datastore /// </summary> /// <returns></returns> IList SelectAll(); /// <summary> /// Retrieves an object with the matching id /// </summary> /// <param name="id">The id of the object to retrieve</param> /// <returns></returns> object SelectOne(object id); /// <summary> /// Gets the number of persisted objects in the underlying datastore /// </summary> /// <returns></returns> int GetCount(); } } --- NEW FILE: ProviderInfoManager.cs --- namespace Adapdev.Data { using System; using System.Collections; using System.Data; using System.IO; using System.Reflection; using Adapdev.Data.Mappings; using Adapdev.Data; using Adapdev.Data.Xml; /// <summary> /// Provides provider specific information related to data types /// and their corresponding object types /// </summary> public class ProviderInfoManager { private static ProviderInfoManager instance; private static readonly Hashtable ht = new Hashtable(); private static readonly ProvidersInfo ds = new ProvidersInfo(); /// <summary> /// Creates a new <see cref="ProviderInfoManager"/> instance. /// </summary> private ProviderInfoManager() { Stream s =Assembly.GetExecutingAssembly().GetManifestResourceStream("Adapdev.Data.Xml.ProviderInfo.xml"); ds.ReadXml(s); this.LoadTypes(); if (ht.Count == 0) { throw new Exception("DatabaseProviders contains no information."); } } /// <summary> /// Gets the instance. /// </summary> /// <returns></returns> public static ProviderInfoManager GetInstance() { if (instance == null) { instance = new ProviderInfoManager(); } return instance; } /// <summary> /// Loads the types. /// </summary> private void LoadTypes() { foreach (ProvidersInfo.ProviderInfoRow dr in ds.ProviderInfo.Rows) { Hashtable tht = new Hashtable(); ht.Add(dr.Name.Trim().ToLower(), tht); } foreach (ProvidersInfo.TypeRow tr in ds.Type.Rows) { Hashtable tht = (Hashtable) ht[tr.ProviderInfoRow.Name.Trim().ToLower()]; tht.Add(tr.Name.ToLower(), tr); } } /// <summary> /// Gets the prefix by name /// </summary> /// <param name="name">Name.</param> /// <param name="typeName">Name of the type.</param> /// <returns></returns> public string GetPrefixByName(string name, string typeName) { return this.GetTypeRowByName(name, typeName).Prefix; } /// <summary> /// Gets the prefix by name /// </summary> /// <param name="ct">Ct.</param> /// <param name="typeName">Name of the type.</param> /// <returns></returns> public string GetPrefixByName(DbProviderType ct, string typeName) { return this.GetPrefixByName(ct.ToString(), typeName); } /// <summary> /// Gets the postfix by name /// </summary> /// <param name="name">Name.</param> /// <param name="typeName">Name of the type.</param> /// <returns></returns> public string GetPostfixByName(string name, string typeName) { return this.GetTypeRowByName(name, typeName).Postfix; } /// <summary> /// Gets the postfix by name /// </summary> /// <param name="ct">Ct.</param> /// <param name="typeName">Name of the type.</param> /// <returns></returns> public string GetPostfixByName(DbProviderType ct, string typeName) { return this.GetPostfixByName(ct.ToString(), typeName); } /// <summary> /// Gets the postfix by name /// </summary> /// <param name="name">Name.</param> /// <param name="typeName">Name of the type.</param> /// <returns></returns> public string GetObjectByName(string name, string typeName) { return this.GetTypeRowByName(name, typeName).Object; } /// <summary> /// Gets the object by name /// </summary> /// <param name="providerType">Provider type</param> /// <param name="typeName">Name of the type.</param> /// <returns></returns> public string GetObjectByName(DbProviderType providerType, string typeName) { return this.GetObjectByName(providerType.ToString(), typeName); } /// <summary> /// Gets the object by id. /// </summary> /// <param name="name">Name.</param> /// <param name="id">Id.</param> /// <returns></returns> public string GetObjectById(string name, int id) { ProviderInfo p = this.GetTypeRowById(name, id); if (p != null) return p.Object; else return ""; } /// <summary> /// Gets the object by id. /// </summary> /// <param name="ct">Ct.</param> /// <param name="id">Id.</param> /// <returns></returns> public string GetObjectById(DbProviderType ct, int id) { return this.GetObjectById(ct.ToString(), id); } /// <summary> /// Gets the name by id. /// </summary> /// <param name="name">Name.</param> /// <param name="id">Id.</param> /// <returns></returns> public string GetNameById(string name, int id) { ProviderInfo p = this.GetTypeRowById(name, id); if (p != null) return p.Name; else return ""; } /// <summary> /// Gets the name by id. /// </summary> /// <param name="providerType">Provider type.</param> /// <param name="id">Id.</param> /// <returns></returns> public string GetNameById(DbProviderType providerType, int id) { return this.GetNameById(providerType.ToString(), id); } /// <summary> /// Gets the default by id. /// </summary> /// <param name="name">Name.</param> /// <param name="id">Id.</param> /// <returns></returns> public string GetDefaultById(string name, int id) { ProviderInfo p = this.GetTypeRowById(name, id); if (p != null) return p.Default; else return ""; } /// <summary> /// Gets the default by id. /// </summary> /// <param name="providerType">Provider type.</param> /// <param name="id">Id.</param> /// <returns></returns> public string GetDefaultById(DbProviderType providerType, int id) { return this.GetDefaultById(providerType.ToString(), id); } /// <summary> /// Gets the test default by id. /// </summary> /// <param name="name">Name.</param> /// <param name="id">Id.</param> /// <returns></returns> public string GetTestDefaultById(string name, int id) { ProviderInfo p = this.GetTypeRowById(name, id); if (p != null) return p.TestDefault; else return ""; } /// <summary> /// Gets the test default by id. /// </summary> /// <param name="providerType">Provider type.</param> /// <param name="id">Id.</param> /// <returns></returns> public string GetTestDefaultById(DbProviderType providerType, int id) { return this.GetTestDefaultById(providerType.ToString(), id); } /// <summary> /// Gets the name of the id by. /// </summary> /// <param name="name">Name.</param> /// <param name="typeName">Name of the type.</param> /// <returns></returns> public int GetIdByName(string name, string typeName) { return Convert.ToInt32(this.GetTypeRowByName(name, typeName).Id); } /// <summary> /// Gets the name of the id by. /// </summary> /// <param name="providerType">Provider type.</param> /// <param name="typeName">Name of the type.</param> /// <returns></returns> public int GetIdByName(DbProviderType providerType, string typeName) { return this.GetIdByName(providerType.ToString(), typeName); } /// <summary> /// Gets the name of the type row by. /// </summary> /// <param name="name">Name.</param> /// <param name="typeName">Name of the type.</param> /// <returns></returns> protected ProviderInfo GetTypeRowByName(string name, string typeName) { string _name = name.Trim().ToLower(); string _typeName = typeName.Trim().ToLower(); if (ht.Contains(_name)) { Hashtable tht = (Hashtable) ht[_name]; if (tht.Contains(_typeName)) { ProvidersInfo.TypeRow tr = (ProvidersInfo.TypeRow) tht[_typeName]; return this.BuildProviderInfo(tr); } } else { throw new Exception(String.Format("TypeRow not found. name: {0}, typeName: {1}", name, typeName)); } return null; } /// <summary> /// Gets the type row by id. /// </summary> /// <param name="name">Name.</param> /// <param name="id">Id.</param> /// <returns></returns> protected ProviderInfo GetTypeRowById(string name, int id) { string _name = name.Trim().ToLower(); if (ht.Contains(_name)) { Hashtable tht = (Hashtable) ht[_name]; foreach (DictionaryEntry d in tht) { ProvidersInfo.TypeRow tr = (ProvidersInfo.TypeRow) d.Value; if (tr.Id.Equals(id.ToString())) return this.BuildProviderInfo(tr); } } else { throw new Exception(String.Format("TypeRow not found. name: {0}, id: {1}", name, id)); } return null; } /// <summary> /// Builds the provider info. /// </summary> /// <param name="r">Row.</param> /// <returns></returns> protected ProviderInfo BuildProviderInfo(ProvidersInfo.TypeRow r) { ProviderInfo pr = new ProviderInfo(); pr.Default = r.Default; pr.Id = r.Id; pr.Name = r.Name; pr.Object = r.Object; pr.Postfix = r.Postfix; pr.Prefix = r.Prefix; pr.TestDefault = r.TestDefault; return pr; } } } --- NEW FILE: IDbDataSetAccessObject.cs --- namespace Adapdev.Data { using System.Data; /// <summary> /// Provides DataSet-centric operations /// </summary> public interface IDbDataSetAccessObject : IDataSetAccessObject { /// <summary> /// Saves a DataSet to the underlying datastore /// </summary> /// <param name="ds">The dataset to save</param> /// <param name="conn">The connection to use</param> /// <returns>Number of records affected</returns> int SaveDS(DataSet ds, IDbConnection conn); /// <summary> /// Returns a DataSet, most likely with one DataTable DataRow. It fills /// the DataSet by grabbing a record with a matching id /// </summary> /// <param name="id">The id of the record to retrieve</param> /// <param name="conn">The connection to use</param> /// <returns></returns> DataSet SelectOneDS(object id, IDbConnection conn); /// <summary> /// Returns a DataSet populated with all records /// </summary> /// <param name="conn">The connection to use</param> /// <returns></returns> DataSet SelectAllDS(IDbConnection conn); /// <summary> /// Returns a DataSet with records that match the command /// </summary> /// <param name="cmd">The command to use</param> /// <returns></returns> DataSet SelectDS(IDbCommand cmd); /// <summary> /// Returns a DataSet with records that match the command /// </summary> /// <param name="cmd">The command to use</param> /// <param name="conn">The connection to use</param> /// <returns></returns> DataSet SelectDS(IDbCommand cmd, IDbConnection conn); /// <summary> /// Executes the specified command /// </summary> /// <param name="cmd">The command to use</param> void ExecuteNonQuery(IDbCommand cmd); /// <summary> /// Executes the specified command /// </summary> /// <param name="cmd">The command to use</param> /// <param name="conn">The connection to use</param> void ExecuteNonQuery(IDbCommand cmd, IDbConnection conn); } } --- NEW FILE: DbType.cs --- namespace Adapdev.Data { /// <summary> /// Summary description for DbType. /// </summary> public enum DbType { UNKNOWN, ACCESS, SQLSERVER, MYSQL, ORACLE, DB2 } } --- NEW FILE: CommandTextViewer.cs --- namespace Adapdev.Data { using System; using System.Data; using System.Text; /// <summary> /// CommandStringBuilder takes an IDbCommand and creates a fully filled in sql text, replacing /// parameter designations with their actual values /// </summary> public class CommandTextViewer { private static readonly ProviderInfoManager dp = ProviderInfoManager.GetInstance(); /// <summary> /// Returns the fully filled-in sql text for a specified IDbCommand /// </summary> /// <param name="cmd"></param> /// <param name="providerType"></param> /// <returns></returns> public static string Parse(IDbCommand cmd, DbProviderType providerType) { if (providerType == DbProviderType.OLEDB) { return ParseOleDbCommand(cmd); } else if (providerType == DbProviderType.SQLSERVER) { return ParseSqlCommand(cmd); } else if (providerType == DbProviderType.ORACLE) { return ParseOracleCommand(cmd); } else throw new NotImplementedException(providerType.ToString() + " is not currently supported."); } /// <summary> /// This is a worker method, which takes an OleDbCommand and builds the sql text, with the parameter values added into it. /// </summary> /// <param name="cmd">The command.</param> /// <returns>A sql string with all of the parameter values filled in.</returns> public static string ParseOleDbCommand(IDbCommand cmd) { string cmds = cmd.CommandText.ToString().Trim(); StringBuilder scmds = new StringBuilder(cmds); if (cmd.CommandType == CommandType.Text) { for (int i = cmd.Parameters.Count - 1; i >= 0; i--) { string pvalue = ""; string pname = ((IDataParameter) cmd.Parameters[i]).ParameterName; if (((IDataParameter) cmd.Parameters[i]).Value == null) { pvalue = DBNull.Value.ToString(); } else { pvalue = ((IDataParameter) cmd.Parameters[i]).Value.ToString(); } string ptype = ((IDataParameter) cmd.Parameters[i]).DbType.ToString(); string prefix = dp.GetPrefixByName("dbtype_oledb", ptype); string newValue = prefix + pvalue + prefix; // Console.WriteLine(newValue); int qindex = scmds.ToString().LastIndexOf("?"); //Console.WriteLine(qindex + " : " + scmds.ToString().Length); //if(qindex == scmds.ToString().Length - 1) qindex = qindex - 1; if (qindex > 0) scmds.Replace("?", newValue, qindex, 1); } cmds = scmds.ToString(); } else if (cmd.CommandType == CommandType.StoredProcedure) { StringBuilder sb = new StringBuilder(); sb.Append("{call "); sb.Append(cmds + "("); for (int i = 0; i < cmd.Parameters.Count; i++) { string pvalue = ""; string pname = ((IDataParameter) cmd.Parameters[i]).ParameterName; if (((IDataParameter) cmd.Parameters[i]).Value == null) { pvalue = DBNull.Value.ToString(); } else { pvalue = ((IDataParameter) cmd.Parameters[i]).Value.ToString(); } string ptype = ((IDataParameter) cmd.Parameters[i]).DbType.ToString(); string prefix = dp.GetPrefixByName("dbtype_oledb", ptype); string newValue = prefix + pvalue + prefix; string comma = ","; if (i >= cmd.Parameters.Count - 1) { comma = ""; } sb.Append(" " + newValue + comma); } sb.Append(" )}"); cmds = sb.ToString(); } return cmds; } /// <summary> /// This is a worker method, which takes an SqlCommand and builds the sql text, with the parameter values added into it. /// </summary> /// <param name="cmd">The command.</param> /// <returns>A sql string with all of the parameter values filled in.</returns> public static string ParseSqlCommand(IDbCommand cmd) { string cmds = cmd.CommandText.ToString().Trim(); if (cmd.CommandType == CommandType.Text) { for (int i = 0; i < cmd.Parameters.Count; i++) { string pvalue = ""; string pname = ((IDataParameter) cmd.Parameters[i]).ParameterName; if (((IDataParameter) cmd.Parameters[i]).Value == null) { pvalue = DBNull.Value.ToString(); } else { pvalue = ((IDataParameter) cmd.Parameters[i]).Value.ToString(); } string ptype = ((IDataParameter) cmd.Parameters[i]).DbType.ToString(); string prefix = dp.GetPrefixByName("dbtype_sqlclient", ptype); string newValue = prefix + pvalue + prefix; cmds = cmds.Replace(pname, newValue); } } else if (cmd.CommandType == CommandType.StoredProcedure) { StringBuilder sb = new StringBuilder(); sb.Append("EXEC "); sb.Append(cmds); for (int i = 0; i < cmd.Parameters.Count; i++) { string pvalue = ""; string pname = ((IDataParameter) cmd.Parameters[i]).ParameterName; if (((IDataParameter) cmd.Parameters[i]).Value == null) { pvalue = DBNull.Value.ToString(); } else { pvalue = ((IDataParameter) cmd.Parameters[i]).Value.ToString(); } string ptype = ((IDataParameter) cmd.Parameters[i]).DbType.ToString(); string prefix = dp.GetPrefixByName("dbtype_sqlclient", ptype); string newValue = prefix + pvalue + prefix; string comma = ","; if (i >= cmd.Parameters.Count - 1) { comma = ""; } sb.Append(" " + newValue + comma); } cmds = sb.ToString(); } return cmds; } /// <summary> /// This is a worker method, which takes an OracleCommand and builds the sql text, /// with the parameter values added into it. /// </summary> /// <param name="cmd">The command.</param> /// <returns>A sql string with all of the parameter values filled in.</returns> public static string ParseOracleCommand(IDbCommand cmd) { string cmds = cmd.CommandText.ToString().Trim(); if (cmd.CommandType == CommandType.Text) { for (int i = 0; i < cmd.Parameters.Count; i++) { string pvalue = ""; string pname = ((IDataParameter) cmd.Parameters[i]).ParameterName; if (((IDataParameter) cmd.Parameters[i]).Value == null) { pvalue = DBNull.Value.ToString(); } else { pvalue = ((IDataParameter) cmd.Parameters[i]).Value.ToString(); } string ptype = ((IDataParameter) cmd.Parameters[i]).DbType.ToString(); string prefix = dp.GetPrefixByName("oracle", ptype); string newValue = prefix + pvalue + prefix; cmds = cmds.Replace(pname, newValue); } } else if (cmd.CommandType == CommandType.StoredProcedure) { StringBuilder sb = new StringBuilder(); sb.Append("CREATE OR REPLACE"); sb.Append(cmds); for (int i = 0; i < cmd.Parameters.Count; i++) { string pvalue = ""; string pname = ((IDataParameter) cmd.Parameters[i]).ParameterName; if (((IDataParameter) cmd.Parameters[i]).Value == null) { pvalue = DBNull.Value.ToString(); } else { pvalue = ((IDataParameter) cmd.Parameters[i]).Value.ToString(); } string ptype = ((IDataParameter) cmd.Parameters[i]).DbType.ToString(); string prefix = dp.GetPrefixByName("oracle", ptype); string newValue = prefix + pvalue + prefix; string comma = ","; if (i >= cmd.Parameters.Count - 1) { comma = ""; } sb.Append(" " + newValue + comma); } cmds = sb.ToString(); } return cmds; } } } --- NEW FILE: Adapdev.Data.csproj --- <VisualStudioProject> <CSHARP ProjectType = "Local" ProductVersion = "7.10.3077" SchemaVersion = "2.0" ProjectGuid = "{08C5794D-44ED-4E75-A1C1-48A28C3D0044}" > <Build> <Settings ApplicationIcon = "" AssemblyKeyContainerName = "" AssemblyName = "Adapdev.Data" AssemblyOriginatorKeyFile = "" DefaultClientScript = "JScript" DefaultHTMLPageLayout = "Grid" DefaultTargetSchema = "IE50" DelaySign = "false" OutputType = "Library" PreBuildEvent = "" PostBuildEvent = "" RootNamespace = "Adapdev.Data" RunPostBuildEvent = "OnBuildSuccess" StartupObject = "" > <Config Name = "Debug" AllowUnsafeBlocks = "false" BaseAddress = "285212672" CheckForOverflowUnderflow = "false" ConfigurationOverrideFile = "" DefineConstants = "DEBUG;TRACE" DocumentationFile = "" DebugSymbols = "true" FileAlignment = "4096" IncrementalBuild = "false" NoStdLib = "false" NoWarn = "" Optimize = "false" OutputPath = "bin\Debug\" RegisterForComInterop = "false" RemoveIntegerChecks = "false" TreatWarningsAsErrors = "false" WarningLevel = "4" /> <Config Name = "Release" AllowUnsafeBlocks = "false" BaseAddress = "285212672" CheckForOverflowUnderflow = "false" ConfigurationOverrideFile = "" DefineConstants = "TRACE" DocumentationFile = "" DebugSymbols = "false" FileAlignment = "4096" IncrementalBuild = "false" NoStdLib = "false" NoWarn = "" Optimize = "true" OutputPath = "bin\Release\" RegisterForComInterop = "false" RemoveIntegerChecks = "false" TreatWarningsAsErrors = "false" WarningLevel = "4" /> </Settings> <References> <Reference Name = "System" AssemblyName = "System" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.dll" /> <Reference Name = "System.Data" AssemblyName = "System.Data" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.Data.dll" /> <Reference Name = "System.XML" AssemblyName = "System.Xml" HintPath = "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.XML.dll" /> <Reference Name = "Adapdev" Project = "{CC30A321-2569-4B1F-8E1A-781B5509B56D}" Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" /> <Reference Name = "System.Data.OracleClient" AssemblyName = "System.Data.OracleClient" HintPath = "..\..\..\..\..\WINDOWS\Microsoft.NET\Framework\v1.1.4322\System.Data.OracleClient.dll" /> ... [truncated message content] |
From: Sean M. <int...@us...> - 2005-11-16 07:01:57
|
Update of /cvsroot/adapdev/Adapdev/src/Adapdev.NVelocity/Dvsl/Resource In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv909/src/Adapdev.NVelocity/Dvsl/Resource Added Files: defaultroot.dvsl Log Message: --- NEW FILE: defaultroot.dvsl --- ## ## This is the default root template, to make it behave like XSLT ## #match( "/" )$context.applyTemplates()#end #match("*")$context.applyTemplates()#end ## #match("text()")$node.value()#end ## #match("@*")$node.value()#end |