This commit is contained in:
2018-06-29 19:47:36 +00:00
commit be7f501333
3769 changed files with 1425961 additions and 0 deletions

View File

@@ -0,0 +1,174 @@
using System;
namespace GZTW.Data
{
/// <summary>
/// <para>Common validation routines for argument validation.</para>
/// </summary>
public sealed class ArgumentValidation
{
private ArgumentValidation()
{
}
/// <summary>
/// <para>Check if the <paramref name="variable"/> is an embpty string.</para>
/// </summary>
/// <param name="variable">
/// <para>The value to check.</para>
/// </param>
/// <param name="variableName">
/// <para>The name of the variable being checked.</para>
/// </param>
/// <remarks>
/// <para>Before checking the <paramref name="variable"/>, a call is made to <see cref="ArgumentValidation.CheckForNullReference"/>.</para>
/// </remarks>
/// <exception cref="ArgumentNullException">
/// <pararef name="variable"/> can not be <see langword="null"/> (Nothing in Visual Basic).
/// <para>- or -</para>
/// <pararef name="variableName"/> can not be <see langword="null"/> (Nothing in Visual Basic).
/// </exception>
/// <exception cref="ArgumentException">
/// <pararef name="variable"/> can not be a zero length <see cref="string"/>.
/// </exception>
public static void CheckForEmptyString(string variable, string variableName)
{
CheckForNullReference(variable, variableName);
CheckForNullReference(variableName, "variableName");
if (variable.Length == 0)
{
throw new ArgumentException("GZTW.Data.ArgumentValidation:CheckForEmptyString failed on " + variableName);
}
}
/// <summary>
/// <para>Check if the <paramref name="variable"/> is <see langword="null"/> (Nothing in Visual Basic).</para>
/// </summary>
/// <param name="variable">
/// <para>The value to check.</para>
/// </param>
/// <param name="variableName">
/// <para>The name of the variable being checked.</para>
/// </param>
/// <exception cref="ArgumentNullException">
/// <pararef name="variable"/> can not <see langword="null"/> (Nothing in Visual Basic).
/// <para>- or -</para>
/// <pararef name="variableName"/> can not <see langword="null"/> (Nothing in Visual Basic).
/// </exception>
public static void CheckForNullReference(object variable, string variableName)
{
if (variableName == null)
{
throw new ArgumentNullException("variableName");
}
if (null == variable)
{
throw new ArgumentNullException(variableName);
}
}
/// <summary>
/// Validates that the input messageName is neither null nor empty
/// </summary>
/// <param name="name">Parameter name</param>
/// <param name="messageName">Parameter value</param>
public static void CheckForInvalidNullNameReference(string name, string messageName)
{
if ((null == name) || (name.Length == 0))
{
throw new InvalidOperationException("GZTW.Data.ArgumentValidation:CheckForInvalidNullNameReference failed: " + messageName);
}
}
/// <summary>
/// <para>Checks <paramref name="bytes"/> for zero length and throw an <see cref="ArgumentException"/> if the length equals zero.</para>
/// </summary>
/// <param name="bytes">
/// The <see cref="byte"/> array to check.
/// </param>
/// <param name="variableName">
/// <para>The name of the variable being checked.</para>
/// </param>
/// <exception cref="ArgumentNullException">
/// <pararef name="variable"/> can not <see langword="null"/> (Nothing in Visual Basic).
/// <para>- or -</para>
/// <pararef name="variableName"/> can not <see langword="null"/> (Nothing in Visual Basic).
/// </exception>
/// <exception cref="ArgumentException">
/// <para><paramref name="bytes"/> can not be zero length.</para>
/// </exception>
public static void CheckForZeroBytes(byte[] bytes, string variableName)
{
CheckForNullReference(bytes, "bytes");
CheckForNullReference(variableName, "variableName");
if (bytes.Length == 0)
{
throw new ArgumentException("GZTW.Data.ArgumentValidation:CheckForZeroBytes failed: " + variableName);
}
}
/// <summary>
/// <para>Check <paramref name="variable"/> to determine if it matches the <see cref="Type"/> of <paramref name="type"/>.</para>
/// </summary>
/// <param name="variable">
/// <para>The value to check.</para>
/// </param>
/// <param name="type">
/// <para>The <see cref="Type"/> expected type of <paramref name="variable"/>.</para>
/// </param>
/// <exception cref="ArgumentNullException">
/// <pararef name="variable"/> can not <see langword="null"/> (Nothing in Visual Basic).
/// <para>- or -</para>
/// <pararef name="typeName"/> can not <see langword="null"/> (Nothing in Visual Basic).
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="variable"/> is not the expected <see cref="Type"/>.
/// </exception>
public static void CheckExpectedType(object variable, Type type)
{
CheckForNullReference(variable, "variable");
CheckForNullReference(type, "type");
if (!type.IsAssignableFrom(variable.GetType()))
{
throw new ArgumentException(SR.ExceptionExpectedType(type.FullName));
}
}
/// <summary>
/// <para>Check <paramref name="variable"/> to determine if it is a valid defined enumeration for <paramref name="enumType"/>.</para>
/// </summary>
/// <param name="variable">
/// <para>The value to check.</para>
/// </param>
/// <param name="enumType">
/// <para>The <see cref="Type"/> expected type of <paramref name="variable"/>.</para>
/// </param>
/// <param name="variableName">
/// <para>The name of the variable being checked.</para>
/// </param>
/// <exception cref="ArgumentNullException">
/// <pararef name="variable"/> can not <see langword="null"/> (Nothing in Visual Basic).
/// <para>- or -</para>
/// <pararef name="enumType"/> can not <see langword="null"/> (Nothing in Visual Basic).
/// <para>- or -</para>
/// <pararef name="variableName"/> can not <see langword="null"/> (Nothing in Visual Basic).
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="variable"/> is not the expected <see cref="Type"/>.
/// <para>- or -</para>
/// <par><paramref name="enumType"/> is not an <see cref="Enum"/>. </par>
/// </exception>
public static void CheckEnumeration(Type enumType, object variable, string variableName)
{
CheckForNullReference(variable, "variable");
CheckForNullReference(enumType, "enumType");
CheckForNullReference(variableName, "variableName");
if (!Enum.IsDefined(enumType, variable))
{
throw new ArgumentException("GZTW.Data.ArgumentValidation:CheckEnumeration failed: " + variable.ToString() +", "+ enumType.FullName+", "+variableName);
}
}
}
}

View File

@@ -0,0 +1,63 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
//
// 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("AyaNova BL")]
[assembly: AssemblyDescription("AyaNova DataAccess object library")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Ground Zero Tech-Works Inc.")]
[assembly: AssemblyProduct("AyaNova")]
[assembly: AssemblyCopyright("Copyright 2006-2018 Ground Zero Tech-Works Inc. All rights reserved.")]
[assembly: AssemblyTrademark("AyaNova® is either a registered trademark or trademark of Ground Zero Tech-Works Inc. in the United States and/or other countries.")]
[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("7.5.0.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("..\\..\\..\\..\\..\\keys\\AyaNova.snk")]
//[assembly: AssemblyKeyName("")]
[assembly: AssemblyFileVersionAttribute("7.5.0.0")]
[assembly: ComVisibleAttribute(false)]

View File

@@ -0,0 +1,78 @@
using System;
using System.Collections;
using System.Data;
namespace GZTW.Data
{
/// <devdoc>
/// CachingMechanism provides caching support for stored procedure
/// parameter discovery and caching
/// </devdoc>
internal class CachingMechanism
{
private Hashtable paramCache = Hashtable.Synchronized(new Hashtable());
/// <devdoc>
/// Create and return a copy of the IDataParameter array.
/// </devdoc>
public static IDataParameter[] CloneParameters(IDataParameter[] originalParameters)
{
IDataParameter[] clonedParameters = new IDataParameter[originalParameters.Length];
for (int i = 0, j = originalParameters.Length; i < j; i++)
{
clonedParameters[i] = (IDataParameter)((ICloneable)originalParameters[i]).Clone();
}
return clonedParameters;
}
/// <devdoc>
/// Empties all items from the cache
/// </devdoc>
public void Clear()
{
this.paramCache.Clear();
}
/// <devdoc>
/// Add a parameter array to the cache for the command.
/// </devdoc>
public void AddParameterSetToCache(IDbCommand command, IDataParameter[] parameters)
{
string connectionString = command.Connection.ConnectionString;
string storedProcedure = command.CommandText;
string key = CreateHashKey(connectionString, storedProcedure);
this.paramCache[key] = parameters;
}
/// <devdoc>
/// Gets a parameter array from the cache for the command. Returns null if no parameters are found.
/// </devdoc>
public IDataParameter[] GetCachedParameterSet(IDbCommand command)
{
string connectionString = command.Connection.ConnectionString;
string storedProcedure = command.CommandText;
string key = CreateHashKey(connectionString, storedProcedure);
IDataParameter[] cachedParameters = (IDataParameter[])(this.paramCache[key]);
return CloneParameters(cachedParameters);
}
/// <devdoc>
/// Gets if a given stored procedure on a specific connection string has a cached parameter set
/// </devdoc>
public bool IsParameterSetCached(IDbCommand command)
{
string hashKey = CreateHashKey(
command.Connection.ConnectionString,
command.CommandText);
return this.paramCache[hashKey] != null;
}
private static string CreateHashKey(string connectionString, string storedProcedure)
{
return connectionString + ":" + storedProcedure;
}
}
}

View File

@@ -0,0 +1,186 @@
using System;
using System.Data;
namespace GZTW.Data
{
/// <summary>
/// <para>Represents a wrapper for <see cref="IDbCommand"/> types. This class is abstract.</para>
/// <seealso cref="IDbCommand"/>
/// </summary>
public abstract class DBCommandWrapper : MarshalByRefObject, IDisposable
{
/// <summary>
/// <para>When overridden in a derived class, gets the underlying <see cref="IDbCommand"/>.</para>
/// </summary>
/// <value>
/// <para>The underlying <see cref="IDbCommand"/>. The default is <see langword="null"/>.</para>
/// </value>
public abstract IDbCommand Command { get; }
/// <summary>
/// <para>When overridden in a derived class, gets or sets the rows affected by this command.</para>
/// </summary>
/// <value>
/// <para>The rows affected by this command.</para>
/// </value>
public abstract int RowsAffected { get; set; }
/// <summary>
/// <para>When overridden in a derived class, gets or sets the wait time before terminating the attempt to execute a command and generating an error.</para>
/// </summary>
/// <value>
/// <para>The wait time before terminating the attempt to execute a command and generating an error.</para>
/// </value>
public abstract int CommandTimeout { get; set; }
/// <summary>
/// <para>When overridden in a derived class, adds a new instance of an <see cref="IDataParameter"/> object to the command.</para>
/// </summary>
/// <param name="name"><para>The name of the parameter.</para></param>
/// <param name="dbType"><para>One of the <see cref="DbType"/> values.</para></param>
/// <param name="size"><para>The maximum size of the data within the column.</para></param>
/// <param name="direction"><para>One of the <see cref="ParameterDirection"/> values.</para></param>
/// <param name="nullable"><para>Avalue indicating whether the parameter accepts null values.</para></param>
/// <param name="precision"><para>The maximum number of digits used to represent the <paramref name="value"/>.</para></param>
/// <param name="scale"><para>The number of decimal places to which <paramref name="value"/> is resolved.</para></param>
/// <param name="sourceColumn"><para>The name of the source column mapped to the DataSet and used for loading or returning the <paramref name="value"/>.</para></param>
/// <param name="sourceVersion"><para>One of the <see cref="DataRowVersion"/> values.</para></param>
/// <param name="value"><para>The value of the parameter.</para></param>
public abstract void AddParameter(string name, DbType dbType, int size, ParameterDirection direction,
bool nullable, byte precision, byte scale, string sourceColumn,
DataRowVersion sourceVersion, object value);
/// <summary>
/// <para>When overridden in a derived class, adds a new instance of an <see cref="IDataParameter"/> object to the command.</para>
/// </summary>
/// <param name="name"><para>The name of the parameter.</para></param>
/// <param name="dbType"><para>One of the <see cref="DbType"/> values.</para></param>
/// <param name="direction"><para>One of the <see cref="ParameterDirection"/> values.</para></param>
/// <param name="sourceColumn"><para>The name of the source column mapped to the DataSet and used for loading or returning the <paramref name="value"/>.</para></param>
/// <param name="sourceVersion"><para>One of the <see cref="DataRowVersion"/> values.</para></param>
/// <param name="value"><para>The value of the parameter.</para></param>
public abstract void AddParameter(string name, DbType dbType, ParameterDirection direction,
string sourceColumn, DataRowVersion sourceVersion, object value);
/// <summary>
/// <para>When overridden in a derived class, adds a new instance of an <see cref="IDataParameter"/> object to the command set as <see cref="ParameterDirection"/> value of Output.</para>
/// </summary>
/// <param name="name"><para>The name of the parameter.</para></param>
/// <param name="dbType"><para>One of the <see cref="DbType"/> values.</para></param>
/// <param name="size"><para>The maximum size of the data within the column.</para></param>
public abstract void AddOutParameter(string name, DbType dbType, int size);
/// <summary>
/// <para>When overridden in a derived class, adds a new instance of an <see cref="IDataParameter"/> object to the command set as <see cref="ParameterDirection"/> value of Input.</para>
/// </summary>
/// <param name="name"><para>The name of the parameter.</para></param>
/// <param name="dbType"><para>One of the <see cref="DbType"/> values.</para></param>
/// <remarks>
/// <para>This version of the method is used when you can have the same parameter object multiple times with different values.</para>
/// </remarks>
public abstract void AddInParameter(string name, DbType dbType);
/// <summary>
/// <para>When overridden in a derived class, adds a new instance of an <see cref="IDataParameter"/> object to the command set as <see cref="ParameterDirection"/> value of Input.</para>
/// </summary>
/// <param name="name"><para>The name of the parameter.</para></param>
/// <param name="dbType"><para>One of the <see cref="DbType"/> values.</para></param>
/// <param name="value"><para>The value of the parameter.</para></param>
public abstract void AddInParameter(string name, DbType dbType, object value);
/// <summary>
/// Used for special handling of large string values
/// in each type of database.
/// <para>When overridden in a derived class, adds a new instance of an <see cref="IDataParameter"/> object to the command set as <see cref="ParameterDirection"/> value of Input.</para>
/// </summary>
/// <param name="name"><para>The name of the parameter.</para></param>
/// <param name="value"><para>The value of the parameter.</para></param>
public abstract void AddLargeStringInParameter(string name, object value);
/// <summary>
/// <para>When overridden in a derived class, adds a new instance of an <see cref="IDataParameter"/> object to the command set as <see cref="ParameterDirection"/> value of Input.</para>
/// </summary>
/// <param name="name"><para>The name of the parameter.</para></param>
/// <param name="dbType"><para>One of the <see cref="DbType"/> values.</para></param>
/// <param name="sourceColumn"><para>The name of the source column mapped to the DataSet and used for loading or returning the value.</para></param>
/// <param name="sourceVersion"><para>One of the <see cref="DataRowVersion"/> values.</para></param>
public abstract void AddInParameter(string name, DbType dbType, string sourceColumn, DataRowVersion sourceVersion);
/// <summary>
/// <para>When overridden in a derived class, returns the value of the parameter for the given <paramref name="name"/>.</para>
/// </summary>
/// <param name="name"><para>The name of the parameter to get the value.</para></param>
/// <returns><para>The value of the parameter.</para></returns>
public abstract object GetParameterValue(string name);
/// <summary>
/// <para>When overridden in a derived class, sets the value of a parameter for the given <paramref name="name"/>.</para>
/// </summary>
/// <param name="name"><para>The name of the parameter to set the value.</para></param>
/// <param name="value"><para>The new value of the parameter.</para></param>
public abstract void SetParameterValue(string name, object value);
/// <summary>
/// <para>When overridden in a derived class, sets the value of a parameter for the given <paramref name="index"/>.</para>
/// </summary>
/// <param name="index"><para>The index of the parameter to set the value.</para></param>
/// <param name="value"><para>The new value of the parameter.</para></param>
public abstract void SetParameterValue(int index, object value);
/// <summary>
/// Populate the parameter collection for a stored procedure by querying the database
/// or loading a cached parameter set.
/// </summary>
internal void DiscoverParameters(char parameterToken)
{
DoDiscoverParameters(parameterToken);
}
/// <summary>
/// Determine if the parameters collection needs to be populated
/// using parameter discovery
/// </summary>
/// <returns>true if parameter discovery is needed</returns>
internal bool IsFurtherPreparationNeeded()
{
return DoIsFurtherPreparationNeeded();
}
/// <summary>
/// Assign values to parameters in positional orders
/// </summary>
internal void AssignParameterValues()
{
DoAssignParameterValues();
}
/// <summary>
/// <para>When overridden in a derived class, discover the parameters for a stored procedure using a separate connection and command.</para>
/// </summary>
/// <param name="parameterToken"><para>The parameter delimeter for database commands.</para></param>
protected abstract void DoDiscoverParameters(char parameterToken);
/// <summary>
/// <para>When overridden in a derived class, assign the values provided by a user to the command parameters discovered in positional order.</para>
/// </summary>
/// <exception cref="InvalidOperationException">
/// <para>The number of parameters does not match number of values for stored procedure.</para>
/// </exception>
protected abstract void DoAssignParameterValues();
/// <summary>
/// <para>When overridden in a derived class, determine if a stored procedure is using parameter discovery.</para>
/// </summary>
/// <returns>
/// <para><see langword="true"/> if further preparation is needed.</para>
/// </returns>
protected abstract bool DoIsFurtherPreparationNeeded();
/// <summary>
/// <para>When overridden in a derived class, clean up resources.</para>
/// </summary>
public abstract void Dispose();
}
}

View File

@@ -0,0 +1,466 @@
using System;
using System.Data;
using FirebirdSql.Data.FirebirdClient;
using System.Text;
namespace GZTW.Data.FireBird
{
/// <summary>
/// <para>Represents a SQL statement or stored procedure to execute against a Sql Server database.</para>
/// </summary>
public class FireBirdCommandWrapper : DBCommandWrapper
{
private FbCommand command;
private int rowsAffected;
private object[] parameterValues;
private bool needsParameters = false;
private char parameterToken;
/// <summary>
/// <para>Initialize a new instance of the <see cref="SqlCommandWrapper"/> class with the text of a query and the command type.</para>
/// </summary>
/// <param name="commandText"><para>The stored procedure name or SQL sting the command represents.</para></param>
/// <param name="commandType"><para>One of the <see crer="CommandType"/> values.</para></param>
/// <param name="parameterToken"><para>The parameter delimeter for database commands.</para></param>
internal FireBirdCommandWrapper(string commandText, CommandType commandType, char parameterToken)
{
this.parameterToken = parameterToken;
this.command = CreateCommand(commandText, commandType);
}
/// <summary>
/// <para>Initialize a new instance of the <see cref="SqlCommandWrapper"/> class with the text of a query the command type, and the parameter values.</para>
/// </summary>
/// <param name="commandText"><para>The stored procedure name or SQL sting the command represents.</para></param>
/// <param name="commandType"><para>One of the <see crer="CommandType"/> values.</para></param>
/// <param name="parameterToken"><para>The parameter delimeter for database commands.</para></param>
/// <param name="parameterValues"><para>The parameter values to assign in positional order.</para></param>
internal FireBirdCommandWrapper(string commandText, CommandType commandType, char parameterToken, object[] parameterValues) : this(commandText, commandType, parameterToken)
{
//this.command = CreateCommand(commandText, commandType);
this.parameterValues = parameterValues;
if (commandType == CommandType.StoredProcedure)
{
this.needsParameters = true;
}
}
/// <summary>
/// <para>Gets the underlying <see cref="IDbCommand"/>.</para>
/// </summary>
/// <value>
/// <para>The underlying <see cref="IDbCommand"/>. The default is <see langword="null"/>.</para>
/// </value>
/// <remarks>
/// <para>This command is a <see cref="SqlCommand"/></para>
/// </remarks>
/// <seealso cref="SqlCommand"/>
public override IDbCommand Command
{
get { return this.command; }
}
/// <summary>
/// <para>Gets or sets the rows affected by this command.</para>
/// </summary>
/// <value>
/// <para>The rows affected by this command.</para>
/// </value>
public override int RowsAffected
{
get { return this.rowsAffected; }
set { this.rowsAffected = value; }
}
/// <summary>
/// <para>Gets or sets the wait time before terminating the attempt to execute a command and generating an error.</para>
/// </summary>
/// <value>
/// <para>The wait time before terminating the attempt to execute a command and generating an error.</para>
/// </value>
/// /// <remarks>
/// <para>The inner <see cref="FbCommand"/> does not implement a command timeout.</para>
/// </remarks>
public override int CommandTimeout
{
get { return -1; }
set
{
}
}
/// <summary>
/// <para>Adds a new instance of an <see cref="SqlParameter"/> object to the command.</para>
/// </summary>
/// <param name="name"><para>The name of the parameter.</para></param>
/// <param name="dbType"><para>One of the <see cref="DbType"/> values.</para></param>
/// <param name="size"><para>The maximum size of the data within the column.</para></param>
/// <param name="direction"><para>One of the <see cref="ParameterDirection"/> values.</para></param>
/// <param name="nullable"><para>Avalue indicating whether the parameter accepts null values.</para></param>
/// <param name="precision"><para>The maximum number of digits used to represent the <paramref name="value"/>.</para></param>
/// <param name="scale"><para>The number of decimal places to which <paramref name="value"/> is resolved.</para></param>
/// <param name="sourceColumn"><para>The name of the source column mapped to the DataSet and used for loading or returning the <paramref name="value"/>.</para></param>
/// <param name="sourceVersion"><para>One of the <see cref="DataRowVersion"/> values.</para></param>
/// <param name="value"><para>The value of the parameter.</para></param>
public override void AddParameter(string name, DbType dbType, int size, ParameterDirection direction, bool nullable, byte precision, byte scale, string sourceColumn, DataRowVersion sourceVersion, object value)
{
this.command.Parameters.Add(CreateParameter(name, dbType, size, direction, nullable, precision, scale, sourceColumn, sourceVersion, value));
}
// /// <summary>
// /// <para>Adds a new instance of an <see cref="SqlParameter"/> object to the command.</para>
// /// </summary>
// /// <param name="name"><para>The name of the parameter.</para></param>
// /// <param name="sqlType"><para>One of the <see cref="SqlDbType"/> values.</para></param>
// /// <param name="size"><para>The maximum size of the data within the column.</para></param>
// /// <param name="direction"><para>One of the <see cref="ParameterDirection"/> values.</para></param>
// /// <param name="nullable"><para>Avalue indicating whether the parameter accepts null values.</para></param>
// /// <param name="precision"><para>The maximum number of digits used to represent the <paramref name="value"/>.</para></param>
// /// <param name="scale"><para>The number of decimal places to which <paramref name="value"/> is resolved.</para></param>
// /// <param name="sourceColumn"><para>The name of the source column mapped to the DataSet and used for loading or returning the <paramref name="value"/>.</para></param>
// /// <param name="sourceVersion"><para>One of the <see cref="DataRowVersion"/> values.</para></param>
// /// <param name="value"><para>The value of the parameter.</para></param>
// public void AddParameter(string name, DbType dbType, int size, ParameterDirection direction, bool nullable, byte precision, byte scale, string sourceColumn, DataRowVersion sourceVersion, object value)
// {
// FireBirdDBParameter param = CreateParameter(name, dbType.String, size, direction, nullable, precision, scale, sourceColumn, sourceVersion, value);
// param.DbType = dbType;
// this.command.Parameters.Add(param);
// }
/// <summary>
/// <para>Adds a new instance of an <see cref="SqlParameter"/> object to the command.</para>
/// </summary>
/// <param name="name"><para>The name of the parameter.</para></param>
/// <param name="dbType"><para>One of the <see cref="DbType"/> values.</para></param>
/// <param name="direction"><para>One of the <see cref="ParameterDirection"/> values.</para></param>
/// <param name="sourceColumn"><para>The name of the source column mapped to the DataSet and used for loading or returning the <paramref name="value"/>.</para></param>
/// <param name="sourceVersion"><para>One of the <see cref="DataRowVersion"/> values.</para></param>
/// <param name="value"><para>The value of the parameter.</para></param>
public override void AddParameter(string name, DbType dbType, ParameterDirection direction, string sourceColumn, DataRowVersion sourceVersion, object value)
{
FbParameter param = CreateParameter(name, dbType, 0, direction, false, 0, 0, sourceColumn, sourceVersion, value);
this.command.Parameters.Add(param);
}
/// <summary>
/// <para>Adds a new instance of an <see cref="SqlParameter"/> object to the command set as <see cref="ParameterDirection"/> value of Output.</para>
/// </summary>
/// <param name="name"><para>The name of the parameter.</para></param>
/// <param name="dbType"><para>One of the <see cref="DbType"/> values.</para></param>
/// <param name="size"><para>The maximum size of the data within the column.</para></param>
public override void AddOutParameter(string name, DbType dbType, int size)
{
AddParameter(name, dbType, size, ParameterDirection.Output, true, 0, 0, String.Empty, DataRowVersion.Default, DBNull.Value);
}
/// <summary>
/// <para>Adds a new instance of an <see cref="SqlParameter"/> object to the command set as <see cref="ParameterDirection"/> value of Input.</para>
/// </summary>
/// <param name="name"><para>The name of the parameter.</para></param>
/// <param name="dbType"><para>One of the <see cref="DbType"/> values.</para></param>
/// <remarks>
/// <para>This version of the method is used when you can have the same parameter object multiple times with different values.</para>
/// </remarks>
public override void AddInParameter(string name, DbType dbType)
{
AddParameter(name, dbType, ParameterDirection.Input, String.Empty, DataRowVersion.Default, null);
}
/// <summary>
/// <para>Adds a new instance of an <see cref="SqlParameter"/> object to the command set as <see cref="ParameterDirection"/> value of Input.</para>
/// </summary>
/// <param name="name"><para>The name of the parameter.</para></param>
/// <param name="dbType"><para>One of the <see cref="DbType"/> values.</para></param>
/// <param name="value"><para>The value of the parameter.</para></param>
public override void AddInParameter(string name, DbType dbType, object value)
{
AddParameter(name, dbType, ParameterDirection.Input, String.Empty, DataRowVersion.Default, value);
}
/// <summary>
/// Special version for handling large strings efficiently
/// For now, does nothing special as it's mssql that this was targetted to originally
/// <para>Adds a new instance of an <see cref="OracleParameter"/> object to the command set as <see cref="ParameterDirection"/> value of Input.</para>
/// </summary>
/// <param name="name"><para>The name of the parameter.</para></param>
/// <param name="value"><para>The value of the parameter.</para></param>
public override void AddLargeStringInParameter(string name, object value)
{
AddParameter(name, DbType.String, ParameterDirection.Input, String.Empty, DataRowVersion.Default, value);
}
/// <summary>
/// <para>Adds a new instance of an <see cref="SqlParameter"/> object to the command set as <see cref="ParameterDirection"/> value of Input.</para>
/// </summary>
/// <param name="name"><para>The name of the parameter.</para></param>
/// <param name="dbType"><para>One of the <see cref="DbType"/> values.</para></param>
/// <param name="sourceColumn"><para>The name of the source column mapped to the DataSet and used for loading or returning the value.</para></param>
/// <param name="sourceVersion"><para>One of the <see cref="DataRowVersion"/> values.</para></param>
public override void AddInParameter(string name, DbType dbType, string sourceColumn, DataRowVersion sourceVersion)
{
AddParameter(name, dbType, 0, ParameterDirection.Input, true, 0, 0, sourceColumn, sourceVersion, null);
}
/// <summary>
/// <para>Returns the value of the parameter for the given <paramref name="name"/>.</para>
/// </summary>
/// <param name="name"><para>The name of the parameter to get the value.</para></param>
/// <returns><para>The value of the parameter.</para></returns>
public override object GetParameterValue(string name)
{
return this.command.Parameters[BuildParameterName(name)].Value;
}
/// <summary>
/// <para>Sets the value of a parameter for the given <paramref name="name"/>.</para>
/// </summary>
/// <param name="name"><para>The name of the parameter to set the value.</para></param>
/// <param name="value"><para>The new value of the parameter.</para></param>
public override void SetParameterValue(string name, object value)
{
//this.command.Parameters[BuildParameterName(name)].Value = (value == null) ? DBNull.Value : value;
//throw new NotSupportedException("DAL:SetParameterValue: FireBirdDB not implemented, use AddInParameter instead");
this.command.Parameters[BuildParameterName(name)].Value = (value == null) ? DBNull.Value : value;
}
/// <summary>
/// Set parameter by index for faster performance
/// </summary>
/// <param name="index"></param>
/// <param name="value"></param>
public override void SetParameterValue(int index, object value)
{
//Handle nulls or Guid's specially for firebird
//as they are actually char 38's
if(value==null || (Guid)value==Guid.Empty)
{
this.command.Parameters[index].Value=DBNull.Value;
return;
}
if(value is Guid)
{
this.command.Parameters[index].Value="{"+((Guid)value).ToString().ToUpper()+"}";
}
else
this.command.Parameters[index].Value = (value == null) ? DBNull.Value : value;
}
/// <summary>
/// <para>Clean up resources.</para>
/// </summary>
public override void Dispose()
{
this.command.Dispose();
}
/// <summary>
/// <para>Dicover the parameters for a stored procedure using a separate connection and command.</para>
/// </summary>
/// <param name="parameterToken"><para>The parameter delimeter for database commands.</para></param>
protected override void DoDiscoverParameters(char parameterToken)
{
throw new NotSupportedException("DAL: DoDiscoverParamenters: FireBirdDB stored procedures not implemented");
// this.parameterToken = parameterToken;
// using (SqlCommand newCommand = CreateNewCommandAndConnectionForDiscovery())
// {
// SqlCommandBuilder.DeriveParameters(newCommand);
//
// foreach (IDataParameter parameter in newCommand.Parameters)
// {
// IDataParameter cloneParameter = (IDataParameter)((ICloneable)parameter).Clone();
// cloneParameter.ParameterName = BuildParameterName(cloneParameter.ParameterName);
// this.command.Parameters.Add(cloneParameter);
// }
// newCommand.Connection.Close();
// }
}
/// <summary>
/// <para>Assign the values provided by a user to the command parameters discovered in positional order.</para>
/// </summary>
/// <exception cref="InvalidOperationException">
/// <para>The number of parameters does not match number of values for stored procedure.</para>
/// </exception>
protected override void DoAssignParameterValues()
{
throw new NotSupportedException("DAL:DoAssignParameterValues: FireBirdDB stored procedures not implemented");
// if (SameNumberOfParametersAndValues() == false)
// {
// throw new InvalidOperationException(SR.ExceptionMessageParameterMatchFailure);
// }
//
// int returnParameter = 1;
// for (int i = 0; i < this.parameterValues.Length; i++)
// {
// IDataParameter parameter = this.command.Parameters[i + returnParameter];
//
// // There used to be code here that checked to see if the parameter was input or input/output
// // before assigning the value to it. We took it out because of an operational bug with
// // deriving parameters for a stored procedure. It turns out that output parameters are set
// // to input/output after discovery, so any direction checking was unneeded. Should it ever
// // be needed, it should go here, and check that a parameter is input or input/output before
// // assigning a value to it.
// SetParameterValue(parameter.ParameterName, this.parameterValues[i]);
// }
}
/// <summary>
/// <para>Determine if a stored procedure is using parameter discovery.</para>
/// </summary>
/// <returns>
/// <para><see langword="true"/> if further preparation is needed.</para>
/// </returns>
protected override bool DoIsFurtherPreparationNeeded()
{
//throw new NotSupportedException("DoIsFurtherPreparationNeeded: FireBirdDB does not support stored procedures");
return this.needsParameters;
}
/// <devdoc>
/// Create a parameter converting it as necessary.
/// </devdoc>
private FbParameter CreateParameter(string name, DbType type, int size, ParameterDirection direction, bool nullable, byte precision, byte scale, string sourceColumn, DataRowVersion sourceVersion, object value)
{
FbParameter param = this.command.CreateParameter();
param.ParameterName = BuildParameterName(name);
param.IsNullable=true;
switch(type)
{
case DbType.Guid://char38 in firebird (ensure emptys save as nulls)
param.FbDbType=FbDbType.Char;
if(value==null || (Guid)value==Guid.Empty)
param.Value=DBNull.Value;//"{"+Guid.Empty.ToString()+"}";
else
{
param.Value="{"+((Guid)value).ToString().ToUpper()+"}";
}
break;
//any and all binary byte[] types
case DbType.Object:
param.FbDbType=FbDbType.Binary;
param.Value = (value == null) ? DBNull.Value : value;
break;
case DbType.Binary:
param.FbDbType=FbDbType.Binary;
param.Value = (value == null) ? DBNull.Value : value;
break;
case DbType.String:
param.FbDbType=FbDbType.VarChar;
param.Value = (value == null ) ? DBNull.Value : value;
break;
case DbType.DateTime:
param.FbDbType=FbDbType.TimeStamp;
param.Value = (value == null) ? DBNull.Value : value;
break;
case DbType.Int16:
param.FbDbType=FbDbType.SmallInt;
param.Value = (value == null) ? DBNull.Value : value;
break;
case DbType.Int32:
param.FbDbType=FbDbType.Integer;
param.Value = (value == null) ? DBNull.Value : value;
break;
case DbType.Int64:
param.FbDbType=FbDbType.BigInt;
param.Value = (value == null) ? DBNull.Value : value;
break;
case DbType.Decimal:
param.FbDbType=FbDbType.Decimal;
param.Value = (value == null) ? DBNull.Value : value;
break;
case DbType.Boolean://small int in firebird
param.FbDbType=FbDbType.SmallInt;
if(value==null)
param.Value=DBNull.Value;
else
{
if((bool)value==true)
param.Value=1;
else
param.Value=0;
}
break;
default:
{
throw new NotSupportedException("FireBirdCommandWrapper:CreateParameter encountered unexpected type:" + type.ToString());
}
}
param.Size = size;
param.Direction = direction;
//param.IsNullable = nullable;
param.Precision = precision;
param.Scale = scale;
param.SourceColumn = sourceColumn;
param.SourceVersion = sourceVersion;
return param;
}
private bool SameNumberOfParametersAndValues()
{
int returnParameterCount = 1;
int numberOfParametersToStoredProcedure = this.command.Parameters.Count - returnParameterCount;
int numberOfValuesProvidedForStoredProcedure = this.parameterValues.Length;
return numberOfParametersToStoredProcedure == numberOfValuesProvidedForStoredProcedure;
}
/// <devdoc>
/// Discovery has to be done on its own connection to allow for the case of the
/// connection being used being enrolled in a transaction. The SqlCommandBuilder.DeriveParameters
/// method creates a new SqlCommand internally to communicate to the database, and it
/// reuses the same connection that is passed in on the command object. If this command
/// object has a connection that is enrolled in a transaction, the DeriveParameters method does not
/// honor that transaction, and the call fails. To avoid this, create your own connection and
/// command, and use them.
///
/// You then have to clone each of the IDataParameter objects before it can be transferred to
/// the original command, or another exception is thrown.
/// </devdoc>
// private SqlCommand CreateNewCommandAndConnectionForDiscovery()
// {
// SqlConnection clonedConnection = (SqlConnection)((ICloneable)this.command.Connection).Clone();
// clonedConnection.Open();
// SqlCommand newCommand = CreateCommand(this.command.CommandText, this.command.CommandType);
// newCommand.Connection = clonedConnection;
//
// return newCommand;
// }
private static FbCommand CreateCommand(string commandText, CommandType commandType)
{
FbCommand newCommand = new FbCommand();
newCommand.CommandText = commandText;
newCommand.CommandType = commandType;
return newCommand;
}
private string BuildParameterName(string name)
{
//since the token is *always* specified, no need for this at all
return name;
// //System.Diagnostics.Debug.Assert(parameterToken != 0x0000);
// if (name[0] != this.parameterToken)
// {
// return name.Insert(0, new string(this.parameterToken, 1));
// }
// return name;
}
}
}

View File

@@ -0,0 +1,224 @@
using System;
using System.Collections;
using System.Data;
using FirebirdSql.Data.FirebirdClient;
//using FirebirdSql.Data.Firebird;
using System.Globalization;
using System.Text;
namespace GZTW.Data.FireBird
{
/// <devdoc>
/// A wrapper to convert data from FireBird for the reader.
/// </devdoc>
internal class FireBirdDataReaderWrapper : MarshalByRefObject, IDataReader, IEnumerable
{
private FbDataReader innerReader;
public static explicit operator FbDataReader(FireBirdDataReaderWrapper fireBirdDataReaderWrapper)
{
return fireBirdDataReaderWrapper.InnerReader;
}
public FireBirdDataReaderWrapper(FbDataReader reader)
{
this.innerReader = reader;
}
public object this[int index]
{
get { return InnerReader[index]; }
}
public object this[string name]
{
get { return InnerReader[name]; }
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable)InnerReader).GetEnumerator();
}
void IDisposable.Dispose()
{
//InnerReader.Dispose();
}
public void Close()
{
InnerReader.Close();
}
public DataTable GetSchemaTable()
{
return InnerReader.GetSchemaTable();
}
public bool NextResult()
{
return InnerReader.NextResult();
}
public bool Read()
{
return InnerReader.Read();
}
public int Depth
{
get { return InnerReader.Depth; }
}
public bool IsClosed
{
get { return InnerReader.IsClosed; }
}
public int RecordsAffected
{
get { return InnerReader.RecordsAffected; }
}
public int FieldCount
{
get { return InnerReader.FieldCount; }
}
public bool GetBoolean(int index)
{
if(InnerReader.GetInt16(index)!=0)
return true;
return false;
//not directly supported, using int16 instead
//int nBool=InnerReader.get
//return InnerReader.GetBoolean(index);
}
public byte GetByte(int index)
{
return InnerReader.GetByte(index);
}
public long GetBytes(int ordinal, long dataIndex, byte[] buffer, int bufferIndex, int length)
{
return InnerReader.GetBytes(ordinal, dataIndex, buffer, bufferIndex, length);
}
public Char GetChar(int index)
{
return InnerReader.GetChar(index);
}
public long GetChars(int index, long dataIndex, char[] buffer, int bufferIndex, int length)
{
return InnerReader.GetChars(index, dataIndex, buffer, bufferIndex, length);
}
public IDataReader GetData(int index)
{
return InnerReader.GetData(index);
}
public string GetDataTypeName(int index)
{
return InnerReader.GetDataTypeName(index);
}
public DateTime GetDateTime(int ordinal_)
{
return InnerReader.GetDateTime(ordinal_);
}
public decimal GetDecimal(int index)
{
return InnerReader.GetDecimal(index);
}
public double GetDouble(int index)
{
return InnerReader.GetDouble(index);
}
public Type GetFieldType(int index)
{
return InnerReader.GetFieldType(index);
}
public float GetFloat(int index)
{
return InnerReader.GetFloat(index);
}
//not directly supported using char38
public Guid GetGuid(int index)
{
string sTemp=InnerReader.GetString(index);
if(sTemp==null||sTemp=="")
return Guid.Empty;
else
return new Guid(sTemp);
}
public short GetInt16(int index)
{
return InnerReader.GetInt16(index);
}
public int GetInt32(int index)
{
return InnerReader.GetInt32(index);
}
public long GetInt64(int index)
{
return InnerReader.GetInt64(index);
}
public string GetName(int index)
{
return InnerReader.GetName(index);
}
public int GetOrdinal(string index)
{
return InnerReader.GetOrdinal(index);
}
public string GetString(int index)
{
return InnerReader.GetString(index);
}
public object GetValue(int index)
{
return InnerReader.GetValue(index);
}
public int GetValues(object[] values)
{
return InnerReader.GetValues(values);
}
public bool IsDBNull(int index)
{
return InnerReader.IsDBNull(index);
}
public FbDataReader InnerReader
{
get { return this.innerReader; }
}
}
}

View File

@@ -0,0 +1,251 @@
using System;
using System.Data;
using System.Data.Common;
using FirebirdSql.Data.FirebirdClient;
//using FirebirdSql.Data.Firebird;
using System.Xml;
//using GZTW.Common;
namespace GZTW.Data.FireBird
{
/// <summary>
/// <para>Represents a FireBird Database.</para>
/// </summary>
/// <remarks>
/// <para>
/// Firebird database
/// </para>
/// </remarks>
public class FireBirdDatabase : GZTWDatabase
{
/// <summary>
/// Initialize a new instance of the <see cref="FireBirdDatabase"/> class.
/// </summary>
public FireBirdDatabase() : base()
{
}
public override void ClearPool()
{
FbConnection.ClearAllPools();
}
/// <summary>
/// Get the DataBaseType enum for the active db type
/// Used by higher layers when some DB specific code needs to be
/// executed
/// </summary>
/// <value>
/// <para>DataBaseType enumeration value</para>
/// </value>
public override DataBaseType DBType
{
get
{
return DataBaseType.FireBird;
}
}
/// <summary>
/// Get the schema fingerprint for database
/// </summary>
public override string SchemaFingerPrint//case 856
{
get
{
string _fingerprint = "";
using (FbConnection cn = new FbConnection(ConnectionString))
{
try
{
cn.Open();
System.Text.StringBuilder sb = new System.Text.StringBuilder();
DataTable t=cn.GetSchema("Tables", new string[] { null, null,null, "TABLE" });
//iterate all tables
DataView dvTables = t.DefaultView;
dvTables.Sort = "TABLE_NAME";
foreach (DataRowView dvTable in dvTables)
{
sb.Append(dvTable["TABLE_NAME"].ToString());
sb.Append("\r\n");
DataTable tColumns = cn.GetSchema("Columns", new string[] { null, null, dvTable["TABLE_NAME"].ToString() });
DataView dvColumns = tColumns.DefaultView;
dvColumns.Sort = "COLUMN_NAME";
foreach (DataRowView dvColumn in dvColumns)
{
sb.Append("\t");
sb.Append(dvColumn["COLUMN_NAME"].ToString());
//sb.Append(" ");
//string sType = "";
//if (dvColumn["DOMAIN_NAME"] != System.DBNull.Value)
//{
// sType = dvColumn["DOMAIN_NAME"].ToString();
//}
//else
// sType = dvColumn["COLUMN_DATA_TYPE"].ToString();
//sb.Append(sType);
sb.Append("\r\n");
}
}
_fingerprint = sb.ToString().Trim();
}
catch
{
}
finally
{
if (cn != null)
cn.Close();
}
}
return _fingerprint;
}
}
/// <summary>
/// <para>Gets the parameter token used to delimit parameters for the Sql Database.</para>
/// </summary>
/// <value>
/// <para>The '?' symbol.</para>
/// </value>
protected override char ParameterToken
{
get { return '@'; }
}
/// <summary>
/// <para>Get the connection for this database.</para>
/// <seealso cref="IDbConnection"/>
/// <seealso cref="FbConnection"/>
/// </summary>
/// <returns>
/// <para>The <see cref="FbConnection"/> for this database.</para>
/// </returns>
public override IDbConnection GetConnection()
{
//try
//{
return new FbConnection(ConnectionString);
//}
//catch (Exception ex)
//{
// System.Diagnostics.Debugger.Break();
// ClearPool();
// return new FbConnection(ConnectionString);
//}
}
/// <summary>
/// We don't need stored procedures currently so throw and exception
/// </summary>
/// <param name="storedProcedureName"></param>
/// <returns></returns>
// public override DBCommandWrapper GetStoredProcCommandWrapper(string storedProcedureName)
// {
//// ArgumentValidation.CheckForNullReference(storedProcedureName, "storedProcedureName");
//// ArgumentValidation.CheckForEmptyString(storedProcedureName, "storedProcedureName");
////
//// return new SqlCommandWrapper(storedProcedureName, CommandType.StoredProcedure, ParameterToken);
// }
/// <summary>
/// Not supported
/// </summary>
/// <param name="storedProcedureName"></param>
/// <param name="parameterValues"></param>
/// <returns></returns>
// public override DBCommandWrapper GetStoredProcCommandWrapper(string storedProcedureName, params object[] parameterValues)
// {
//// ArgumentValidation.CheckForNullReference(storedProcedureName, "storedProcedureName");
//// ArgumentValidation.CheckForEmptyString(storedProcedureName, "storedProcedureName");
//// ArgumentValidation.CheckForNullReference(parameterValues, "parameterValues");
////
//// return new SqlCommandWrapper(storedProcedureName, CommandType.StoredProcedure, ParameterToken, parameterValues);
// }
/// <summary>
/// <para>Create an <see cref="FbCommandWrapper"/> for a SQL query.</para>
/// </summary>
/// <param name="query"><para>The text of the query.</para></param>
/// <returns><para>The <see cref="DBCommandWrapper"/> for the SQL query.</para></returns>
/// <exception cref="ArgumentNullException">
/// <para><paramref name="query"/> can not be <see langword="null"/> (Nothing in Visual Basic).</para>
/// </exception>
/// <exception cref="ArgumentException">
/// <para><paramref name="query"/> hast not been initialized.</para>
/// </exception>
public override DBCommandWrapper GetSqlStringCommandWrapper(string query)
{
ArgumentValidation.CheckForNullReference(query, "query");
ArgumentValidation.CheckForEmptyString(query, "query");
//Firebird uses the keyword FIRST exactly the same as ms sql TOP
query=query.Replace(" TOP "," FIRST ");
return new FireBirdCommandWrapper(query, CommandType.Text, ParameterToken);
}
/// <summary>
/// <para>Create a <see cref="FbDataAdapter"/> with the given update behavior and connection.</para>
/// </summary>
/// <param name="updateBehavior">
/// <para>One of the <see cref="UpdateBehavior"/> values.</para>
/// </param>
/// <param name="connection">
/// <para>The open connection to the database.</para>
/// </param>
/// <returns>An <see cref="DbDataAdapter"/>.</returns>
/// <exception cref="ArgumentNullException">
/// <para><paramref name="connection"/> can not be <see langword="null"/> (Nothing in Visual Basic).</para>
/// </exception>
protected override DbDataAdapter GetDataAdapter(UpdateBehavior updateBehavior, IDbConnection connection)
{
string queryStringToBeFilledInLater = String.Empty;
FbDataAdapter adapter = new FbDataAdapter(queryStringToBeFilledInLater, (FbConnection)connection);
if (updateBehavior == UpdateBehavior.Continue)
{
adapter.RowUpdated += new FbRowUpdatedEventHandler(OnFireBirdRowUpdated);
}
return adapter;
}
public override IDataReader ExecuteReader(DBCommandWrapper commandWrapper)
{
return new FireBirdDataReaderWrapper((FbDataReader)base.ExecuteReader(commandWrapper));
}
public override IDataReader ExecuteReader(DBCommandWrapper commandWrapper, IDbTransaction transaction)
{
return new FireBirdDataReaderWrapper((FbDataReader)base.ExecuteReader(commandWrapper, transaction));
}
/// <devdoc>
/// Listens for the RowUpdate event on a dataadapter to support UpdateBehavior.Continue
/// </devdoc>
private void OnFireBirdRowUpdated(object sender, FbRowUpdatedEventArgs rowThatCouldNotBeWritten)
{
if (rowThatCouldNotBeWritten.RecordsAffected == 0)
{
if (rowThatCouldNotBeWritten.Errors != null)
{
rowThatCouldNotBeWritten.Row.RowError = SR.ExceptionMessageUpdateDataSetRowFailure;
rowThatCouldNotBeWritten.Status = UpdateStatus.SkipCurrentRow;
}
}
}
}
}

View File

@@ -0,0 +1,178 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
<PropertyGroup>
<ProjectType>Local</ProjectType>
<ProductVersion>9.0.21022</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{701893AA-C042-4FB2-8643-E139372C1117}</ProjectGuid>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ApplicationIcon>
</ApplicationIcon>
<AssemblyKeyContainerName>
</AssemblyKeyContainerName>
<AssemblyName>GZTW.Data</AssemblyName>
<AssemblyOriginatorKeyFile>..\..\..\keys\AyaNova.snk</AssemblyOriginatorKeyFile>
<DefaultClientScript>JScript</DefaultClientScript>
<DefaultHTMLPageLayout>Grid</DefaultHTMLPageLayout>
<DefaultTargetSchema>IE50</DefaultTargetSchema>
<DelaySign>false</DelaySign>
<OutputType>Library</OutputType>
<RootNamespace>GZTW.Data</RootNamespace>
<RunPostBuildEvent>OnBuildSuccess</RunPostBuildEvent>
<StartupObject>
</StartupObject>
<FileUpgradeFlags>
</FileUpgradeFlags>
<UpgradeBackupLocation>
</UpgradeBackupLocation>
<SignAssembly>true</SignAssembly>
<OldToolsVersion>3.5</OldToolsVersion>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<TargetFrameworkProfile>
</TargetFrameworkProfile>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<OutputPath>bin\Debug\</OutputPath>
<AllowUnsafeBlocks>false</AllowUnsafeBlocks>
<BaseAddress>285212672</BaseAddress>
<CheckForOverflowUnderflow>false</CheckForOverflowUnderflow>
<ConfigurationOverrideFile>
</ConfigurationOverrideFile>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<DocumentationFile>
</DocumentationFile>
<DebugSymbols>true</DebugSymbols>
<FileAlignment>4096</FileAlignment>
<NoStdLib>false</NoStdLib>
<NoWarn>
</NoWarn>
<Optimize>false</Optimize>
<RegisterForComInterop>false</RegisterForComInterop>
<RemoveIntegerChecks>false</RemoveIntegerChecks>
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
<WarningLevel>4</WarningLevel>
<DebugType>full</DebugType>
<ErrorReport>prompt</ErrorReport>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<OutputPath>bin\Release\</OutputPath>
<AllowUnsafeBlocks>false</AllowUnsafeBlocks>
<BaseAddress>285212672</BaseAddress>
<CheckForOverflowUnderflow>false</CheckForOverflowUnderflow>
<ConfigurationOverrideFile>
</ConfigurationOverrideFile>
<DefineConstants>TRACE</DefineConstants>
<DocumentationFile>
</DocumentationFile>
<DebugSymbols>false</DebugSymbols>
<FileAlignment>4096</FileAlignment>
<NoStdLib>false</NoStdLib>
<NoWarn>
</NoWarn>
<Optimize>true</Optimize>
<RegisterForComInterop>false</RegisterForComInterop>
<RemoveIntegerChecks>false</RemoveIntegerChecks>
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
<WarningLevel>4</WarningLevel>
<DebugType>none</DebugType>
<ErrorReport>prompt</ErrorReport>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'RELEASE AND DEPLOY BUILD|AnyCPU' ">
<OutputPath>bin\RELEASE AND DEPLOY BUILD\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<BaseAddress>285212672</BaseAddress>
<Optimize>true</Optimize>
<DebugType>
</DebugType>
<PlatformTarget>AnyCPU</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
</PropertyGroup>
<ItemGroup>
<Reference Include="FirebirdSql.Data.FirebirdClient, Version=2.1.0.0, Culture=neutral, PublicKeyToken=3750abcc3150b00c, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\3rdprtylibs\firebird ado.net driver\FirebirdSql.Data.FirebirdClient.dll</HintPath>
</Reference>
<Reference Include="System">
<Name>System</Name>
</Reference>
<Reference Include="System.Core">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Data">
<Name>System.Data</Name>
</Reference>
<Reference Include="System.Xml">
<Name>System.XML</Name>
</Reference>
<ProjectReference Include="..\..\Profile\GZTW.Profile\GZTW.Profile.csproj">
<Name>GZTW.Profile</Name>
<Project>{EDE897E2-E2E6-441D-9F83-0B973AE09670}</Project>
<Package>{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</Package>
<Private>False</Private>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<Compile Include="ArgumentValidation.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="AssemblyInfo.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="CachingMechanism.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="DbCommandWrapper.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="FireBird\FireBirdCommandWrapper.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="FireBird\FireBirdDatabase.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="FireBird\FireBirdDataReaderWrapper.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="GZTWDatabase.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="GZTWDatabaseFactory.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="ParameterCache.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="Resources.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="Sql\SqlCommandWrapper.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="Sql\SqlDatabase.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="SR.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="UpdateBehavior.cs">
<SubType>Code</SubType>
</Compile>
<EmbeddedResource Include="SR.resx">
<DependentUpon>SR.cs</DependentUpon>
<SubType>Designer</SubType>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="..\..\..\keys\AyaNova.snk">
<Link>AyaNova.snk</Link>
</None>
</ItemGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<PropertyGroup>
<PreBuildEvent>
</PreBuildEvent>
<PostBuildEvent>
</PostBuildEvent>
</PropertyGroup>
</Project>

View File

@@ -0,0 +1,61 @@
<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<LastOpenVersion>7.10.3077</LastOpenVersion>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ReferencePath>C:\data\AyaNova\source\Profile\GZTW.Profile\bin\Release\;C:\Program Files\FirebirdNETProvider1.7\</ReferencePath>
<CopyProjectDestinationFolder>
</CopyProjectDestinationFolder>
<CopyProjectUncPath>
</CopyProjectUncPath>
<CopyProjectOption>0</CopyProjectOption>
<ProjectView>ProjectFiles</ProjectView>
<ProjectTrust>0</ProjectTrust>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<EnableASPDebugging>false</EnableASPDebugging>
<EnableASPXDebugging>false</EnableASPXDebugging>
<EnableUnmanagedDebugging>false</EnableUnmanagedDebugging>
<EnableSQLServerDebugging>false</EnableSQLServerDebugging>
<RemoteDebugEnabled>false</RemoteDebugEnabled>
<RemoteDebugMachine>
</RemoteDebugMachine>
<StartAction>Project</StartAction>
<StartArguments>
</StartArguments>
<StartPage>
</StartPage>
<StartProgram>
</StartProgram>
<StartURL>
</StartURL>
<StartWorkingDirectory>
</StartWorkingDirectory>
<StartWithIE>true</StartWithIE>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<EnableASPDebugging>false</EnableASPDebugging>
<EnableASPXDebugging>false</EnableASPXDebugging>
<EnableUnmanagedDebugging>false</EnableUnmanagedDebugging>
<EnableSQLServerDebugging>false</EnableSQLServerDebugging>
<RemoteDebugEnabled>false</RemoteDebugEnabled>
<RemoteDebugMachine>
</RemoteDebugMachine>
<StartAction>Project</StartAction>
<StartArguments>
</StartArguments>
<StartPage>
</StartPage>
<StartProgram>
</StartProgram>
<StartURL>
</StartURL>
<StartWorkingDirectory>
</StartWorkingDirectory>
<StartWithIE>true</StartWithIE>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'RELEASE AND DEPLOY BUILD|AnyCPU' ">
<StartWithIE>true</StartWithIE>
</PropertyGroup>
</Project>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,54 @@
using System;
using GZTW.Profile;
using System.Text.RegularExpressions;
namespace GZTW.Data
{
/// <summary>
/// A factory for returning database objects
/// </summary>
public sealed class GZTWDatabaseFactory
{
private GZTWDatabaseFactory()
{
}
public static GZTWDatabase CreateDatabase(AyaNovaConnectionSettings a)
{
//instantiate and return database depending upon connection setting type
switch(a.DBType)
{
case AyaNovaConnectionSettings.DataBaseType.MSSQL:
{
GZTW.Data.Sql.SqlDatabase q= new GZTW.Data.Sql.SqlDatabase();
q.ConnectionString=a.DataBaseConnectionStringUnTokenized;
return q;
}
case AyaNovaConnectionSettings.DataBaseType.FireBird:
{
GZTW.Data.FireBird.FireBirdDatabase q= new GZTW.Data.FireBird.FireBirdDatabase();
//case 1391 - make sure a user= statement is present if embedded
string sConnect = a.DataBaseConnectionStringUnTokenized;
if (a.SingleUserConnection)
{
Regex regex = new Regex("User\\s*=", RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Compiled);
if (!regex.IsMatch(sConnect))
sConnect = sConnect + "User=SYSDBA;";
}
//case 1721 - make sure Charset=UNICODE_FSS; is specified
if (!sConnect.Contains("Charset"))
sConnect = sConnect + "Charset=UNICODE_FSS;";
q.ConnectionString = sConnect;
return q;
}
}
throw new ApplicationException("GZTWDatabaseFactory: Unable to instantiate provider specific database object from settings in config file\r\nDataBaseType is not set, in-valid or config file is missing or unreadable");
}
}
}

View File

@@ -0,0 +1,91 @@
using System.Data;
namespace GZTW.Data
{
/// <summary>
/// <para>
/// Provides parameter caching services for dynamic parameter discovery of stored procedures.
/// Eliminates the round-trip to the database to derive the parameters and types when a command
/// is executed more than once.
/// </para>
/// </summary>
public class ParameterCache
{
private CachingMechanism cache = new CachingMechanism();
/// <summary>
/// <para>
/// Populates the parameter collection for a command wrapper from the cache
/// or performs a round-trip to the database to query the parameters
/// </para>
/// </summary>
/// <param name="command">
/// <para>The command to add the parameters.</para>
/// </param>
/// <param name="parameterToken">
/// <para>The token used to delimit parameters.</para>
/// </param>
public void FillParameters(DBCommandWrapper command, char parameterToken)
{
if (AlreadyCached(command))
{
AddParametersFromCache(command);
}
else
{
command.DiscoverParameters(parameterToken);
IDataParameter[] copyOfParameters = CreateParameterCopy(command);
this.cache.AddParameterSetToCache(command.Command, copyOfParameters);
}
command.AssignParameterValues();
}
/// <summary>
/// <para>Empty the parameter cache</para>
/// </summary>
internal void Clear()
{
this.cache.Clear();
}
/// <summary>
/// <para>Checks to see if a cache entry exists for a specific command on a specific connection</para>
/// </summary>
/// <param name="command">
/// <para>The command to check.</para>
/// </param>
/// <returns>True if the parameters are already cached for the provided command, false otherwise</returns>
protected virtual bool AlreadyCached(DBCommandWrapper command)
{
return this.cache.IsParameterSetCached(command.Command);
}
/// <summary>
/// <para>Adds parameters to a command using the cache</para>
/// </summary>
/// <param name="command">
/// <para>The command to add the parameters.</para>
/// </param>
protected virtual void AddParametersFromCache(DBCommandWrapper command)
{
IDataParameter[] parameters = this.cache.GetCachedParameterSet(command.Command);
foreach (IDataParameter p in parameters)
{
command.Command.Parameters.Add(p);
}
}
private static IDataParameter[] CreateParameterCopy(DBCommandWrapper command)
{
IDataParameterCollection parameters = command.Command.Parameters;
IDataParameter[] parameterArray = new IDataParameter[parameters.Count];
parameters.CopyTo(parameterArray, 0);
return CachingMechanism.CloneParameters(parameterArray);
}
}
}

View File

@@ -0,0 +1,20 @@
using System.Globalization;
namespace GZTW.Data
{
/// <devdoc>
/// Used for the common ui culture in SR
/// </devdoc>
internal sealed class Resources
{
private Resources()
{
}
public static CultureInfo CultureInfo
{
get { return CultureInfo.InvariantCulture; }
}
}
}

275
source/Data/Data/SR.cs Normal file
View File

@@ -0,0 +1,275 @@
namespace GZTW.Data
{
using System;
using System.Resources;
using System.Globalization;
internal class SR
{
public static string UserName
{
get { return Keys.GetString( Keys.UserName ); }
}
public static string Password
{
get { return Keys.GetString( Keys.Password ); }
}
public static string FactoryName
{
get { return Keys.GetString( Keys.FactoryName ); }
}
public static string ExceptionMsg
{
get { return Keys.GetString( Keys.ExceptionMsg ); }
}
public static string EventSource
{
get { return Keys.GetString( Keys.EventSource ); }
}
public static string CounterCategory
{
get { return Keys.GetString( Keys.CounterCategory ); }
}
public static string CounterCategoryHelp
{
get { return Keys.GetString( Keys.CounterCategoryHelp ); }
}
public static string LogName
{
get { return Keys.GetString( Keys.LogName ); }
}
public static string NumConnPerSec
{
get { return Keys.GetString( Keys.NumConnPerSec ); }
}
public static string NumConnPerSecMsg
{
get { return Keys.GetString( Keys.NumConnPerSecMsg ); }
}
public static string NumConnFailPerSec
{
get { return Keys.GetString( Keys.NumConnFailPerSec ); }
}
public static string NumConnFailPerSecMsg
{
get { return Keys.GetString( Keys.NumConnFailPerSecMsg ); }
}
public static string NumCmdsPerSec
{
get { return Keys.GetString( Keys.NumCmdsPerSec ); }
}
public static string NumCmdsPerSecMsg
{
get { return Keys.GetString( Keys.NumCmdsPerSecMsg ); }
}
public static string NumCmdsFailPerSec
{
get { return Keys.GetString( Keys.NumCmdsFailPerSec ); }
}
public static string NumCmdsFailPerSecMsg
{
get { return Keys.GetString( Keys.NumCmdsFailPerSecMsg ); }
}
public static string NumTransOpenPerSec
{
get { return Keys.GetString( Keys.NumTransOpenPerSec ); }
}
public static string NumTransOpenPerSecMsg
{
get { return Keys.GetString( Keys.NumTransOpenPerSecMsg ); }
}
public static string NumTransFailPerSec
{
get { return Keys.GetString( Keys.NumTransFailPerSec ); }
}
public static string NumTransFailPerSecMsg
{
get { return Keys.GetString( Keys.NumTransFailPerSecMsg ); }
}
public static string NumTransCommitPerSec
{
get { return Keys.GetString( Keys.NumTransCommitPerSec ); }
}
public static string NumTransCommitPerSecMsg
{
get { return Keys.GetString( Keys.NumTransCommitPerSecMsg ); }
}
public static string NumTransAbortPerSec
{
get { return Keys.GetString( Keys.NumTransAbortPerSec ); }
}
public static string NumTransAbortPerSecMsg
{
get { return Keys.GetString( Keys.NumTransAbortPerSecMsg ); }
}
public static string AvgCmdTime
{
get { return Keys.GetString( Keys.AvgCmdTime ); }
}
public static string AvgCmdTimeMsg
{
get { return Keys.GetString( Keys.AvgCmdTimeMsg ); }
}
public static string TotalCmd
{
get { return Keys.GetString( Keys.TotalCmd ); }
}
public static string TotalCmdMsg
{
get { return Keys.GetString( Keys.TotalCmdMsg ); }
}
public static string MessageConnection (string connectionString)
{
return Keys.GetString( Keys.MessageConnection, connectionString );
}
public static string MessageDataConnectionOpened (string connectionString)
{
return Keys.GetString( Keys.MessageDataConnectionOpened, connectionString );
}
public static string ExceptionConnectionStringNotSet
{
get { return Keys.GetString( Keys.ExceptionConnectionStringNotSet ); }
}
public static string ExceptionParameterStringIsEmpty
{
get { return Keys.GetString( Keys.ExceptionParameterStringIsEmpty ); }
}
public static string ExceptionCommandTypeNotValid
{
get { return Keys.GetString( Keys.ExceptionCommandTypeNotValid ); }
}
public static string ExceptionTableNameArrayEmpty
{
get { return Keys.GetString( Keys.ExceptionTableNameArrayEmpty ); }
}
public static string ExceptionTableNameEmpty
{
get { return Keys.GetString( Keys.ExceptionTableNameEmpty ); }
}
public static string ExceptionExpectedType (string typeName)
{
return Keys.GetString( Keys.ExceptionExpectedType, typeName );
}
public static string ExceptionDatabaseSettingsMissing
{
get { return Keys.GetString( Keys.ExceptionDatabaseSettingsMissing ); }
}
public static string ExceptionMessageCreateServiceFailure (string databaseServiceKey)
{
return Keys.GetString( Keys.ExceptionMessageCreateServiceFailure, databaseServiceKey );
}
public static string ExceptionMessageDatabaseCommandFailed (string connectionString)
{
return Keys.GetString( Keys.ExceptionMessageDatabaseCommandFailed, connectionString );
}
public static string ExceptionMessageDatabaseConnectionFailed (string connectionString)
{
return Keys.GetString( Keys.ExceptionMessageDatabaseConnectionFailed, connectionString );
}
public static string ExceptionMessageConfigurationLoadFailed (string configFilename, string exceptionMessage)
{
return Keys.GetString( Keys.ExceptionMessageConfigurationLoadFailed, configFilename, exceptionMessage );
}
public static string ExceptionMessageNoDefault
{
get { return Keys.GetString( Keys.ExceptionMessageNoDefault ); }
}
public static string ExceptionMessageUpdateDataSetArgumentFailure
{
get { return Keys.GetString( Keys.ExceptionMessageUpdateDataSetArgumentFailure ); }
}
public static string ExceptionMessageUpdateDataSetRowFailure
{
get { return Keys.GetString( Keys.ExceptionMessageUpdateDataSetRowFailure ); }
}
public static string ExceptionNoInstance (string name)
{
return Keys.GetString( Keys.ExceptionNoInstance, name );
}
public static string ExceptionNoDatabaseType (string name)
{
return Keys.GetString( Keys.ExceptionNoDatabaseType, name );
}
public static string ExceptionNoConnectionStringType (string name)
{
return Keys.GetString( Keys.ExceptionNoConnectionStringType, name );
}
public static string ExceptionMessageParameterMatchFailure
{
get { return Keys.GetString( Keys.ExceptionMessageParameterMatchFailure ); }
}
public static string ExceptionMessageEmptyTableName
{
get { return Keys.GetString( Keys.ExceptionMessageEmptyTableName ); }
}
internal class Keys
{
static ResourceManager resourceManager =
new ResourceManager("GZTW.Data.SR", typeof(GZTW.Data.SR).Module.Assembly );
public static string GetString( string key )
{
return resourceManager.GetString( key, Resources.CultureInfo );
}
public static string GetString( string key, params object[] args )
{
string msg = resourceManager.GetString( key, Resources.CultureInfo );
msg = string.Format( msg, args );
return msg;
}
public const string UserName = "UserName";
public const string Password = "Password";
public const string FactoryName = "FactoryName";
public const string ExceptionMsg = "ExceptionMsg";
public const string EventSource = "EventSource";
public const string CounterCategory = "CounterCategory";
public const string CounterCategoryHelp = "CounterCategoryHelp";
public const string LogName = "LogName";
public const string NumConnPerSec = "NumConnPerSec";
public const string NumConnPerSecMsg = "NumConnPerSecMsg";
public const string NumConnFailPerSec = "NumConnFailPerSec";
public const string NumConnFailPerSecMsg = "NumConnFailPerSecMsg";
public const string NumCmdsPerSec = "NumCmdsPerSec";
public const string NumCmdsPerSecMsg = "NumCmdsPerSecMsg";
public const string NumCmdsFailPerSec = "NumCmdsFailPerSec";
public const string NumCmdsFailPerSecMsg = "NumCmdsFailPerSecMsg";
public const string NumTransOpenPerSec = "NumTransOpenPerSec";
public const string NumTransOpenPerSecMsg = "NumTransOpenPerSecMsg";
public const string NumTransFailPerSec = "NumTransFailPerSec";
public const string NumTransFailPerSecMsg = "NumTransFailPerSecMsg";
public const string NumTransCommitPerSec = "NumTransCommitPerSec";
public const string NumTransCommitPerSecMsg = "NumTransCommitPerSecMsg";
public const string NumTransAbortPerSec = "NumTransAbortPerSec";
public const string NumTransAbortPerSecMsg = "NumTransAbortPerSecMsg";
public const string AvgCmdTime = "AvgCmdTime";
public const string AvgCmdTimeMsg = "AvgCmdTimeMsg";
public const string TotalCmd = "TotalCmd";
public const string TotalCmdMsg = "TotalCmdMsg";
public const string MessageConnection = "MessageConnection";
public const string MessageDataConnectionOpened = "MessageDataConnectionOpened";
public const string ExceptionConnectionStringNotSet = "ExceptionConnectionStringNotSet";
public const string ExceptionParameterStringIsEmpty = "ExceptionParameterStringIsEmpty";
public const string ExceptionCommandTypeNotValid = "ExceptionCommandTypeNotValid";
public const string ExceptionTableNameArrayEmpty = "ExceptionTableNameArrayEmpty";
public const string ExceptionTableNameEmpty = "ExceptionTableNameEmpty";
public const string ExceptionExpectedType = "ExceptionExpectedType";
public const string ExceptionDatabaseSettingsMissing = "ExceptionDatabaseSettingsMissing";
public const string ExceptionMessageCreateServiceFailure = "ExceptionMessageCreateServiceFailure";
public const string ExceptionMessageDatabaseCommandFailed = "ExceptionMessageDatabaseCommandFailed";
public const string ExceptionMessageDatabaseConnectionFailed = "ExceptionMessageDatabaseConnectionFailed";
public const string ExceptionMessageConfigurationLoadFailed = "ExceptionMessageConfigurationLoadFailed";
public const string ExceptionMessageNoDefault = "ExceptionMessageNoDefault";
public const string ExceptionMessageUpdateDataSetArgumentFailure = "ExceptionMessageUpdateDataSetArgumentFailure";
public const string ExceptionMessageUpdateDataSetRowFailure = "ExceptionMessageUpdateDataSetRowFailure";
public const string ExceptionNoInstance = "ExceptionNoInstance";
public const string ExceptionNoDatabaseType = "ExceptionNoDatabaseType";
public const string ExceptionNoConnectionStringType = "ExceptionNoConnectionStringType";
public const string ExceptionMessageParameterMatchFailure = "ExceptionMessageParameterMatchFailure";
public const string ExceptionMessageEmptyTableName = "ExceptionMessageEmptyTableName";
}
}
}

209
source/Data/Data/SR.resx Normal file
View File

@@ -0,0 +1,209 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<xs:schema id="root" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xs:element name="root" msdata:IsDataSet="true">
<xs:complexType>
<xs:choice maxOccurs="unbounded">
<xs:element name="data">
<xs:complexType>
<xs:sequence>
<xs:element name="value" type="xs:string" minOccurs="0" msdata:Ordinal="1" />
<xs:element name="comment" type="xs:string" minOccurs="0" msdata:Ordinal="2" />
</xs:sequence>
<xs:attribute name="name" type="xs:string" />
<xs:attribute name="type" type="xs:string" />
<xs:attribute name="mimetype" type="xs:string" />
</xs:complexType>
</xs:element>
<xs:element name="resheader">
<xs:complexType>
<xs:sequence>
<xs:element name="value" type="xs:string" minOccurs="0" msdata:Ordinal="1" />
</xs:sequence>
<xs:attribute name="name" type="xs:string" use="required" />
</xs:complexType>
</xs:element>
</xs:choice>
</xs:complexType>
</xs:element>
</xs:schema>
<data name="UserName">
<value>User id,uid</value>
</data>
<data name="Password">
<value>Password,pwd</value>
</data>
<data name="FactoryName">
<value>Database</value>
</data>
<data name="ExceptionMsg">
<value> Exception: </value>
</data>
<data name="EventSource">
<value>Enterprise Library Data Service</value>
</data>
<data name="CounterCategory">
<value>Enterprise Library Data Service</value>
</data>
<data name="CounterCategoryHelp">
<value>Enterprise Library Data Service application performance counters.</value>
</data>
<data name="LogName">
<value>Application</value>
</data>
<data name="NumConnPerSec">
<value># of Connections Opened/Sec</value>
</data>
<data name="NumConnPerSecMsg">
<value>Number of database connections opened by the Enterprise Library Data Service.</value>
</data>
<data name="NumConnFailPerSec">
<value># of Connection Failures/Sec</value>
</data>
<data name="NumConnFailPerSecMsg">
<value>Number of database connections that failed to open by the Enterprise Library Data Service.</value>
</data>
<data name="NumCmdsPerSec">
<value># of Commands Executed/Sec</value>
</data>
<data name="NumCmdsPerSecMsg">
<value>Number of database commands executed by the Enterprise Library Data Service.</value>
</data>
<data name="NumCmdsFailPerSec">
<value># of Command Failures/Sec</value>
</data>
<data name="NumCmdsFailPerSecMsg">
<value>Number of database commands that failed to execute by the Enterprise Library Data Service.</value>
</data>
<data name="NumTransOpenPerSec">
<value># of Transactions Opened/Sec</value>
</data>
<data name="NumTransOpenPerSecMsg">
<value>Number of database transactions opened by the Enterprise Library Data Service.</value>
</data>
<data name="NumTransFailPerSec">
<value># of Transaction Failures/Sec</value>
</data>
<data name="NumTransFailPerSecMsg">
<value>Number of database transactions that failed to open by the Enterprise Library Data Service.</value>
</data>
<data name="NumTransCommitPerSec">
<value># of Transactions Committed/Sec</value>
</data>
<data name="NumTransCommitPerSecMsg">
<value>Number of database transactions committed by the Enterprise Library Data Service.</value>
</data>
<data name="NumTransAbortPerSec">
<value># of Transactions Aborted/Sec</value>
</data>
<data name="NumTransAbortPerSecMsg">
<value>Number of database transactions rolled back by the Enterprise Library Data Service.</value>
</data>
<data name="AvgCmdTime">
<value>Average Command Execution Time</value>
</data>
<data name="AvgCmdTimeMsg">
<value>Average round-trip time, in seconds, for executing a database command.</value>
</data>
<data name="TotalCmd">
<value>Total Command Executions</value>
</data>
<data name="TotalCmdMsg">
<value>Total database command executed.</value>
</data>
<data name="MessageConnection">
<value>Connection: {0}</value>
<comment>.
Parameters: 0 - connectionString (string) </comment>
</data>
<data name="MessageDataConnectionOpened">
<value>Data Connection opened: {0}</value>
<comment>.
Parameters: 0 - connectionString (string) </comment>
</data>
<data name="ExceptionConnectionStringNotSet">
<value>The connection string value is not set.</value>
</data>
<data name="ExceptionParameterStringIsEmpty">
<value>The contents of this parameter cannot be empty.</value>
</data>
<data name="ExceptionCommandTypeNotValid">
<value>The value of the parameter was not valid.</value>
</data>
<data name="ExceptionTableNameArrayEmpty">
<value>The table name array used to map results to user-specified table names cannot be empty.</value>
</data>
<data name="ExceptionTableNameEmpty">
<value>The specified table name is empty.</value>
</data>
<data name="ExceptionExpectedType">
<value>The type is invalid. Expected type '{0}'.</value>
<comment>.
Parameters: 0 - typeName (string) </comment>
</data>
<data name="ExceptionDatabaseSettingsMissing">
<value>The database settings are not present in the context.</value>
</data>
<data name="ExceptionMessageCreateServiceFailure">
<value>Error creating EnterpriseLibrary.DataService database "{0}".</value>
<comment>.
Parameters: 0 - databaseServiceKey (string) </comment>
</data>
<data name="ExceptionMessageDatabaseCommandFailed">
<value>Database command failed: {0}</value>
<comment>.
Parameters: 0 - connectionString (string) </comment>
</data>
<data name="ExceptionMessageDatabaseConnectionFailed">
<value>Data connection failed to open: {0}</value>
<comment>.
Parameters: 0 - connectionString (string) </comment>
</data>
<data name="ExceptionMessageConfigurationLoadFailed">
<value>Unable to load configuration file "{0}". Exception: {1}</value>
<comment>.
Parameters: 0 - configFilename (string), 1 - exceptionMessage (string) </comment>
</data>
<data name="ExceptionMessageNoDefault">
<value>A default instance was not defined in configuration so no database can be created.</value>
</data>
<data name="ExceptionMessageUpdateDataSetArgumentFailure">
<value>At least one command must be initialized</value>
</data>
<data name="ExceptionMessageUpdateDataSetRowFailure">
<value>Failed to update row </value>
</data>
<data name="ExceptionNoInstance">
<value>'{0}' is not a named instance in configuration.</value>
<comment>.
Parameters: 0 - name (string) </comment>
</data>
<data name="ExceptionNoDatabaseType">
<value>'{0}' is not a named database type in configuration.</value>
<comment>.
Parameters: 0 - name (string) </comment>
</data>
<data name="ExceptionNoConnectionStringType">
<value>'{0}' is not a named connection string in configuration.</value>
<comment>.
Parameters: 0 - name (string) </comment>
</data>
<data name="ExceptionMessageParameterMatchFailure">
<value>The number of parameters does not match number of values for stored procedure.</value>
</data>
<data name="ExceptionMessageEmptyTableName">
<value>Expected a non-empty string for SourceTable name.</value>
</data>
<resheader name="ResMimeType">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="Version">
<value>1.0.0.0</value>
</resheader>
<resheader name="Reader">
<value>System.Resources.ResXResourceReader</value>
</resheader>
<resheader name="Writer">
<value>System.Resources.ResXResourceWriter</value>
</resheader>
</root>

View File

@@ -0,0 +1,402 @@
//===============================================================================
// Microsoft patterns & practices Enterprise Library
// Data Access Application Block
//========================= ======================================================
// Copyright © Microsoft Corporation. All rights reserved.
// Adapted from ACA.NET with permission from Avanade Inc.
// ACA.NET copyright © Avanade Inc. All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================
using System;
using System.Data;
using System.Data.SqlClient;
namespace GZTW.Data.Sql
{
/// <summary>
/// <para>Represents a SQL statement or stored procedure to execute against a Sql Server database.</para>
/// </summary>
public class SqlCommandWrapper : DBCommandWrapper
{
private SqlCommand command;
private int rowsAffected;
private object[] parameterValues;
private bool needsParameters = false;
private char parameterToken;
/// <summary>
/// <para>Initialize a new instance of the <see cref="SqlCommandWrapper"/> class with the text of a query and the command type.</para>
/// </summary>
/// <param name="commandText"><para>The stored procedure name or SQL sting the command represents.</para></param>
/// <param name="commandType"><para>One of the <see crer="CommandType"/> values.</para></param>
/// <param name="parameterToken"><para>The parameter delimeter for database commands.</para></param>
internal SqlCommandWrapper(string commandText, CommandType commandType, char parameterToken)
{
this.parameterToken = parameterToken;
this.command = CreateCommand(commandText, commandType);
}
/// <summary>
/// <para>Initialize a new instance of the <see cref="SqlCommandWrapper"/> class with the text of a query the command type, and the parameter values.</para>
/// </summary>
/// <param name="commandText"><para>The stored procedure name or SQL sting the command represents.</para></param>
/// <param name="commandType"><para>One of the <see crer="CommandType"/> values.</para></param>
/// <param name="parameterToken"><para>The parameter delimeter for database commands.</para></param>
/// <param name="parameterValues"><para>The parameter values to assign in positional order.</para></param>
internal SqlCommandWrapper(string commandText, CommandType commandType, char parameterToken, object[] parameterValues) : this(commandText, commandType, parameterToken)
{
//this.command = CreateCommand(commandText, commandType);
this.parameterValues = parameterValues;
if (commandType == CommandType.StoredProcedure)
{
this.needsParameters = true;
}
}
/// <summary>
/// <para>Gets the underlying <see cref="IDbCommand"/>.</para>
/// </summary>
/// <value>
/// <para>The underlying <see cref="IDbCommand"/>. The default is <see langword="null"/>.</para>
/// </value>
/// <remarks>
/// <para>This command is a <see cref="SqlCommand"/></para>
/// </remarks>
/// <seealso cref="SqlCommand"/>
public override IDbCommand Command
{
get { return this.command; }
}
/// <summary>
/// <para>Gets or sets the rows affected by this command.</para>
/// </summary>
/// <value>
/// <para>The rows affected by this command.</para>
/// </value>
public override int RowsAffected
{
get { return this.rowsAffected; }
set { this.rowsAffected = value; }
}
/// <summary>
/// <para>Gets or sets the wait time before terminating the attempt to execute a command and generating an error.</para>
/// </summary>
/// <value>
/// <para>The wait time before terminating the attempt to execute a command and generating an error.</para>
/// </value>
public override int CommandTimeout
{
get { return this.command.CommandTimeout; }
set { this.command.CommandTimeout = value; }
}
/// <summary>
/// <para>Adds a new instance of an <see cref="SqlParameter"/> object to the command.</para>
/// </summary>
/// <param name="name"><para>The name of the parameter.</para></param>
/// <param name="dbType"><para>One of the <see cref="DbType"/> values.</para></param>
/// <param name="size"><para>The maximum size of the data within the column.</para></param>
/// <param name="direction"><para>One of the <see cref="ParameterDirection"/> values.</para></param>
/// <param name="nullable"><para>Avalue indicating whether the parameter accepts null values.</para></param>
/// <param name="precision"><para>The maximum number of digits used to represent the <paramref name="value"/>.</para></param>
/// <param name="scale"><para>The number of decimal places to which <paramref name="value"/> is resolved.</para></param>
/// <param name="sourceColumn"><para>The name of the source column mapped to the DataSet and used for loading or returning the <paramref name="value"/>.</para></param>
/// <param name="sourceVersion"><para>One of the <see cref="DataRowVersion"/> values.</para></param>
/// <param name="value"><para>The value of the parameter.</para></param>
public override void AddParameter(string name, DbType dbType, int size, ParameterDirection direction, bool nullable, byte precision, byte scale, string sourceColumn, DataRowVersion sourceVersion, object value)
{
this.command.Parameters.Add(CreateParameter(name, dbType, size, direction, nullable, precision, scale, sourceColumn, sourceVersion, value));
}
/// <summary>
/// <para>Adds a new instance of an <see cref="SqlParameter"/> object to the command.</para>
/// </summary>
/// <param name="name"><para>The name of the parameter.</para></param>
/// <param name="sqlType"><para>One of the <see cref="SqlDbType"/> values.</para></param>
/// <param name="size"><para>The maximum size of the data within the column.</para></param>
/// <param name="direction"><para>One of the <see cref="ParameterDirection"/> values.</para></param>
/// <param name="nullable"><para>Avalue indicating whether the parameter accepts null values.</para></param>
/// <param name="precision"><para>The maximum number of digits used to represent the <paramref name="value"/>.</para></param>
/// <param name="scale"><para>The number of decimal places to which <paramref name="value"/> is resolved.</para></param>
/// <param name="sourceColumn"><para>The name of the source column mapped to the DataSet and used for loading or returning the <paramref name="value"/>.</para></param>
/// <param name="sourceVersion"><para>One of the <see cref="DataRowVersion"/> values.</para></param>
/// <param name="value"><para>The value of the parameter.</para></param>
public void AddParameter(string name, SqlDbType sqlType, int size, ParameterDirection direction, bool nullable, byte precision, byte scale, string sourceColumn, DataRowVersion sourceVersion, object value)
{
SqlParameter param = CreateParameter(name, DbType.String, size, direction, nullable, precision, scale, sourceColumn, sourceVersion, value);
param.SqlDbType = sqlType;
this.command.Parameters.Add(param);
}
/// <summary>
/// <para>Adds a new instance of an <see cref="SqlParameter"/> object to the command.</para>
/// </summary>
/// <param name="name"><para>The name of the parameter.</para></param>
/// <param name="dbType"><para>One of the <see cref="DbType"/> values.</para></param>
/// <param name="direction"><para>One of the <see cref="ParameterDirection"/> values.</para></param>
/// <param name="sourceColumn"><para>The name of the source column mapped to the DataSet and used for loading or returning the <paramref name="value"/>.</para></param>
/// <param name="sourceVersion"><para>One of the <see cref="DataRowVersion"/> values.</para></param>
/// <param name="value"><para>The value of the parameter.</para></param>
public override void AddParameter(string name, DbType dbType, ParameterDirection direction, string sourceColumn, DataRowVersion sourceVersion, object value)
{
SqlParameter param = CreateParameter(name, dbType, 0, direction, false, 0, 0, sourceColumn, sourceVersion, value);
this.command.Parameters.Add(param);
}
/// <summary>
/// <para>Adds a new instance of an <see cref="SqlParameter"/> object to the command set as <see cref="ParameterDirection"/> value of Output.</para>
/// </summary>
/// <param name="name"><para>The name of the parameter.</para></param>
/// <param name="dbType"><para>One of the <see cref="DbType"/> values.</para></param>
/// <param name="size"><para>The maximum size of the data within the column.</para></param>
public override void AddOutParameter(string name, DbType dbType, int size)
{
AddParameter(name, dbType, size, ParameterDirection.Output, true, 0, 0, String.Empty, DataRowVersion.Default, DBNull.Value);
}
/// <summary>
/// <para>Adds a new instance of an <see cref="SqlParameter"/> object to the command set as <see cref="ParameterDirection"/> value of Input.</para>
/// </summary>
/// <param name="name"><para>The name of the parameter.</para></param>
/// <param name="dbType"><para>One of the <see cref="DbType"/> values.</para></param>
/// <remarks>
/// <para>This version of the method is used when you can have
/// the same parameter object multiple times with different values.</para>
/// </remarks>
public override void AddInParameter(string name, DbType dbType)
{
AddParameter(name, dbType, ParameterDirection.Input, String.Empty, DataRowVersion.Default, null);
}
/// <summary>
/// <para>Adds a new instance of an <see cref="SqlParameter"/> object to the command set as <see cref="ParameterDirection"/> value of Input.</para>
/// </summary>
/// <param name="name"><para>The name of the parameter.</para></param>
/// <param name="dbType"><para>One of the <see cref="DbType"/> values.</para></param>
/// <param name="value"><para>The value of the parameter.</para></param>
public override void AddInParameter(string name, DbType dbType, object value)
{
AddParameter(name, dbType, ParameterDirection.Input, String.Empty, DataRowVersion.Default, value);
}
/// <summary>
/// Used for special handling of large string values
/// This is used for efficiency in MSSQL so that text type fields
/// are ensured to not point to an address on an empty string
/// <para>Adds a new instance of an <see cref="SqlParameter"/> object to the command set as <see cref="ParameterDirection"/> value of Input.</para>
/// </summary>
/// <param name="name"><para>The name of the parameter.</para></param>
/// <param name="value"><para>The value of the parameter.</para></param>
public override void AddLargeStringInParameter(string name, object value)
{
object o=value;
if(o!=null && (string)o=="")
o=null;
AddParameter(name, DbType.String, ParameterDirection.Input, String.Empty, DataRowVersion.Default, o);
}
/// <summary>
/// <para>Adds a new instance of an <see cref="SqlParameter"/> object to the command set as <see cref="ParameterDirection"/> value of Input.</para>
/// </summary>
/// <param name="name"><para>The name of the parameter.</para></param>
/// <param name="dbType"><para>One of the <see cref="DbType"/> values.</para></param>
/// <param name="sourceColumn"><para>The name of the source column mapped to the DataSet and used for loading or returning the value.</para></param>
/// <param name="sourceVersion"><para>One of the <see cref="DataRowVersion"/> values.</para></param>
public override void AddInParameter(string name, DbType dbType, string sourceColumn, DataRowVersion sourceVersion)
{
AddParameter(name, dbType, 0, ParameterDirection.Input, true, 0, 0, sourceColumn, sourceVersion, null);
}
/// <summary>
/// <para>Returns the value of the parameter for the given <paramref name="name"/>.</para>
/// </summary>
/// <param name="name"><para>The name of the parameter to get the value.</para></param>
/// <returns><para>The value of the parameter.</para></returns>
public override object GetParameterValue(string name)
{
return this.command.Parameters[BuildParameterName(name)].Value;
}
/// <summary>
/// <para>Sets the value of a parameter for the given <paramref name="name"/>.</para>
/// </summary>
/// <param name="name"><para>The name of the parameter to set the value.</para></param>
/// <param name="value"><para>The new value of the parameter.</para></param>
public override void SetParameterValue(string name, object value)
{
this.command.Parameters[BuildParameterName(name)].Value = (value == null) ? DBNull.Value : value;
}
/// <summary>
/// set parameter value by index for performance
/// </summary>
/// <param name="index"></param>
/// <param name="value"></param>
public override void SetParameterValue(int index, object value)
{
this.command.Parameters[index].Value = (value == null) ? DBNull.Value : value;
}
/// <summary>
/// <para>Clean up resources.</para>
/// </summary>
public override void Dispose()
{
this.command.Dispose();
}
/// <summary>
/// <para>Dicover the parameters for a stored procedure using a separate connection and command.</para>
/// </summary>
/// <param name="parameterToken"><para>The parameter delimeter for database commands.</para></param>
protected override void DoDiscoverParameters(char parameterToken)
{
this.parameterToken = parameterToken;
using (SqlCommand newCommand = CreateNewCommandAndConnectionForDiscovery())
{
SqlCommandBuilder.DeriveParameters(newCommand);
foreach (IDataParameter parameter in newCommand.Parameters)
{
IDataParameter cloneParameter = (IDataParameter)((ICloneable)parameter).Clone();
cloneParameter.ParameterName = BuildParameterName(cloneParameter.ParameterName);
this.command.Parameters.Add(cloneParameter);
}
newCommand.Connection.Close();
}
}
/// <summary>
/// <para>Assign the values provided by a user to the command parameters discovered in positional order.</para>
/// </summary>
/// <exception cref="InvalidOperationException">
/// <para>The number of parameters does not match number of values for stored procedure.</para>
/// </exception>
protected override void DoAssignParameterValues()
{
if (SameNumberOfParametersAndValues() == false)
{
throw new InvalidOperationException(SR.ExceptionMessageParameterMatchFailure);
}
int returnParameter = 1;
for (int i = 0; i < this.parameterValues.Length; i++)
{
IDataParameter parameter = this.command.Parameters[i + returnParameter];
// There used to be code here that checked to see if the parameter was input or input/output
// before assigning the value to it. We took it out because of an operational bug with
// deriving parameters for a stored procedure. It turns out that output parameters are set
// to input/output after discovery, so any direction checking was unneeded. Should it ever
// be needed, it should go here, and check that a parameter is input or input/output before
// assigning a value to it.
SetParameterValue(parameter.ParameterName, this.parameterValues[i]);
}
}
/// <summary>
/// <para>Determine if a stored procedure is using parameter discovery.</para>
/// </summary>
/// <returns>
/// <para><see langword="true"/> if further preparation is needed.</para>
/// </returns>
protected override bool DoIsFurtherPreparationNeeded()
{
return this.needsParameters;
}
/// <devdoc>
/// Create a parameter.
/// </devdoc>
private SqlParameter CreateParameter(string name, DbType type, int size, ParameterDirection direction, bool nullable, byte precision, byte scale, string sourceColumn, DataRowVersion sourceVersion, object value)
{
SqlParameter param = this.command.CreateParameter();
param.ParameterName = BuildParameterName(name);
param.DbType = type;
param.Size = size;
param.Direction = direction;
param.IsNullable = nullable;
param.Precision = precision;
param.Scale = scale;
param.SourceColumn = sourceColumn;
param.SourceVersion = sourceVersion;
param.Value = (value == null) ? DBNull.Value : value;
if ((type.Equals(DbType.Object)) && (value is byte[]))
{
param.SqlDbType = SqlDbType.Image;
}
else if((type.Equals(DbType.Guid)) && value!=null && ((Guid)value==Guid.Empty))
{
//Force Guid empty to save as dbnull instead
//so that we can use referential integrity properly
//on related tables with optional guid foriegn key values
param.Value=DBNull.Value;
}
return param;
}
private bool SameNumberOfParametersAndValues()
{
int returnParameterCount = 1;
int numberOfParametersToStoredProcedure = this.command.Parameters.Count - returnParameterCount;
int numberOfValuesProvidedForStoredProcedure = this.parameterValues.Length;
return numberOfParametersToStoredProcedure == numberOfValuesProvidedForStoredProcedure;
}
/// <devdoc>
/// Discovery has to be done on its own connection to allow for the case of the
/// connection being used being enrolled in a transaction. The SqlCommandBuilder.DeriveParameters
/// method creates a new SqlCommand internally to communicate to the database, and it
/// reuses the same connection that is passed in on the command object. If this command
/// object has a connection that is enrolled in a transaction, the DeriveParameters method does not
/// honor that transaction, and the call fails. To avoid this, create your own connection and
/// command, and use them.
///
/// You then have to clone each of the IDataParameter objects before it can be transferred to
/// the original command, or another exception is thrown.
/// </devdoc>
private SqlCommand CreateNewCommandAndConnectionForDiscovery()
{
SqlConnection clonedConnection = (SqlConnection)((ICloneable)this.command.Connection).Clone();
clonedConnection.Open();
SqlCommand newCommand = CreateCommand(this.command.CommandText, this.command.CommandType);
newCommand.Connection = clonedConnection;
return newCommand;
}
private static SqlCommand CreateCommand(string commandText, CommandType commandType)
{
SqlCommand newCommand = new SqlCommand();
newCommand.CommandText = commandText;
newCommand.CommandType = commandType;
return newCommand;
}
private string BuildParameterName(string name)
{
//Since we *always* specify parameters with the MSSQL @ token, for
//sqlcommandwrapper this is pointless so just return it.
return name;
// //System.Diagnostics.Debug.Assert(parameterToken != 0x0000);
// if (name[0] != this.parameterToken)
// {
// return name.Insert(0, new string(this.parameterToken, 1));
// }
// return name;
}
}
}

View File

@@ -0,0 +1,306 @@
//===============================================================================
// Microsoft patterns & practices Enterprise Library
// Data Access Application Block
//===============================================================================
// Copyright © Microsoft Corporation. All rights reserved.
// Adapted from ACA.NET with permission from Avanade Inc.
// ACA.NET copyright © Avanade Inc. All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================
using System;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Xml;
//using GZTW.Common;
namespace GZTW.Data.Sql
{
/// <summary>
/// <para>Represents a Sql Server Database.</para>
/// </summary>
/// <remarks>
/// <para>
/// Internally uses Sql Server .NET Managed Provider from Microsoft (System.Data.SqlClient) to connect to the database.
/// </para>
/// </remarks>
public class SqlDatabase : GZTWDatabase
{
/// <summary>
/// Initialize a new instance of the <see cref="SqlDatabase"/> class.
/// </summary>
public SqlDatabase() : base()
{
}
public override void ClearPool()
{
//not implemented, for firebird only for now
}
/// <summary>
/// Get the DataBaseType enum for the active db type
/// Used by higher layers when some DB specific code needs to be
/// executed
/// </summary>
/// <value>
/// <para>DataBaseType enumeration value</para>
/// </value>
public override DataBaseType DBType
{
get
{
return DataBaseType.MSSQL;
}
}
/// <summary>
/// Get the schema fingerprint for database
/// </summary>
public override string SchemaFingerPrint
{
get
{
string _fingerprint = "";
using (SqlConnection cn = new SqlConnection(ConnectionString))
{
try
{
cn.Open();
System.Text.StringBuilder sb = new System.Text.StringBuilder();
DataTable t = new DataTable();
new SqlDataAdapter("select name from sys.tables order by name", cn).Fill(t);
foreach (DataRow drTable in t.Rows)
{
//My development database has this table in it for some reason
//should be ignored
if (drTable[0].ToString() == "sysdiagrams" || drTable[0].ToString().ToLowerInvariant().Contains("dtproperties")) continue;
sb.Append(drTable[0].ToString());
sb.Append("\r\n");
DataTable tColumns = new DataTable();
new SqlDataAdapter("SELECT c.name AS column_name, t.name AS type_name " +
"FROM sys.columns AS c " +
"JOIN sys.types AS t ON c.user_type_id=t.user_type_id " +
"WHERE c.object_id = OBJECT_ID('"+ drTable[0].ToString()+"') " +
"ORDER BY c.name; ", cn).Fill(tColumns);
foreach (DataRow drColumn in tColumns.Rows)
{
sb.Append("\t");
sb.Append(drColumn["column_name"].ToString());
//sb.Append(" ");
//sb.Append(drColumn["type_name"].ToString());
sb.Append("\r\n");
}
}
_fingerprint = sb.ToString().Trim();
}
catch
{
}
finally
{
if (cn != null)
cn.Close();
}
}
return _fingerprint;
}
}
/// <summary>
/// <para>Gets the parameter token used to delimit parameters for the Sql Database.</para>
/// </summary>
/// <value>
/// <para>The '@' symbol.</para>
/// </value>
protected override char ParameterToken
{
get { return '@'; }
}
/// <summary>
/// <para>Get the connection for this database.</para>
/// <seealso cref="IDbConnection"/>
/// <seealso cref="SqlConnection"/>
/// </summary>
/// <returns>
/// <para>The <see cref="SqlConnection"/> for this database.</para>
/// </returns>
public override IDbConnection GetConnection()
{
return new SqlConnection(ConnectionString);
}
/// <summary>
/// <para>Create a <see cref="SqlCommandWrapper"/> for a stored procedure.</para>
/// </summary>
/// <param name="storedProcedureName"><para>The name of the stored procedure.</para></param>
/// <returns><para>The <see cref="SqlCommandWrapper"/> for the stored procedure.</para></returns>
/// <exception cref="ArgumentNullException">
/// <para><paramref name="storedProcedureName"/> can not be <see langword="null"/> (Nothing in Visual Basic).</para>
/// </exception>
/// <exception cref="ArgumentException">
/// <para><paramref name="storedProcedureName"/> hast not been initialized.</para>
/// </exception>
// public override DBCommandWrapper GetStoredProcCommandWrapper(string storedProcedureName)
// {
// ArgumentValidation.CheckForNullReference(storedProcedureName, "storedProcedureName");
// ArgumentValidation.CheckForEmptyString(storedProcedureName, "storedProcedureName");
//
// return new SqlCommandWrapper(storedProcedureName, CommandType.StoredProcedure, ParameterToken);
// }
/// <summary>
/// <para>Create an <see cref="SqlCommandWrapper"/> for a stored procedure.</para>
/// </summary>
/// <param name="storedProcedureName"><para>The name of the stored procedure.</para></param>
/// <param name="parameterValues"><para>The list of parameters for the procedure.</para></param>
/// <returns><para>The <see cref="SqlCommandWrapper"/> for the stored procedure.</para></returns>
/// <remarks>
/// <para>The parameters for the stored procedure will be discovered and the values are assigned in positional order.</para>
/// </remarks>
/// <exception cref="ArgumentNullException">
/// <para><paramref name="storedProcedureName"/> can not be <see langword="null"/> (Nothing in Visual Basic).</para>
/// <para>- or -</para>
/// <para><paramref name="parameterValues"/> can not be <see langword="null"/> (Nothing in Visual Basic).</para>
/// </exception>
/// <exception cref="ArgumentException">
/// <para><paramref name="storedProcedureName"/> hast not been initialized.</para>
/// </exception>
// public override DBCommandWrapper GetStoredProcCommandWrapper(string storedProcedureName, params object[] parameterValues)
// {
// ArgumentValidation.CheckForNullReference(storedProcedureName, "storedProcedureName");
// ArgumentValidation.CheckForEmptyString(storedProcedureName, "storedProcedureName");
// ArgumentValidation.CheckForNullReference(parameterValues, "parameterValues");
//
// return new SqlCommandWrapper(storedProcedureName, CommandType.StoredProcedure, ParameterToken, parameterValues);
// }
/// <summary>
/// <para>Create an <see cref="SqlCommandWrapper"/> for a SQL query.</para>
/// </summary>
/// <param name="query"><para>The text of the query.</para></param>
/// <returns><para>The <see cref="SqlCommandWrapper"/> for the SQL query.</para></returns>
/// <exception cref="ArgumentNullException">
/// <para><paramref name="query"/> can not be <see langword="null"/> (Nothing in Visual Basic).</para>
/// </exception>
/// <exception cref="ArgumentException">
/// <para><paramref name="query"/> hast not been initialized.</para>
/// </exception>
public override DBCommandWrapper GetSqlStringCommandWrapper(string query)
{
ArgumentValidation.CheckForNullReference(query, "query");
ArgumentValidation.CheckForEmptyString(query, "query");
return new SqlCommandWrapper(query, CommandType.Text, ParameterToken);
}
/// <summary>
/// <para>Create a <see cref="SqlDataAdapter"/> with the given update behavior and connection.</para>
/// </summary>
/// <param name="updateBehavior">
/// <para>One of the <see cref="UpdateBehavior"/> values.</para>
/// </param>
/// <param name="connection">
/// <para>The open connection to the database.</para>
/// </param>
/// <returns>An <see cref="SqlDataAdapter"/>.</returns>
/// <exception cref="ArgumentNullException">
/// <para><paramref name="connection"/> can not be <see langword="null"/> (Nothing in Visual Basic).</para>
/// </exception>
protected override DbDataAdapter GetDataAdapter(UpdateBehavior updateBehavior, IDbConnection connection)
{
string queryStringToBeFilledInLater = String.Empty;
SqlDataAdapter adapter = new SqlDataAdapter(queryStringToBeFilledInLater, (SqlConnection)connection);
if (updateBehavior == UpdateBehavior.Continue)
{
adapter.RowUpdated += new SqlRowUpdatedEventHandler(OnSqlRowUpdated);
}
return adapter;
}
/// <summary>
/// <para>Executes the <see cref="SqlCommandWrapper"/> and returns an <see cref="XmlReader"/>.</para>
/// </summary>
/// <param name="command">
/// <para>The <see cref="SqlCommandWrapper"/> to execute.</para>
/// </param>
/// <returns>
/// <para>An <see cref="XmlReader"/> object.</para>
/// </returns>
public XmlReader ExecuteXmlReader(SqlCommandWrapper command)
{
IDbConnection connection = OpenConnection();
PrepareCommand(command, connection);
SqlCommand sqlCommand = command.Command as SqlCommand;
return DoExecuteXmlReader(sqlCommand);
}
/// <summary>
/// <para>Executes the <see cref="SqlCommandWrapper"/> in a transaction and returns an <see cref="XmlReader"/>.</para>
/// </summary>
/// <param name="command">
/// <para>The <see cref="SqlCommandWrapper"/> to execute.</para>
/// </param>
/// <param name="transaction">
/// <para>The <see cref="IDbTransaction"/> to execute the command within.</para>
/// </param>
/// <returns>
/// <para>An <see cref="XmlReader"/> object.</para>
/// </returns>
public XmlReader ExecuteXmlReader(SqlCommandWrapper command, IDbTransaction transaction)
{
PrepareCommand(command, transaction);
SqlCommand sqlCommand = command.Command as SqlCommand;
return DoExecuteXmlReader(sqlCommand);
}
/// <devdoc>
/// Execute the actual Xml Reader call.
/// </devdoc>
private XmlReader DoExecuteXmlReader(SqlCommand sqlCommand)
{
try
{
DateTime startTime = DateTime.Now;
XmlReader reader = sqlCommand.ExecuteXmlReader();
//Instrumentation.CommandExecuted(startTime);
return reader;
}
catch
{
//Instrumentation.CommandFailed(sqlCommand.CommandText, ConnectionStringNoCredentials);
throw;
}
}
/// <devdoc>
/// Listens for the RowUpdate event on a dataadapter to support UpdateBehavior.Continue
/// </devdoc>
private void OnSqlRowUpdated(object sender, SqlRowUpdatedEventArgs rowThatCouldNotBeWritten)
{
if (rowThatCouldNotBeWritten.RecordsAffected == 0)
{
if (rowThatCouldNotBeWritten.Errors != null)
{
rowThatCouldNotBeWritten.Row.RowError = SR.ExceptionMessageUpdateDataSetRowFailure;
rowThatCouldNotBeWritten.Status = UpdateStatus.SkipCurrentRow;
}
}
}
}
}

View File

@@ -0,0 +1,25 @@
namespace GZTW.Data
{
/// <summary>
/// Used with the Database.UpdateDataSet method. Provides control over behavior when the Data
/// Adapter's update command encounters an error.
/// </summary>
public enum UpdateBehavior
{
/// <summary>
/// No interference with the DataAdapter's Update command. If Update encounters
/// an error, the update stops. Additional rows in the Datatable are uneffected.
/// </summary>
Standard,
/// <summary>
/// If the DataAdapter's Update command encounters an error, the update will
/// continue. The Update command will try to update the remaining rows.
/// </summary>
Continue,
/// <summary>
/// If the DataAdapter encounters an error, all updated rows will be rolled back
/// </summary>
Transactional
}
}