Initial Commit
This commit is contained in:
266
Internal/DBMS.cs
Normal file
266
Internal/DBMS.cs
Normal file
@@ -0,0 +1,266 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Data.Common;
|
||||
|
||||
using System.Data.SqlClient;
|
||||
using System.Collections;
|
||||
using System.Data.SqlServerCe;
|
||||
using Sdaleo.Systems;
|
||||
using Devart.Data.PostgreSql;
|
||||
|
||||
namespace Sdaleo
|
||||
{
|
||||
/// <summary>
|
||||
/// This class is a Object factory wrapper class around our DBMS
|
||||
/// </summary>
|
||||
internal static class DBMS
|
||||
{
|
||||
/// <summary>
|
||||
/// Creates a Connection Object depending on the type of DBMS we are using
|
||||
/// </summary>
|
||||
/// <param name="dbsystem">the DBSystem you want parameters for</param>
|
||||
/// <param name="ConnectionStr">Must pass in a valid Connection String</param>
|
||||
/// <returns>a valid connection * Caller Must Dispose of the Object *, or null if system is not available</returns>
|
||||
internal static DbConnection CreateDbConnection(DBSystem dbsystem, string ConnectionStr)
|
||||
{
|
||||
DbConnection connection = null;
|
||||
if (!String.IsNullOrEmpty(ConnectionStr))
|
||||
{
|
||||
switch (dbsystem)
|
||||
{
|
||||
case DBSystem.SQL_SERVER:
|
||||
if(SystemAvailable.Check(dbsystem))
|
||||
connection = (DbConnection)new SqlConnection(ConnectionStr);
|
||||
break;
|
||||
|
||||
case DBSystem.SQL_CE:
|
||||
if (SystemAvailable.Check(dbsystem))
|
||||
connection = (DbConnection)new SqlCeConnection(ConnectionStr);
|
||||
break;
|
||||
|
||||
case DBSystem.ADVANTAGE:
|
||||
if (SystemAvailable.Check(dbsystem))
|
||||
connection = (DbConnection)new SqlCeConnection(ConnectionStr);
|
||||
break;
|
||||
|
||||
case DBSystem.CTREE:
|
||||
if (SystemAvailable.Check(dbsystem))
|
||||
connection = (DbConnection)new SqlCeConnection(ConnectionStr);
|
||||
break;
|
||||
|
||||
case DBSystem.MYSQL:
|
||||
if (SystemAvailable.Check(dbsystem))
|
||||
connection = (DbConnection)new SqlCeConnection(ConnectionStr);
|
||||
break;
|
||||
|
||||
case DBSystem.POSTGRES:
|
||||
if (SystemAvailable.Check(dbsystem))
|
||||
connection = (DbConnection)new PgSqlConnection(ConnectionStr);
|
||||
break;
|
||||
}
|
||||
}
|
||||
return connection;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a DataAdapter depending on the type of DBMS we are using
|
||||
/// </summary>
|
||||
/// <param name="dbsystem">the DBSystem you want a DataAdapter for</param>
|
||||
/// <param name="dbcommand">pass in a valid Command Object for the DBMS</param>
|
||||
/// <returns>a valid DataAdapter * Caller Must Dispose of the Object *, or null if system is not available</returns>
|
||||
internal static DbDataAdapter CreateDbDataAdapter(DBSystem dbsystem, DbCommand dbcommand)
|
||||
{
|
||||
DbDataAdapter dbDataAdapter = null;
|
||||
switch (dbsystem)
|
||||
{
|
||||
case DBSystem.SQL_SERVER:
|
||||
if (SystemAvailable.Check(dbsystem))
|
||||
dbDataAdapter = new SqlDataAdapter((SqlCommand) dbcommand);
|
||||
break;
|
||||
|
||||
case DBSystem.SQL_CE:
|
||||
if (SystemAvailable.Check(dbsystem))
|
||||
dbDataAdapter = new SqlCeDataAdapter((SqlCeCommand) dbcommand);
|
||||
break;
|
||||
|
||||
case DBSystem.ADVANTAGE:
|
||||
if (SystemAvailable.Check(dbsystem))
|
||||
dbDataAdapter = new SqlCeDataAdapter((SqlCeCommand)dbcommand);
|
||||
break;
|
||||
|
||||
case DBSystem.CTREE:
|
||||
if (SystemAvailable.Check(dbsystem))
|
||||
dbDataAdapter = new SqlCeDataAdapter((SqlCeCommand)dbcommand);
|
||||
break;
|
||||
|
||||
case DBSystem.MYSQL:
|
||||
if (SystemAvailable.Check(dbsystem))
|
||||
dbDataAdapter = new SqlCeDataAdapter((SqlCeCommand)dbcommand);
|
||||
break;
|
||||
|
||||
case DBSystem.POSTGRES:
|
||||
if (SystemAvailable.Check(dbsystem))
|
||||
dbDataAdapter = new PgSqlDataAdapter((PgSqlCommand)dbcommand);
|
||||
break;
|
||||
}
|
||||
return dbDataAdapter;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates an Error Object to be returned to the Caller, fills values depending on DBMS
|
||||
/// </summary>
|
||||
/// <param name="dbsystem">the DBSystem you want an Error for</param>
|
||||
/// <param name="e">the exception being thrown by the DBMS</param>
|
||||
/// <returns>a DBRetVal Object filled with the Error Data, or null if system is not available</returns>
|
||||
internal static DBRetVal CreateErrorDBRetVal(DBSystem dbsystem, Exception e)
|
||||
{
|
||||
DBRetVal retVal = null;
|
||||
switch (dbsystem)
|
||||
{
|
||||
case DBSystem.SQL_SERVER:
|
||||
{
|
||||
if (SystemAvailable.Check(dbsystem))
|
||||
{
|
||||
SqlException ex = e as SqlException;
|
||||
if (ex != null)
|
||||
retVal = new DBRetVal(ex.Number, ex.Message, ex.Errors);
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case DBSystem.SQL_CE:
|
||||
{
|
||||
if (SystemAvailable.Check(dbsystem))
|
||||
{
|
||||
SqlCeException ex = e as SqlCeException;
|
||||
if (ex != null)
|
||||
retVal = new DBRetVal(ex.NativeError, ex.Message, ex.Errors);
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case DBSystem.ADVANTAGE:
|
||||
{
|
||||
if (SystemAvailable.Check(dbsystem))
|
||||
{
|
||||
SqlCeException ex = e as SqlCeException;
|
||||
if (ex != null)
|
||||
retVal = new DBRetVal(ex.NativeError, ex.Message, ex.Errors);
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case DBSystem.CTREE:
|
||||
{
|
||||
if (SystemAvailable.Check(dbsystem))
|
||||
{
|
||||
SqlCeException ex = e as SqlCeException;
|
||||
if (ex != null)
|
||||
retVal = new DBRetVal(ex.NativeError, ex.Message, ex.Errors);
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case DBSystem.MYSQL:
|
||||
{
|
||||
if (SystemAvailable.Check(dbsystem))
|
||||
{
|
||||
SqlCeException ex = e as SqlCeException;
|
||||
if (ex != null)
|
||||
retVal = new DBRetVal(ex.NativeError, ex.Message, ex.Errors);
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case DBSystem.POSTGRES:
|
||||
{
|
||||
if (SystemAvailable.Check(dbsystem))
|
||||
{
|
||||
PgSqlException ex = e as PgSqlException;
|
||||
if (ex != null)
|
||||
retVal = new DBRetVal(0, ex.Message, null);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
return retVal;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a DBMS Specific Parameter Array from a DMBS Independent Parameter Array
|
||||
/// </summary>
|
||||
/// <param name="dbsystem">the DBSystem you want parameters for</param>
|
||||
/// <param name="parameters">a valid DBMSIndependent Param array</param>
|
||||
/// <returns>a DBMS Specific Parameter Array</returns>
|
||||
internal static DbParameter[] CreateDbParameter(DBSystem dbsystem, DBMSIndParameter[] parameters)
|
||||
{
|
||||
List<DbParameter> param_s = new List<DbParameter>();
|
||||
|
||||
// Convert the Parameters
|
||||
foreach (DBMSIndParameter parameter in parameters)
|
||||
{
|
||||
switch (dbsystem)
|
||||
{
|
||||
case DBSystem.SQL_SERVER:
|
||||
{
|
||||
if (SystemAvailable.Check(dbsystem))
|
||||
{
|
||||
param_s.Add(new SqlParameter(parameter.parameterName, parameter.Value));
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case DBSystem.SQL_CE:
|
||||
{
|
||||
if (SystemAvailable.Check(dbsystem))
|
||||
{
|
||||
param_s.Add(new SqlCeParameter(parameter.parameterName, parameter.Value));
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case DBSystem.ADVANTAGE:
|
||||
{
|
||||
if (SystemAvailable.Check(dbsystem))
|
||||
{
|
||||
param_s.Add(new SqlCeParameter(parameter.parameterName, parameter.Value));
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case DBSystem.CTREE:
|
||||
{
|
||||
if (SystemAvailable.Check(dbsystem))
|
||||
{
|
||||
param_s.Add(new SqlCeParameter(parameter.parameterName, parameter.Value));
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case DBSystem.MYSQL:
|
||||
{
|
||||
if (SystemAvailable.Check(dbsystem))
|
||||
{
|
||||
param_s.Add(new SqlCeParameter(parameter.parameterName, parameter.Value));
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case DBSystem.POSTGRES:
|
||||
{
|
||||
if (SystemAvailable.Check(dbsystem))
|
||||
{
|
||||
param_s.Add(new PgSqlParameter(parameter.parameterName, parameter.Value));
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Return the Parameter
|
||||
return param_s.ToArray();
|
||||
}
|
||||
}
|
||||
}
|
||||
109
Internal/ObjTool.cs
Normal file
109
Internal/ObjTool.cs
Normal file
@@ -0,0 +1,109 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Sdaleo
|
||||
{
|
||||
/// <summary>
|
||||
/// Useful Utilities around objects
|
||||
/// </summary>
|
||||
internal static class ObjTool
|
||||
{
|
||||
/// <summary>
|
||||
/// Returns true if passed in object is valid and is not empty
|
||||
/// </summary>
|
||||
/// <param name="oToValidate">an object to validate</param>
|
||||
/// <returns>true if valid, false otherwise</returns>
|
||||
internal static bool IsNotNullAndNotEmpty(object oToValidate)
|
||||
{
|
||||
if ((oToValidate != null) && (oToValidate.ToString() != String.Empty))
|
||||
return true;
|
||||
else
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Convert a string to an Object of Type T
|
||||
/// </summary>
|
||||
/// <typeparam name="T">Should be a System Type like string, bool, int32, double, decimal, etc...</typeparam>
|
||||
/// <param name="strToConvert">String Value to Convert</param>
|
||||
/// <returns>an converted Object of Type t, or T Default if error occured</returns>
|
||||
internal static T ConvertStringToObj<T>(string strToConvert)
|
||||
{
|
||||
|
||||
// Create a Default Type T
|
||||
T retVal = default(T);
|
||||
|
||||
try
|
||||
{
|
||||
#region Conversion
|
||||
|
||||
if (retVal is Char)
|
||||
{
|
||||
retVal = (T)((object)strToConvert[0]);
|
||||
}
|
||||
else if (retVal is String)
|
||||
{
|
||||
retVal = (T)((object)strToConvert);
|
||||
}
|
||||
else if (retVal is Decimal)
|
||||
{
|
||||
retVal = (T)((object)Decimal.Parse(strToConvert));
|
||||
}
|
||||
else if (retVal is Int32)
|
||||
{
|
||||
retVal = (T)((object)Int32.Parse(strToConvert));
|
||||
}
|
||||
else if (retVal is Int64)
|
||||
{
|
||||
retVal = (T)((object)Int64.Parse(strToConvert));
|
||||
}
|
||||
else if (retVal is Single)
|
||||
{
|
||||
retVal = (T)((object)Single.Parse(strToConvert));
|
||||
}
|
||||
else if (retVal is Double)
|
||||
{
|
||||
retVal = (T)((object)Double.Parse(strToConvert));
|
||||
}
|
||||
else if (retVal is Boolean)
|
||||
{
|
||||
retVal = (T)((object)Boolean.Parse(strToConvert));
|
||||
}
|
||||
else if (retVal is DateTime)
|
||||
{
|
||||
retVal = (T)((object)DateTime.Parse(strToConvert));
|
||||
}
|
||||
#if NET40
|
||||
else if (retVal is Guid)
|
||||
{
|
||||
retVal = (T)((object)Guid.Parse(strToConvert));
|
||||
}
|
||||
#endif
|
||||
else if (retVal is IntPtr)
|
||||
{
|
||||
retVal = (T)((object)Int32.Parse(strToConvert));
|
||||
}
|
||||
else if (retVal is UInt32)
|
||||
{
|
||||
retVal = (T)((object)UInt32.Parse(strToConvert));
|
||||
}
|
||||
else if (retVal is UInt64)
|
||||
{
|
||||
retVal = (T)((object)UInt64.Parse(strToConvert));
|
||||
}
|
||||
else
|
||||
{
|
||||
retVal = (T)((object)(strToConvert));
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
catch (Exception) { /* ignore */ }
|
||||
|
||||
// return T
|
||||
return retVal;
|
||||
}
|
||||
}
|
||||
}
|
||||
416
Internal/RegKey.cs
Normal file
416
Internal/RegKey.cs
Normal file
@@ -0,0 +1,416 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Microsoft.Win32;
|
||||
|
||||
namespace Sdaleo
|
||||
{
|
||||
#region RegKey Enums
|
||||
|
||||
internal enum HKEYRoot
|
||||
{
|
||||
ClassesRoot,
|
||||
CurrentUser,
|
||||
LocalMachine,
|
||||
}
|
||||
|
||||
internal enum KeySub
|
||||
{
|
||||
Software,
|
||||
Custom
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
/// <summary>
|
||||
/// Wrapper Class around Registry Functionallity,
|
||||
/// allows for easy reading/writing to the registry, especially HKEY_CURRENT_USER\Software
|
||||
/// ~If you use this class directly make sure to call dispose(),
|
||||
/// otherwise, use the Public Static Helper Functions to do the work for you
|
||||
/// </summary>
|
||||
internal class RegKey : IDisposable
|
||||
{
|
||||
private RegistryKey _RegKey;
|
||||
private bool _disposed = false;
|
||||
|
||||
#region Constructors
|
||||
|
||||
/// <summary>
|
||||
/// Opens the specified Key in CURRENT_USER\Software\Key.
|
||||
/// </summary>
|
||||
/// <param name="Key">Specify Key to Open</param>
|
||||
/// <param name="bReadOnly">Set to true to Open, false to Create if not Exists</param>
|
||||
internal RegKey(string Key, bool bReadOnly = true) : this(HKEYRoot.CurrentUser, KeySub.Software, Key, bReadOnly) { }
|
||||
|
||||
/// <summary>
|
||||
/// Use this to Open or Automatically Create a Registry Key
|
||||
/// </summary>
|
||||
/// <param name="root">specify registry root</param>
|
||||
/// <param name="sub">specify a sub or custom</param>
|
||||
/// <param name="Key">key you want to open / create </param>
|
||||
/// <param name="bReadOnly">true if you want to force only reading it</param>
|
||||
private RegKey(HKEYRoot root, KeySub sub, string Key, bool bReadOnly)
|
||||
{
|
||||
string KeyToOpen = String.Empty;
|
||||
if (sub == KeySub.Custom)
|
||||
KeyToOpen = Key;
|
||||
else
|
||||
KeyToOpen = sub.ToString() + "\\" + Key;
|
||||
|
||||
// Read Only Permission
|
||||
RegistryKeyPermissionCheck permission = RegistryKeyPermissionCheck.ReadSubTree;
|
||||
if (!bReadOnly)
|
||||
permission = RegistryKeyPermissionCheck.ReadWriteSubTree;
|
||||
|
||||
// Open or Create, if it doesn't exist and we have writable set
|
||||
switch (root)
|
||||
{
|
||||
case HKEYRoot.ClassesRoot:
|
||||
if (bReadOnly)
|
||||
_RegKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(KeyToOpen);
|
||||
else
|
||||
_RegKey = Microsoft.Win32.Registry.ClassesRoot.CreateSubKey(KeyToOpen, permission);
|
||||
break;
|
||||
|
||||
case HKEYRoot.CurrentUser:
|
||||
if (bReadOnly)
|
||||
_RegKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(KeyToOpen, permission);
|
||||
else
|
||||
_RegKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(KeyToOpen, permission);
|
||||
break;
|
||||
|
||||
case HKEYRoot.LocalMachine:
|
||||
if (bReadOnly)
|
||||
_RegKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(KeyToOpen, permission);
|
||||
else
|
||||
_RegKey = Microsoft.Win32.Registry.LocalMachine.CreateSubKey(KeyToOpen, permission);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Finalizer
|
||||
/// </summary>
|
||||
~RegKey()
|
||||
{
|
||||
#if NET40
|
||||
if (_RegKey != null)
|
||||
_RegKey.Dispose();
|
||||
#endif
|
||||
_RegKey = null;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region GetValue Registry Functions
|
||||
|
||||
/// <summary>
|
||||
/// Generic Registry KeyValue Getter Function
|
||||
/// </summary>
|
||||
/// <typeparam name="T">Should be a System Type like string, bool, int32, double, decimal, etc...</typeparam>
|
||||
/// <param name="strKeyValue">The Value to get from the Registry</param>
|
||||
/// <param name="DefaultValue">Default value to use if nothing was retrieved * Error occured *</param>
|
||||
/// <returns>Value found or Default Value</returns>
|
||||
internal T GetVal<T>(string strKeyValue, T DefaultValue)
|
||||
{
|
||||
T retVal = DefaultValue;
|
||||
try
|
||||
{
|
||||
if (_RegKey != null)
|
||||
{
|
||||
object keyvalue = _RegKey.GetValue(strKeyValue);
|
||||
string strvalue = string.Empty;
|
||||
if (ObjTool.IsNotNullAndNotEmpty(keyvalue))
|
||||
{
|
||||
#region First Handle the Value as a string
|
||||
|
||||
// Handle Multi-Strings
|
||||
if (keyvalue is object[])
|
||||
{
|
||||
string keyVal2 = string.Empty;
|
||||
string[] strVal2 = (string[])keyvalue;
|
||||
foreach (string str in strVal2)
|
||||
{
|
||||
keyVal2 += str;
|
||||
}
|
||||
strvalue = keyVal2;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Handle Single-Strings
|
||||
strvalue = keyvalue.ToString();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
// Now cast the Object Return type * Handle each object differently *
|
||||
retVal = ObjTool.ConvertStringToObj<T>(strvalue);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception) { /* ignore */ }
|
||||
return retVal;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Binary Registry KeyValue Getter Function
|
||||
/// </summary>
|
||||
/// <param name="strKeyValue">The Value to get from the Registry</param>
|
||||
/// <returns>an array of Bytes found in the Registry, or null if none found, or error occured</returns>
|
||||
internal byte[] GetVal(string strKeyValue)
|
||||
{
|
||||
byte[] retVal = null;
|
||||
try
|
||||
{
|
||||
string StringValue = GetVal<String>(strKeyValue, String.Empty);
|
||||
if (!String.IsNullOrEmpty(StringValue))
|
||||
{
|
||||
Byte[] ByteValue = new Byte[StringValue.Length];
|
||||
for (int i = 0; i < ByteValue.Length; ++i)
|
||||
{
|
||||
string strByte = Convert.ToString(StringValue[i]);
|
||||
ByteValue[i] = byte.Parse(strByte);
|
||||
}
|
||||
retVal = ByteValue;
|
||||
}
|
||||
}
|
||||
catch (Exception) { /* ignore */ }
|
||||
return retVal;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region SetValue Registry Functions
|
||||
|
||||
/// <summary>
|
||||
/// Generic Registry KeyValue Setter Function
|
||||
/// </summary>
|
||||
/// <typeparam name="T">Should be a System Type like string, bool, int32, double, decimal, etc...</typeparam>
|
||||
/// <param name="strKeyValue">The Value to write to in the Registry</param>
|
||||
/// <param name="Value">The Value to set to the Registry</param>
|
||||
/// <returns>true if successful, false otherwise</returns>
|
||||
internal bool SetVal<T>(string strKeyValue, T Value)
|
||||
{
|
||||
bool bRetVal = false;
|
||||
try
|
||||
{
|
||||
if (_RegKey != null)
|
||||
{
|
||||
if (Value is Int32)
|
||||
{
|
||||
_RegKey.SetValue(strKeyValue, Value, RegistryValueKind.DWord);
|
||||
}
|
||||
else if (Value is Int64)
|
||||
{
|
||||
_RegKey.SetValue(strKeyValue, Value, RegistryValueKind.QWord);
|
||||
}
|
||||
else
|
||||
{
|
||||
_RegKey.SetValue(strKeyValue, Value, RegistryValueKind.String);
|
||||
}
|
||||
bRetVal = true;
|
||||
}
|
||||
}
|
||||
catch (Exception) { /* ignore */ }
|
||||
return bRetVal;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Generic Registry KeyValue Setter Function
|
||||
/// </summary>
|
||||
/// <param name="strKeyValue">The Value to write to in the Registry</param>
|
||||
/// <param name="ByteValue">A binary array of bytes to write to the Registry</param>
|
||||
/// <returns>true if successful, false otherwise</returns>
|
||||
internal bool SetVal(string strKeyValue, byte[] ByteValue)
|
||||
{
|
||||
try
|
||||
{
|
||||
_RegKey.SetValue(strKeyValue, ByteValue, RegistryValueKind.Binary);
|
||||
return true;
|
||||
}
|
||||
catch (Exception) { /* ignore */ }
|
||||
return false;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Public Static Helper Functions
|
||||
|
||||
/// <summary>
|
||||
/// Generic Static Registry Writer Function * Allows writing to HKEY\CURRENT_USER\SOFTWARE *
|
||||
/// </summary>
|
||||
/// <typeparam name="T">Should be a System Type like string, bool, int32, double, decimal, etc...</typeparam>
|
||||
/// <param name="SubKey">SubKey i.e. Microsoft, Microsoft\Windows</param>
|
||||
/// <param name="KeyValue">Value to write to</param>
|
||||
/// <param name="Value">Value to write</param>
|
||||
/// <returns>true if successful, false otherwise</returns>
|
||||
internal static bool SetKey<T>(String SubKey, String KeyValue, T Value)
|
||||
{
|
||||
bool bRetVal = false;
|
||||
using (RegKey reg = new RegKey(HKEYRoot.CurrentUser, KeySub.Software, SubKey, false))
|
||||
{
|
||||
bRetVal = reg.SetVal<T>(KeyValue, Value);
|
||||
}
|
||||
return bRetVal;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Generic Static Registry Writer For Binary Function * Allows writing to HKEY\CURRENT_USER\SOFTWARE *
|
||||
/// </summary>
|
||||
/// <param name="SubKey">SubKey i.e. Microsoft, Microsoft\Windows</param>
|
||||
/// <param name="KeyValue">Value to write to</param>
|
||||
/// <param name="ByteValue">Binary Value to write</param>
|
||||
/// <returns>true if successful, false otherwise</returns>
|
||||
internal static bool SetKey(String SubKey, String KeyValue, byte[] ByteValue)
|
||||
{
|
||||
bool bRetVal = false;
|
||||
using (RegKey reg = new RegKey(HKEYRoot.CurrentUser, KeySub.Software, SubKey, false))
|
||||
{
|
||||
bRetVal = reg.SetVal(KeyValue, ByteValue);
|
||||
}
|
||||
return bRetVal;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Generic Static Registry Writer Function * Allows writing to any key *
|
||||
/// </summary>
|
||||
/// <typeparam name="T">Should be a System Type like string, bool, int32, double, decimal, etc...</typeparam>
|
||||
/// <param name="rootKey">RootKey as defined in this Class</param>
|
||||
/// <param name="SubKey">SubKey i.e. Software, Software\Microsoft</param>
|
||||
/// <param name="KeyValue">Value to write to</param>
|
||||
/// <param name="Value">Value to write</param>
|
||||
/// <returns>true if successful, false otherwise</returns>
|
||||
internal static bool SetKey<T>(HKEYRoot rootKey, String SubKey, String KeyValue, T Value)
|
||||
{
|
||||
bool bRetVal = false;
|
||||
using (RegKey reg = new RegKey(rootKey, KeySub.Custom, SubKey, false))
|
||||
{
|
||||
bRetVal = reg.SetVal<T>(KeyValue, Value);
|
||||
}
|
||||
return bRetVal;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Generic Static Registry Writer For Binary Function * Allows writing to any key *
|
||||
/// </summary>
|
||||
/// <param name="rootKey">RootKey as defined in this Class</param>
|
||||
/// <param name="SubKey">SubKey i.e. Software, Software\Microsoft</param>
|
||||
/// <param name="KeyValue">Value to write to</param>
|
||||
/// <param name="ByteValue">Binary Value to write</param>
|
||||
/// <returns>true if successful, false otherwise</returns>
|
||||
internal static bool SetKey(HKEYRoot rootKey, String SubKey, String KeyValue, byte[] ByteValue)
|
||||
{
|
||||
bool bRetVal = false;
|
||||
using (RegKey reg = new RegKey(rootKey, KeySub.Custom, SubKey, false))
|
||||
{
|
||||
bRetVal = reg.SetVal(KeyValue, ByteValue);
|
||||
}
|
||||
return bRetVal;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Generic Static Registry Reader Function * Allows reading from HKEY\CURRENT_USER\SOFTWARE *
|
||||
/// </summary>
|
||||
/// <typeparam name="T">Should be a System Type like string, bool, int32, double, decimal, etc...</typeparam>
|
||||
/// <param name="SubKey">SubKey i.e. Microsoft, Microsoft\Windows</param>
|
||||
/// <param name="KeyValue">Value to write to</param>
|
||||
/// <param name="DefaultValue">Default Value to return if none found or error occured</param>
|
||||
/// <returns>true if successful, false otherwise</returns>
|
||||
internal static T GetKey<T>(String SubKey, String KeyValue, T DefaultValue)
|
||||
{
|
||||
T tRetVal = default(T);
|
||||
using (RegKey reg = new RegKey(HKEYRoot.CurrentUser, KeySub.Software, SubKey, true))
|
||||
{
|
||||
tRetVal = reg.GetVal<T>(KeyValue, DefaultValue);
|
||||
}
|
||||
return tRetVal;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Generic Static Registry Reader For Binary Function * Allows reading from HKEY\CURRENT_USER\SOFTWARE *
|
||||
/// </summary>
|
||||
/// <param name="SubKey">SubKey i.e. Microsoft, Microsoft\Windows</param>
|
||||
/// <param name="KeyValue">Value to write to</param>
|
||||
/// <returns>true if successful, false otherwise</returns>
|
||||
internal static Byte[] GetKey(String SubKey, String KeyValue)
|
||||
{
|
||||
Byte[] retByte = null;
|
||||
using (RegKey reg = new RegKey(HKEYRoot.CurrentUser, KeySub.Software, SubKey, true))
|
||||
{
|
||||
retByte = reg.GetVal(KeyValue);
|
||||
}
|
||||
return retByte;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Generic Static Registry Reader Function * Allows reading from any key *
|
||||
/// </summary>
|
||||
/// <typeparam name="T">Should be a System Type like string, bool, int32, double, decimal, etc...</typeparam>
|
||||
/// <param name="rootKey">RootKey as defined in this Class</param>
|
||||
/// <param name="SubKey">SubKey i.e. Software, Software\Microsoft</param>
|
||||
/// <param name="KeyValue">Value to write to</param>
|
||||
/// <param name="DefaultValue">Default Value to return if none found or error occured</param>
|
||||
/// <returns>true if successful, false otherwise</returns>
|
||||
internal static T GetKey<T>(HKEYRoot rootKey, String SubKey, String KeyValue, T DefaultValue)
|
||||
{
|
||||
T tRetVal = default(T);
|
||||
using (RegKey reg = new RegKey(rootKey, KeySub.Custom, SubKey, true))
|
||||
{
|
||||
tRetVal = reg.GetVal<T>(KeyValue, DefaultValue);
|
||||
}
|
||||
return tRetVal;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Generic Static Registry Reader For Binary Function * Allows reading from any key *
|
||||
/// </summary>
|
||||
/// <typeparam name="T">Should be a System Type like string, bool, int32, double, decimal, etc...</typeparam>
|
||||
/// <param name="rootKey">RootKey as defined in this Class</param>
|
||||
/// <param name="SubKey">SubKey i.e. Software, Software\Microsoft</param>
|
||||
/// <param name="KeyValue">Value to write to</param>
|
||||
/// <returns>true if successful, false otherwise</returns>
|
||||
internal static Byte[] GetKey(HKEYRoot rootKey, String SubKey, String KeyValue)
|
||||
{
|
||||
Byte[] retByte = null;
|
||||
using (RegKey reg = new RegKey(rootKey, KeySub.Custom, SubKey, true))
|
||||
{
|
||||
retByte = reg.GetVal(KeyValue);
|
||||
}
|
||||
return retByte;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region IDisposable Members
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Dispose(true);
|
||||
|
||||
// Use SupressFinalize in case a subclass
|
||||
// of this type implements a finalizer
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
protected virtual void Dispose(bool disposing)
|
||||
{
|
||||
if (!_disposed)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
#if NET40
|
||||
if (_RegKey != null)
|
||||
_RegKey.Dispose();
|
||||
#endif
|
||||
}
|
||||
|
||||
// Indicate that the instance has been disposed.
|
||||
_RegKey = null;
|
||||
_disposed = true;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
462
Internal/SQLParser.cs
Normal file
462
Internal/SQLParser.cs
Normal file
@@ -0,0 +1,462 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Diagnostics;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
/// <summary>
|
||||
/// MySQLCommands are embedded in SQL Scripts as follows:
|
||||
///--# [Command] [Version] [Arg1] [Arg2] ... [Arg3]
|
||||
///--#
|
||||
///~ Serves as the Command End Marker!
|
||||
///-- Possible Commands are, PRE_CREATE,CREATE,POST_CREATE,PRE_ALTER,ALTER,POST_ALTER,PRE_DROP,DROP,POST_DROP,RENAME
|
||||
///-- Command Execution is as follows.
|
||||
///
|
||||
///-- CREATE must exists.
|
||||
///-- For New Install: *Script ID does not exist* -- WILL ALWAYS TAKE ONLY LATEST VERSION for CREATE, runs PRE-CREATEs and POST-CREATEs accordingly
|
||||
///-- PRE-CREATE, CREATE, POST-CREATE (If you want nothing done, leave command blank)
|
||||
///-- Allow Versions to use *, so that we can say for all [0.*.*] call this PRE-CREATE, or POST-CREATE
|
||||
///
|
||||
///-- For Update Install: *Script ID exists* - Will check db where to start and execute until to highest version of CREATE was reached
|
||||
///-- PRE-DROP, DROP, POST-DROP, PRE-RENAME, RENAME, POST-RENAME, PRE-ALTER, ALTER, POST-ALTER, for each respective version
|
||||
///
|
||||
///-- Versioning is done as follows:
|
||||
/// (Major version).(Minor version).(Revision number)
|
||||
///
|
||||
/// MySQLIdentifiers are embedded in SQL Scripts as follows:
|
||||
///--$ [Identifier] [Value], Identifier structure
|
||||
///
|
||||
///--$ [ScriptId] [Guid]!
|
||||
///-- Each script is versioned on it's own, so that is what we store in the db.
|
||||
///-- Give each script a UNIQUE GUID.
|
||||
///-- We will then store the ScriptID guid in the versioning table, along side the highest version of the script that most recently ran!,
|
||||
///-- ~this way we can always know if something has to be done for each database object,
|
||||
/// </summary>
|
||||
namespace Sdaleo.Internal
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public enum MySQLCommandType
|
||||
{
|
||||
PRE_CREATE,
|
||||
CREATE,
|
||||
POST_CREATE,
|
||||
PRE_ALTER,
|
||||
ALTER,
|
||||
POST_ALTER,
|
||||
PRE_DROP,
|
||||
DROP,
|
||||
POST_DROP,
|
||||
PRE_RENAME,
|
||||
RENAME,
|
||||
POST_RENAME,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Custom SQL Commands that are part of an SQL Script.
|
||||
/// They start as follows:
|
||||
/// --# [Command] [Version] [Arg1] [Arg2] ... [Arg3]
|
||||
///
|
||||
/// and end as follows:
|
||||
/// --#
|
||||
/// ~Serves as the Command End Marker!
|
||||
/// Everything in between is SQL.
|
||||
/// </summary>
|
||||
internal class MySQLCommand
|
||||
{
|
||||
#region Members N' Properties
|
||||
|
||||
// Line Specifics
|
||||
internal uint Line_CommandStart { get; private set; }
|
||||
internal uint Line_CommandEnd { get; private set; }
|
||||
internal string[] SQLScriptBlock { get; private set; }
|
||||
|
||||
// Command Specifics
|
||||
internal MySQLCommandType Command { get; private set; }
|
||||
internal string Version
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_Versioning != null)
|
||||
return _Versioning.Version;
|
||||
else
|
||||
return String.Empty;
|
||||
}
|
||||
}
|
||||
internal Versioning _Versioning = null;
|
||||
internal string[] Arguments = null;
|
||||
|
||||
/// <summary>
|
||||
/// Returns true if there are Lines between CommandStart and CommandEnd,
|
||||
/// this indicates that it contains sql in between
|
||||
/// </summary>
|
||||
internal bool ContainsSQLScript
|
||||
{
|
||||
get
|
||||
{
|
||||
if (Line_CommandStart >= Line_CommandEnd)
|
||||
return false;
|
||||
else if ((Line_CommandStart + 1) == Line_CommandEnd)
|
||||
return false;
|
||||
else if ((SQLScriptBlock != null) && (SQLScriptBlock.Length > 0))
|
||||
return true;
|
||||
else
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Internal Execute
|
||||
|
||||
internal DBError ExecuteScriptBlock(IConnectDb credential)
|
||||
{
|
||||
DBError dbError = DBError.Create("No Script Block to Execute");
|
||||
if ((SQLScriptBlock != null) && (SQLScriptBlock.Length > 0))
|
||||
{
|
||||
foreach (string sqlLine in SQLScriptBlock)
|
||||
{
|
||||
DB db = DB.Create(credential);
|
||||
dbError = db.ExecuteNonQuery(sqlLine);
|
||||
if (dbError.ErrorOccured)
|
||||
break;
|
||||
}
|
||||
}
|
||||
return dbError;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Construction
|
||||
|
||||
/// <summary>
|
||||
/// Used to Parse a SQLCommand from an SQL Script
|
||||
/// </summary>
|
||||
/// <param name="Line_CommandStart">Specifies the line of code where the Command is located --# [Command] [Version] [Arg1] [Arg2] ... [Arg3] </param>
|
||||
/// <param name="Line_CommandStartString">The String of Line_CommandStart, that contains all the Command Values the --# [Command] [Version] [Arg1] [Arg2] ... [Arg3] string</param>
|
||||
/// <param name="Line_CommandEnd">Specifies the line of code where the Command ends --#</param>
|
||||
internal MySQLCommand(uint Line_CommandStart, string Line_CommandStartString, uint Line_CommandEnd, string[] sqlScriptBlock)
|
||||
{
|
||||
this.Line_CommandStart = Line_CommandStart;
|
||||
this.Line_CommandEnd = Line_CommandEnd;
|
||||
ParseLine_CommandStartString(Line_CommandStartString);
|
||||
this.SQLScriptBlock = sqlScriptBlock;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parses a CommmandStartString and fills the values for this class
|
||||
/// </summary>
|
||||
/// <param name="LineCommandStartString">a line that contains a CommandStartString</param>
|
||||
private void ParseLine_CommandStartString(string LineCommandStartString)
|
||||
{
|
||||
/// --# [Command] [Version] [Arg1] [Arg2] ... [Arg3]
|
||||
/// --# [Create] [1.0.0] [Arg1] [Arg2]
|
||||
Regex rx = new Regex(@"\[([\w\a-\?\.\*\+]+)\]");
|
||||
MatchCollection matches = rx.Matches(LineCommandStartString);
|
||||
if (matches.Count < 2)
|
||||
throw new ArgumentException("LineIdentifierString is Invalid");
|
||||
|
||||
// Get the Command and Command Version
|
||||
string m1 = matches[0].ToString().Trim(new char[] { '[', ']' });
|
||||
string m2 = matches[1].ToString().Trim(new char[] { '[', ']' });
|
||||
this.Command = (MySQLCommandType)Enum.Parse(typeof(MySQLCommandType), m1.ToUpper());
|
||||
this._Versioning = new Versioning(m2);
|
||||
|
||||
// Get Optional Arguments
|
||||
int nArguments = matches.Count - 2;
|
||||
if (nArguments > 0)
|
||||
{
|
||||
Arguments = new string[nArguments];
|
||||
for (int i = 0; i < nArguments; ++i)
|
||||
Arguments[i] = matches[2 + i].ToString().Trim(new char[] { '[', ']' });
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Internal Statics
|
||||
|
||||
internal const string IDENTIFY_SQLSCRIPT_COMMAND = "--#";
|
||||
|
||||
/// <summary>
|
||||
/// Returns true if the passed in line is a MySQLCommandStartLine
|
||||
/// </summary>
|
||||
/// <param name="line">line to check</param>
|
||||
/// <returns>true if MySQLCommandStartLine, false otherwise</returns>
|
||||
internal static bool IsMySQLCommandStartLine(string line)
|
||||
{
|
||||
string lineTrimed = line.Trim();
|
||||
if (lineTrimed.StartsWith(IDENTIFY_SQLSCRIPT_COMMAND) && lineTrimed.Length != IDENTIFY_SQLSCRIPT_COMMAND.Length)
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns ture if the passed in line is a MySQLCommandEndLine
|
||||
/// </summary>
|
||||
/// <param name="line">line to check</param>
|
||||
/// <returns>true if MySQLCommandEndLine, false otherwise</returns>
|
||||
internal static bool IsMySQLCommandEndLine(string line)
|
||||
{
|
||||
string lineTrimed = line.Trim();
|
||||
if (lineTrimed.StartsWith(IDENTIFY_SQLSCRIPT_COMMAND) && lineTrimed.Length == IDENTIFY_SQLSCRIPT_COMMAND.Length)
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public enum MySQLIdentifierType
|
||||
{
|
||||
SCRIPTID,
|
||||
SCRIPTVERSION,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Custom SQL Identifiers that are part of an SQL Script.
|
||||
/// They start as follows:
|
||||
/// --$ [Identifier] [Value]
|
||||
/// </summary>
|
||||
public class MySQLIdentifier
|
||||
{
|
||||
#region Members N' Properties
|
||||
|
||||
// Line Specifics
|
||||
internal uint Line_IdentifierStart { get; private set; }
|
||||
|
||||
// Identifier Specifics
|
||||
internal MySQLIdentifierType Identity { get; private set; }
|
||||
internal string Value { get; private set; }
|
||||
|
||||
#endregion
|
||||
|
||||
#region Construction
|
||||
|
||||
/// <summary>
|
||||
/// Used to Parse a SQLCommand from an SQL Script
|
||||
/// </summary>
|
||||
/// <param name="Line_Identifier">Specifies the line of code where the Identifier is located --$ [Identifier] [Value] </param>
|
||||
/// <param name="Line_IdentifierString">The String of Line_IdentifierString, that contains all the Identifier Values the --$ [Identifier] [Value] string</param>
|
||||
internal MySQLIdentifier(uint Line_IdentifierStart, string Line_IdentifierString)
|
||||
{
|
||||
this.Line_IdentifierStart = Line_IdentifierStart;
|
||||
ParseLine_IndentifierStartString(Line_IdentifierString);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parses a LineIdentifierString and fills the values for this class
|
||||
/// </summary>
|
||||
/// <param name="LineIdentifierString">a line that contains a LineIdentifierString</param>
|
||||
private void ParseLine_IndentifierStartString(string LineIdentifierString)
|
||||
{
|
||||
/// --$ [Identifier] [Value]
|
||||
/// --$ [ScriptID] [12312-312321-3213]
|
||||
Regex rx = new Regex(@"\[([\w\a-\?\.\*\+]+)\]");
|
||||
MatchCollection matches = rx.Matches(LineIdentifierString);
|
||||
if (matches.Count < 2)
|
||||
throw new ArgumentException("LineIdentifierString is Invalid");
|
||||
|
||||
// Get the Identity and Value
|
||||
string m1 = matches[0].ToString().Trim(new char[] { '[', ']' });
|
||||
string m2 = matches[1].ToString().Trim(new char[] { '[', ']' });
|
||||
this.Identity = (MySQLIdentifierType)Enum.Parse(typeof(MySQLIdentifierType), m1.ToUpper());
|
||||
this.Value = m2;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Internal Statics
|
||||
|
||||
internal const string IDENTIFY_SQLSCRIPT_IDENTIFIER = "--$";
|
||||
|
||||
/// <summary>
|
||||
/// Returns true if the passed in line is a MySQLIdentifier
|
||||
/// </summary>
|
||||
/// <param name="line">line to check</param>
|
||||
/// <returns>true if MySQLIdentifier, false otherwise</returns>
|
||||
internal static bool IsMySQLIdentifier(string line)
|
||||
{
|
||||
string lineTrimed = line.Trim();
|
||||
if (lineTrimed.StartsWith(IDENTIFY_SQLSCRIPT_IDENTIFIER) && lineTrimed.Length != IDENTIFY_SQLSCRIPT_IDENTIFIER.Length)
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Helper class that parses an SQL Script for Commands and Identifiers,
|
||||
/// for processing.
|
||||
/// </summary>
|
||||
internal static class SQLParser
|
||||
{
|
||||
/// <summary>
|
||||
/// Iterates thru the Identifiers and returns the value of the first identifier that matches the identity.
|
||||
/// </summary>
|
||||
/// <returns>the value of the first matched identity, String.Empty if not found</returns>
|
||||
internal static string GetValueForFirstFoundMySQLIdentifierType(MySQLIdentifierType Identity, MySQLIdentifier[] identifiers)
|
||||
{
|
||||
if (identifiers != null && identifiers.Length > 0)
|
||||
{
|
||||
foreach (MySQLIdentifier identifier in identifiers)
|
||||
{
|
||||
if (identifier.Identity == Identity)
|
||||
return identifier.Value;
|
||||
}
|
||||
}
|
||||
return String.Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parses an SQLScript for MySQLCommand Objects
|
||||
/// </summary>
|
||||
/// <param name="sqlscript">a string array from an sql script</param>
|
||||
/// <param name="commands">all MySQLCommand objects found, if any, otherwise, empty []</param>
|
||||
/// <param name="identifiers">all MySQLIdentifier objects found, if any, otherwise, empty []</param>
|
||||
internal static void ParseSQLScriptForMySQLCommandsAndIdentifiers(string[] sqlscript, out MySQLCommand[] commands, out MySQLIdentifier[] identifiers)
|
||||
{
|
||||
// Result set
|
||||
commands = null;
|
||||
identifiers = null;
|
||||
List<MySQLCommand> CommandsFound = new List<MySQLCommand>();
|
||||
List<MySQLIdentifier> IdentifiersFound = new List<MySQLIdentifier>();
|
||||
|
||||
// intermediary variables
|
||||
int nStartLine = -1;
|
||||
string strStartLine = String.Empty;
|
||||
|
||||
// Iterate thru all lines
|
||||
for (int i = 0; i < sqlscript.Length; ++i)
|
||||
{
|
||||
string curLine = sqlscript[i];
|
||||
|
||||
/// Parse for
|
||||
/// --$ [Identifier] [Value]
|
||||
if (MySQLIdentifier.IsMySQLIdentifier(curLine))
|
||||
{
|
||||
IdentifiersFound.Add(new MySQLIdentifier((uint)i, curLine));
|
||||
continue;
|
||||
}
|
||||
|
||||
/// Parse for
|
||||
/// --# [Command] [Version] [Arg1] [Arg2] ... [Arg3]
|
||||
/// ...
|
||||
/// --#
|
||||
if (MySQLCommand.IsMySQLCommandStartLine(curLine))
|
||||
{
|
||||
nStartLine = i;
|
||||
strStartLine = curLine;
|
||||
continue;
|
||||
}
|
||||
else if (MySQLCommand.IsMySQLCommandEndLine(curLine))
|
||||
{
|
||||
// Something is wrong with the script!
|
||||
if ((nStartLine == -1) || String.IsNullOrEmpty(strStartLine))
|
||||
{
|
||||
Debug.Assert(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (nStartLine == i || nStartLine == i + 1)
|
||||
{
|
||||
Debug.Assert(false); // There is no SQLCodeBlock! = something is wrong with the script
|
||||
nStartLine = -1;
|
||||
strStartLine = String.Empty;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Create the SQLScriptBlock
|
||||
List<String> sqlScriptBlock = new List<String>();
|
||||
for (int j = nStartLine; j < i; ++j)
|
||||
sqlScriptBlock.Add(sqlscript[j]);
|
||||
|
||||
// Convert the SQLScriptBlock into Executable Code
|
||||
string[] executableSQLCodeBlock = GetExecutableSqlTextFromSQLScriptBlock(sqlScriptBlock.ToArray());
|
||||
|
||||
// Create the Commands Object that now contains the Executable SQL Code
|
||||
CommandsFound.Add(new MySQLCommand((uint)nStartLine, strStartLine, (uint)i, executableSQLCodeBlock));
|
||||
nStartLine = -1;
|
||||
strStartLine = String.Empty;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// Delegate to Propertly Sort the MySQLCommands, First, by Command, then by Version
|
||||
System.Comparison<MySQLCommand> comparer = delegate(MySQLCommand x, MySQLCommand y)
|
||||
{
|
||||
// First Compare the Command,
|
||||
int nCompare = x.Command.CompareTo(y.Command);
|
||||
|
||||
// If equal, compare the versioning
|
||||
if(nCompare == 0)
|
||||
nCompare = x._Versioning.CompareTo(y._Versioning);
|
||||
|
||||
return nCompare;
|
||||
};
|
||||
CommandsFound.Sort(comparer);
|
||||
|
||||
// Pass out Result set
|
||||
commands = CommandsFound.ToArray();
|
||||
identifiers = IdentifiersFound.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Use this to Parse an SQL Script Block (a block of code, contained inside a MySQLCommand.
|
||||
/// It Ignores Comment Lines, and also breaks out the SQL Script by GO Statements.
|
||||
/// </summary>
|
||||
/// <param name="sqlscriptBlock">an unprocessed Script block from an SQL Script</param>
|
||||
/// <returns>a ADO.Net Friend sql script block that can be executed</returns>
|
||||
internal static string[] GetExecutableSqlTextFromSQLScriptBlock(string[] sqlscriptBlock)
|
||||
{
|
||||
|
||||
bool bIsInCommentMode = false;
|
||||
StringBuilder sbSQLLines = new StringBuilder();
|
||||
List<String> sbSQLBrokenOut = new List<String>();
|
||||
foreach (string line in sqlscriptBlock)
|
||||
{
|
||||
// Let's deal with comments, which allows us to put comments in our SQL Scripts
|
||||
if (bIsInCommentMode)
|
||||
{
|
||||
if (line.StartsWith("*/") || line.EndsWith("*/"))
|
||||
bIsInCommentMode = false;
|
||||
continue;
|
||||
}
|
||||
else if (line.StartsWith("/*") && !line.EndsWith("*/"))
|
||||
{
|
||||
bIsInCommentMode = true; // skip lines until end of comment
|
||||
continue;
|
||||
}
|
||||
else if (line.StartsWith("/*") && line.EndsWith("*/"))
|
||||
continue; // skip single comment line
|
||||
else if (line.StartsWith("--"))
|
||||
continue; // skip single comment line
|
||||
|
||||
// We break out GO stmts to allow execution seperatly
|
||||
if ((line.Length == 2) && line.ToUpper().StartsWith("GO"))
|
||||
{
|
||||
if (sbSQLLines.Length > 0)
|
||||
sbSQLBrokenOut.Add(sbSQLLines.ToString());
|
||||
sbSQLLines.Remove(0, sbSQLLines.Length); // clear sbSQLLines
|
||||
continue;
|
||||
}
|
||||
|
||||
// Ready to use the SQL Line
|
||||
sbSQLLines.Append((line + " "));
|
||||
}
|
||||
|
||||
if (sbSQLLines.Length > 0)
|
||||
sbSQLBrokenOut.Add(sbSQLLines.ToString());
|
||||
|
||||
// Return the 'GO' Broken out SQL Script Block
|
||||
return sbSQLBrokenOut.ToArray();
|
||||
}
|
||||
}
|
||||
}
|
||||
31
Internal/SecuredPassword.cs
Normal file
31
Internal/SecuredPassword.cs
Normal file
@@ -0,0 +1,31 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace Sdaleo
|
||||
{
|
||||
/// <summary>
|
||||
/// This class allows us to Secure a Password from spying eyes
|
||||
/// * Only allow specific callers to actually retrieve the password unencrypted *
|
||||
/// </summary>
|
||||
internal class SecuredPassword
|
||||
{
|
||||
private string _Password;
|
||||
internal string Password
|
||||
{
|
||||
get
|
||||
{
|
||||
return _Password;
|
||||
//if (SecureDAL.IsInternal)
|
||||
// return _Password;
|
||||
//else
|
||||
// return Encryption.EncryptText(_Password);
|
||||
}
|
||||
set
|
||||
{
|
||||
_Password = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
562
Internal/UDL.cs
Normal file
562
Internal/UDL.cs
Normal file
@@ -0,0 +1,562 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.IO;
|
||||
|
||||
namespace Sdaleo
|
||||
{
|
||||
/// <summary>
|
||||
/// Core Class to Parse / Generate a UDL String
|
||||
/// </summary>
|
||||
internal class UDL : ICloneable, IComparable
|
||||
{
|
||||
#region Internal ReadWrite Properties
|
||||
|
||||
/// <summary>
|
||||
/// Credential Object can point to different databases
|
||||
/// </summary>
|
||||
internal string DataBase { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Default Connection Timeout
|
||||
/// </summary>
|
||||
internal const uint DEFAULT_CONNECTION_TIMEOUT_UDL = 15;
|
||||
|
||||
/// <summary>
|
||||
/// Allow Caller to set connection timeout
|
||||
/// </summary>
|
||||
internal uint ConnectionTimeout = DEFAULT_CONNECTION_TIMEOUT_UDL;
|
||||
|
||||
/// <summary>
|
||||
/// Defaulted to 'true'. When set uses the ConnectionTimeout value, when false it won't
|
||||
/// </summary>
|
||||
internal bool UseConnectionTimeout = true;
|
||||
|
||||
// * Secured Password *
|
||||
private SecuredPassword _Password = new SecuredPassword();
|
||||
|
||||
/// <summary>
|
||||
/// Secured Password Object that stores the password in a secure manner in memory
|
||||
/// </summary>
|
||||
internal string Password
|
||||
{
|
||||
get
|
||||
{
|
||||
return _Password.Password;
|
||||
}
|
||||
private set
|
||||
{
|
||||
_Password.Password = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
internal string DataSource
|
||||
{
|
||||
get
|
||||
{
|
||||
if (!String.IsNullOrEmpty(ServerAddress) && !String.IsNullOrEmpty(InstanceName))
|
||||
return ServerAddress + "\\" + InstanceName;
|
||||
else if (!String.IsNullOrEmpty(ServerAddress))
|
||||
return ServerAddress;
|
||||
else
|
||||
return string.Empty;
|
||||
}
|
||||
private set
|
||||
{
|
||||
if (!String.IsNullOrEmpty(value))
|
||||
{
|
||||
string[] values = value.Split('\\');
|
||||
if (values.Length == 2)
|
||||
{
|
||||
ServerAddress = values[0];
|
||||
InstanceName = values[1];
|
||||
}
|
||||
else if (value.Length > 2)
|
||||
{
|
||||
int nIndx = value.LastIndexOf('\\');
|
||||
ServerAddress = value.Substring(0, nIndx);
|
||||
InstanceName = value.Substring(nIndx + 1);
|
||||
}
|
||||
else
|
||||
{
|
||||
ServerAddress = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Internal ReadOnly Properties
|
||||
|
||||
#region ReadOnly String Getters
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
internal string Username { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
internal string ServerAddress { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
internal string InstanceName { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
internal string IntegratedSecurity { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
internal string AttachDBFilename { get; private set; }
|
||||
|
||||
#endregion
|
||||
|
||||
#region ReadOnly Bool Getters
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
internal bool TrustedConnection { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
internal bool PersistSecurityInfo { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
internal bool UserInstance { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
internal bool Encrypt { get; private set; }
|
||||
|
||||
#endregion
|
||||
|
||||
#endregion
|
||||
|
||||
#region Constructors
|
||||
|
||||
/// <summary>
|
||||
/// Construction (Set all UDL Settings via Connection String)
|
||||
/// </summary>
|
||||
/// <param name="ConnectionString">Pass in a valid Connection String To correctly instantiate the UDL Object</param>
|
||||
internal UDL(String ConnectionString)
|
||||
{
|
||||
Parse(ConnectionString);
|
||||
}
|
||||
|
||||
#region SQL CE Constructors
|
||||
|
||||
/// <summary>
|
||||
/// Construction SQL CE (Set common UDL Settings for SQL CE)
|
||||
/// </summary>
|
||||
/// <param name="path"></param>
|
||||
/// <param name="filename"></param>
|
||||
/// <param name="Password"></param>
|
||||
internal UDL(string FileNameNPath, string Password)
|
||||
{
|
||||
this.DataSource = FileNameNPath;
|
||||
UseConnectionTimeout = false;
|
||||
if (!String.IsNullOrEmpty(Password))
|
||||
{
|
||||
this.Password = Password;
|
||||
this.Encrypt = true;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region SQL Server Constructors
|
||||
|
||||
/// <summary>
|
||||
/// Construction SQL Server (Using SQL Login Credential)
|
||||
/// </summary>
|
||||
/// <param name="DataBase">Name of Database To Use</param>
|
||||
/// <param name="Username">Username to Connect With</param>
|
||||
/// <param name="Password">Password to Connect With</param>
|
||||
/// <param name="ServerAddress">ServerAddress to use as DataSource</param>
|
||||
/// <param name="InstanceName">Name of Instance to use as DataSource</param>
|
||||
internal UDL(string DataBase, string Username, string Password, string ServerAddress, string InstanceName)
|
||||
{
|
||||
this.DataBase = DataBase.Trim();
|
||||
this.Username = Username.Trim();
|
||||
this.Password = Password;
|
||||
this.ServerAddress = (String.IsNullOrEmpty(ServerAddress)) ? "." : ServerAddress.Trim().ToUpper();
|
||||
this.InstanceName = InstanceName.Trim().ToUpper();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Construction SQL Server (Set common UDL Settings for SQL Server)
|
||||
/// </summary>
|
||||
/// <param name="DataBase">Name of Database To Use</param>
|
||||
/// <param name="Username">Username to Connect With</param>
|
||||
/// <param name="Password">Password to Connect With</param>
|
||||
/// <param name="ServerAddress">ServerAddress to use as DataSource</param>
|
||||
/// <param name="InstanceName">Name of Instance to use as DataSource</param>
|
||||
/// <param name="TrustedConnection">Set to True to use Windows Authentication instead of SQL Auth</param>
|
||||
internal UDL(string DataBase, string Username, string Password, string ServerAddress, string InstanceName, bool TrustedConnection)
|
||||
{
|
||||
this.DataBase = DataBase.Trim();
|
||||
this.Username = Username.Trim();
|
||||
this.Password = Password;
|
||||
this.ServerAddress = (String.IsNullOrEmpty(ServerAddress)) ? "." : ServerAddress.Trim().ToUpper();
|
||||
this.InstanceName = InstanceName.Trim().ToUpper();
|
||||
this.TrustedConnection = TrustedConnection;
|
||||
this.IntegratedSecurity = TrustedConnection ? "SSPI" : "";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Construction SQL Server (Set all UDL Settings for SQL Server)
|
||||
/// </summary>
|
||||
/// <param name="DataBase">Name of Database To Use</param>
|
||||
/// <param name="Username">Username to Connect With</param>
|
||||
/// <param name="Password">Password to Connect With</param>
|
||||
/// <param name="ServerAddress">ServerAddress to use as DataSource</param>
|
||||
/// <param name="InstanceName">Name of Instance to use as DataSource</param>
|
||||
/// <param name="AttachDBFilename">Set to SQL Express .mdf file to attach to (Creates a User Instance)</param>
|
||||
/// <param name="TrustedConnection">Set to True to use Windows Authentication instead of SQL Auth</param>
|
||||
/// <param name="PersistSecurityInfo">Legacy Setting that Persists the Security Information</param>
|
||||
internal UDL(string DataBase, string Username, string Password, string ServerAddress, string InstanceName,
|
||||
string AttachDBFilename, bool TrustedConnection, bool PersistSecurityInfo)
|
||||
{
|
||||
this.DataBase = DataBase.Trim();
|
||||
this.Username = Username.Trim();
|
||||
this.Password = Password;
|
||||
this.ServerAddress = (String.IsNullOrEmpty(ServerAddress)) ? "." : ServerAddress.Trim().ToUpper();
|
||||
this.InstanceName = InstanceName.Trim().ToUpper();
|
||||
this.AttachDBFilename = AttachDBFilename.Trim();
|
||||
this.UserInstance = !String.IsNullOrEmpty(AttachDBFilename);
|
||||
this.TrustedConnection = TrustedConnection;
|
||||
this.IntegratedSecurity = TrustedConnection? "SSPI" : "";
|
||||
this.PersistSecurityInfo = PersistSecurityInfo;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#endregion
|
||||
|
||||
#region Connection String N' Parse
|
||||
|
||||
/// <summary>
|
||||
/// Returns the Connection String formed from the UDL Properties
|
||||
/// </summary>
|
||||
/// <see cref="http://www.connectionstrings.com/sql-server-2008"/>
|
||||
/// <example>
|
||||
/// Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;
|
||||
/// Server=myServerAddress;Database=myDataBase;User ID=myUsername;Password=myPassword;Trusted_Connection=False;
|
||||
/// Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI;
|
||||
/// Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;
|
||||
/// Server=myServerName\theInstanceName;Database=myDataBase;Trusted_Connection=True;
|
||||
/// Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI;User ID=myDomain\myUsername;Password=myPassword;
|
||||
/// </example>
|
||||
internal string ConnectionString
|
||||
{
|
||||
get
|
||||
{
|
||||
string strUDL = String.Empty;
|
||||
|
||||
// * Data Source Must Always be Specified *
|
||||
if (!String.IsNullOrEmpty(ServerAddress) && !String.IsNullOrEmpty(InstanceName))
|
||||
{
|
||||
strUDL = String.Format(@"Data Source={0}\{1};", ServerAddress, InstanceName);
|
||||
}
|
||||
else if (!String.IsNullOrEmpty(ServerAddress))
|
||||
{
|
||||
strUDL = String.Format(@"Data Source={0};", ServerAddress);
|
||||
}
|
||||
else
|
||||
throw new Exception("Invalid DataSource Parameter");
|
||||
|
||||
// Add Database?
|
||||
if (!String.IsNullOrEmpty(DataBase))
|
||||
{
|
||||
string strAddMore = String.Format(@"Initial Catalog={0};", DataBase);
|
||||
strUDL += strAddMore;
|
||||
}
|
||||
|
||||
// Add User Information?
|
||||
if (!String.IsNullOrEmpty(Username))
|
||||
{
|
||||
string strAddMore = String.Format(@"User ID={0};", Username);
|
||||
strUDL += strAddMore;
|
||||
}
|
||||
|
||||
// Add Password Information?
|
||||
if (!String.IsNullOrEmpty(Password))
|
||||
{
|
||||
string strAddMore = String.Format(@"Password={0};", Password);
|
||||
strUDL += strAddMore;
|
||||
}
|
||||
|
||||
// Should we use User Instance?
|
||||
if (UserInstance && !String.IsNullOrEmpty(AttachDBFilename))
|
||||
{
|
||||
string strAddMore = String.Format(@"User Instance={0};AttachDBFilename={1}", UserInstance.ToString(), AttachDBFilename);
|
||||
strUDL += strAddMore;
|
||||
}
|
||||
|
||||
// Should we use Integrated Security?
|
||||
if (TrustedConnection && !String.IsNullOrEmpty(IntegratedSecurity))
|
||||
{
|
||||
string strAddMore = String.Format(@"Trusted_Connection={0};Integrated Security={1}", TrustedConnection.ToString(), IntegratedSecurity);
|
||||
strUDL += strAddMore;
|
||||
}
|
||||
|
||||
// Persist Security Info?
|
||||
if (PersistSecurityInfo)
|
||||
{
|
||||
string strAddMore = String.Format(@"Persist Security Info={0};", PersistSecurityInfo.ToString());
|
||||
strUDL += strAddMore;
|
||||
}
|
||||
|
||||
// SQL CE Encryption
|
||||
if (Encrypt)
|
||||
{
|
||||
string strAddMore = "Encrypt=TRUE;Encryption Mode=platform default;";
|
||||
strUDL += strAddMore;
|
||||
}
|
||||
|
||||
// At the end, specifically add the connection timeout * If asked to *
|
||||
if (UseConnectionTimeout)
|
||||
{
|
||||
string strAddMore = String.Format(@"Connection Timeout={0};", ConnectionTimeout.ToString());
|
||||
strUDL += strAddMore;
|
||||
}
|
||||
return strUDL;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns a Connection String for use with Legacy ADO
|
||||
/// </summary>
|
||||
internal string ConnectionStringADO
|
||||
{
|
||||
get
|
||||
{
|
||||
// Force Persist Security Info
|
||||
bool bPersistSecurity = PersistSecurityInfo;
|
||||
PersistSecurityInfo = true;
|
||||
string retString = "Provider=SQLOLEDB.1;OLE DB Services=-2;" + ConnectionString;
|
||||
PersistSecurityInfo = bPersistSecurity;
|
||||
return retString;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parses (fills in) UDL properties from the passed in Connection String
|
||||
/// </summary>
|
||||
/// <param name="strToParse"></param>
|
||||
private void Parse(String ConnectionString)
|
||||
{
|
||||
if (!String.IsNullOrEmpty(ConnectionString))
|
||||
{
|
||||
String[] tokens = ConnectionString.Split(';');
|
||||
foreach (string Pair in tokens)
|
||||
{
|
||||
string[] KeyValuePair = Pair.Split('=');
|
||||
try
|
||||
{
|
||||
switch (KeyValuePair[0].ToUpper().Trim())
|
||||
{
|
||||
case "INITIAL CATALOG":
|
||||
DataBase = KeyValuePair[1].Trim();
|
||||
break;
|
||||
|
||||
case "USER ID":
|
||||
Username = KeyValuePair[1].Trim();
|
||||
break;
|
||||
|
||||
case "PASSWORD":
|
||||
Password = KeyValuePair[1];
|
||||
break;
|
||||
|
||||
case "DATA SOURCE":
|
||||
DataSource = KeyValuePair[1].Trim();
|
||||
break;
|
||||
|
||||
case "ATTACHDBFILENAME":
|
||||
AttachDBFilename = KeyValuePair[1].Trim();
|
||||
break;
|
||||
|
||||
case "USER INSTANCE":
|
||||
UserInstance = Boolean.Parse(KeyValuePair[1].Trim());
|
||||
break;
|
||||
|
||||
case "CONNECTION TIMEOUT":
|
||||
ConnectionTimeout = UInt32.Parse(KeyValuePair[1].Trim());
|
||||
break;
|
||||
|
||||
case "TRUSTED_CONNECTION":
|
||||
TrustedConnection = Boolean.Parse(KeyValuePair[1].Trim());
|
||||
break;
|
||||
|
||||
case "INTEGRATED SECURITY":
|
||||
IntegratedSecurity = KeyValuePair[1].Trim().ToUpper();
|
||||
break;
|
||||
|
||||
case "PERSIST SECURITY INFO":
|
||||
PersistSecurityInfo = Boolean.Parse(KeyValuePair[1].Trim());
|
||||
break;
|
||||
|
||||
case "ENCRYPT":
|
||||
Encrypt = true;
|
||||
break;
|
||||
|
||||
case "ENCRYPTION MODE":
|
||||
Encrypt = true;
|
||||
break;
|
||||
|
||||
}
|
||||
}
|
||||
catch (Exception) { /* ignore and continue iteration */ }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region ICloneable Members
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public object Clone()
|
||||
{
|
||||
return new UDL(this.ConnectionString);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region IComparable Members
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="obj"></param>
|
||||
/// <returns></returns>
|
||||
public int CompareTo(object obj)
|
||||
{
|
||||
UDL otherUDL = obj as UDL;
|
||||
if (otherUDL != null)
|
||||
{
|
||||
int nCompare = String.Compare(this.ConnectionString, otherUDL.ConnectionString, true);
|
||||
return nCompare;
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new ArgumentException("Object is not a UDL");
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region UDL File Reading / Writing
|
||||
|
||||
/// <summary>
|
||||
/// Use this to Parse a UDL object from a text File
|
||||
/// </summary>
|
||||
/// <param name="FileNameNPath">Full Path to File to Read and Parse</param>
|
||||
/// <param name="bFileIsEncrypted">true if the Text file is encrypted, false otherwise</param>
|
||||
/// <returns>a valid UDL object if successful, null otherwise</returns>
|
||||
internal static UDL UDLReadInFromFile(string FileNameNPath, bool bFileIsEncrypted)
|
||||
{
|
||||
if (!File.Exists(FileNameNPath))
|
||||
return null;
|
||||
|
||||
try
|
||||
{
|
||||
// Read In the file
|
||||
string UDLFileContents = string.Empty;
|
||||
FileStream fs = new FileStream(FileNameNPath, FileMode.Open);
|
||||
StreamReader sr = new StreamReader(fs, Encoding.Unicode);
|
||||
string line;
|
||||
while ((line = sr.ReadLine()) != null)
|
||||
{
|
||||
// UDL File is encrypted * Decrypt line by line *
|
||||
//if (bFileIsEncrypted)
|
||||
//line = Encryption.DecryptText(line);
|
||||
|
||||
if (line.StartsWith("[oledb]") ||
|
||||
line.StartsWith(";"))
|
||||
continue; // skip first 2 lines
|
||||
|
||||
// Read the line
|
||||
UDLFileContents += line;
|
||||
}
|
||||
sr.Close();
|
||||
fs.Close();
|
||||
|
||||
UDLFileContents = UDLFileContents.Trim();
|
||||
if (String.IsNullOrEmpty(UDLFileContents))
|
||||
return null;
|
||||
|
||||
// Parse out the UDL Info
|
||||
UDL udl = new UDL(UDLFileContents);
|
||||
return udl;
|
||||
}
|
||||
catch (Exception) {/* ignore */}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Use this to Write a UDL Object to a Text File
|
||||
/// </summary>
|
||||
/// <param name="FileNameNPath">Full Path to File to Write To</param>
|
||||
/// <param name="udl">UDL Object to write out</param>
|
||||
/// <param name="bEncryptFile">True to encrypt File Contents, False Otherwise</param>
|
||||
/// <returns>true if successful, false otherwise</returns>
|
||||
internal static bool UDLWriteOutToToFile(string FileNameNPath, UDL udl, bool bEncryptFile)
|
||||
{
|
||||
try
|
||||
{
|
||||
string UDLFileContents = string.Empty;
|
||||
|
||||
// Create the Directory (if it doesn't exist) * Otherwise an error occurs *
|
||||
if (!Directory.Exists(Path.GetDirectoryName(FileNameNPath)))
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(FileNameNPath));
|
||||
|
||||
// Write to File
|
||||
FileStream fs = new FileStream(FileNameNPath, FileMode.Create);
|
||||
StreamWriter sw = new StreamWriter(fs, Encoding.Unicode);
|
||||
|
||||
// UDL File is Encrypted Now, so we encrypte Line-by-line
|
||||
if (bEncryptFile)
|
||||
{
|
||||
// sw.WriteLine(Encryption.EncryptText("[oledb]"));
|
||||
// sw.WriteLine(Encryption.EncryptText("; Everything after this line is an OLE DB initstring"));
|
||||
// write out the Connection string,
|
||||
// sw.WriteLine(Encryption.EncryptText(udl.ConnectionStringLegacy));
|
||||
}
|
||||
else
|
||||
{
|
||||
sw.WriteLine("[oledb]");
|
||||
sw.WriteLine("; Everything after this line is an OLE DB initstring");
|
||||
sw.WriteLine(udl.ConnectionString);
|
||||
}
|
||||
|
||||
sw.Close();
|
||||
fs.Close();
|
||||
return true;
|
||||
}
|
||||
catch (Exception) { /* ignore */ }
|
||||
return false;
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
443
Internal/Versioning.cs
Normal file
443
Internal/Versioning.cs
Normal file
@@ -0,0 +1,443 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
|
||||
namespace Sdaleo.Internal
|
||||
{
|
||||
/// <summary>
|
||||
/// Interface of Versioning, to check if the passed in version is supported by the Versioning Object
|
||||
/// </summary>
|
||||
internal interface IVersionSupported
|
||||
{
|
||||
bool IsSupported(string Version);
|
||||
bool IsSupported(Versioning Version);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Allows us to easily wrap Versioning Functionallity,
|
||||
/// into Objects.
|
||||
/// [Major version].[Minor version].[Build number]
|
||||
/// ---------------------------------------------------
|
||||
/// Major version can be any valid uint as well as *
|
||||
/// Minor version can be any valid uint as well as *
|
||||
/// Build number can be any valid uint as well as *
|
||||
/// </summary>
|
||||
internal class Versioning : ICloneable, IComparable, IVersionSupported
|
||||
{
|
||||
#region Internal consts
|
||||
|
||||
internal const int STAR_ALL = -1;
|
||||
|
||||
#endregion
|
||||
|
||||
#region Private Members
|
||||
|
||||
private int _MajorVersion = STAR_ALL;
|
||||
private int _MinorVersion = STAR_ALL;
|
||||
private int _BuildNumber = STAR_ALL;
|
||||
|
||||
#endregion
|
||||
|
||||
#region Construction
|
||||
|
||||
/// <summary>
|
||||
/// Use this to initialize the class with a version string, can not contain multiple versions seperated by ";"
|
||||
/// </summary>
|
||||
/// <param name="strVersion">any version string in the format [Major].[Minor].[Build], like 5.3.3 or 5.4.*</param>
|
||||
internal Versioning(string strVersion)
|
||||
{
|
||||
if (!IsValidVersionStr(strVersion) || strVersion.Contains(";"))
|
||||
throw new ArgumentException("Invalid Version String");
|
||||
ParseVersion(strVersion, out this._MajorVersion, out this._MinorVersion, out this._BuildNumber);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initialize Versioning with a single MajorVersion and MinorVersion.
|
||||
/// </summary>
|
||||
/// <param name="MajorVersion">Major Version</param>
|
||||
/// <param name="MinorVersion">Minor Version</param>
|
||||
internal Versioning(int MajorVersion, int MinorVersion)
|
||||
{
|
||||
if (MajorVersion >= STAR_ALL && MinorVersion >= STAR_ALL)
|
||||
{
|
||||
_MajorVersion = MajorVersion;
|
||||
_MinorVersion = MinorVersion;
|
||||
}
|
||||
else
|
||||
throw new ArgumentException("MajorVersion or MinorVersion is invalid");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initialize Versioning with a single MajorVersion,MinorVersion, and BuildNumber.
|
||||
/// </summary>
|
||||
/// <param name="MajorVersion">Major Version</param>
|
||||
/// <param name="MinorVersion">Minor Version</param>
|
||||
/// <param name="BuildNumber">Build Number</param>
|
||||
internal Versioning(int MajorVersion, int MinorVersion, int BuildNumber)
|
||||
{
|
||||
if (MajorVersion >= STAR_ALL && MinorVersion >= STAR_ALL && _BuildNumber >= STAR_ALL)
|
||||
{
|
||||
_MajorVersion = MajorVersion;
|
||||
_MinorVersion = MinorVersion;
|
||||
_BuildNumber = BuildNumber;
|
||||
}
|
||||
else
|
||||
throw new ArgumentException("MajorVersion,MinorVersion, or BuildNumber is invalid");
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Versioning Getter/Setter
|
||||
|
||||
/// <summary>
|
||||
/// Set/Retrieve Version
|
||||
/// </summary>
|
||||
internal String Version
|
||||
{
|
||||
get
|
||||
{
|
||||
return VersionToVersionString(_MajorVersion, _MinorVersion, _BuildNumber);
|
||||
}
|
||||
set
|
||||
{
|
||||
if (IsValidVersionStr(value) && !value.Contains(";"))
|
||||
ParseVersion(value, out this._MajorVersion, out this._MinorVersion, out this._BuildNumber);
|
||||
else
|
||||
throw new ArgumentException("Invalid Version String");
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region internal Static Helpers
|
||||
|
||||
/// <summary>
|
||||
/// Gets a Versioning object for the Version Information of a File
|
||||
/// </summary>
|
||||
/// <param name="FileNameNPath">Full File Name and Path</param>
|
||||
/// <returns>returns a new Versioning Object for a File, or null if error occured</returns>
|
||||
internal static Versioning GetFileVersioning(string FileNameNPath)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(FileNameNPath) && File.Exists(FileNameNPath))
|
||||
{
|
||||
try
|
||||
{
|
||||
FileVersionInfo info = FileVersionInfo.GetVersionInfo(FileNameNPath);
|
||||
return new Versioning(info.FileMajorPart, info.FileMinorPart, info.FileBuildPart);
|
||||
}
|
||||
catch (Exception) { /* ignore */ }
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parses out a single Version from a string
|
||||
/// </summary>
|
||||
/// <param name="strVersion">pass in a Version format [Major].[Minor].[Build], like 5.3.3 or 5.4.*</param>
|
||||
/// <param name="MajorVersion">returns an int or STAR_ALL, or UNINITIALIZED, if error occured</param>
|
||||
/// <param name="MinorVersion">returns an int or STAR_ALL, or UNINITIALIZED, if error occured</param>
|
||||
/// <param name="BuildNumber">returns an int or STAR_ALL, or UNINITIALIZED, if error occured</param>
|
||||
internal static void ParseVersion(string strVersion, out int MajorVersion, out int MinorVersion, out int BuildNumber)
|
||||
{
|
||||
if (!IsValidVersionStr(strVersion) || strVersion.Contains(";"))
|
||||
throw new ArgumentException("Invalid Version String");
|
||||
|
||||
MajorVersion = STAR_ALL;
|
||||
MinorVersion = STAR_ALL;
|
||||
BuildNumber = STAR_ALL;
|
||||
string[] MajorMinorPossBuildVersion = strVersion.Split('.');
|
||||
try
|
||||
{
|
||||
for (int i = 0; i < MajorMinorPossBuildVersion.Length; ++i)
|
||||
{
|
||||
if (i == 0)
|
||||
{
|
||||
if (MajorMinorPossBuildVersion[0] != "*")
|
||||
MajorVersion = int.Parse(MajorMinorPossBuildVersion[0]);
|
||||
}
|
||||
else if (i == 1)
|
||||
{
|
||||
if (MajorMinorPossBuildVersion[1] != "*")
|
||||
MinorVersion = int.Parse(MajorMinorPossBuildVersion[1]);
|
||||
}
|
||||
else if (i == 2)
|
||||
{
|
||||
if (MajorMinorPossBuildVersion[2] != "*")
|
||||
BuildNumber = int.Parse(MajorMinorPossBuildVersion[2]);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
catch (Exception) { /* Ignore */ }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Turns Version Numbers into a Version String
|
||||
/// </summary>
|
||||
/// <param name="MajorVersion">Major Version</param>
|
||||
/// <param name="MinorVersion">Minor Version, can be *</param>
|
||||
/// <param name="BuildNumber">Build Number, can be * or UNINITIALIZED</param>
|
||||
/// <returns>the Version String</returns>
|
||||
internal static string VersionToVersionString(int MajorVersion, int MinorVersion = STAR_ALL, int BuildNumber = STAR_ALL)
|
||||
{
|
||||
string strRetVal = String.Empty;
|
||||
if (MajorVersion >= STAR_ALL)
|
||||
{
|
||||
// Major Version
|
||||
if (MajorVersion == STAR_ALL)
|
||||
strRetVal += "*";
|
||||
else
|
||||
strRetVal += MajorVersion.ToString();
|
||||
|
||||
// Minor Version
|
||||
if (MinorVersion >= STAR_ALL)
|
||||
{
|
||||
strRetVal += ".";
|
||||
if (MinorVersion == STAR_ALL)
|
||||
strRetVal += "*";
|
||||
else
|
||||
strRetVal += MinorVersion.ToString();
|
||||
}
|
||||
|
||||
// Build Number
|
||||
if (BuildNumber >= STAR_ALL)
|
||||
{
|
||||
strRetVal += ".";
|
||||
if (BuildNumber == STAR_ALL)
|
||||
strRetVal += "*";
|
||||
else
|
||||
strRetVal += BuildNumber.ToString();
|
||||
}
|
||||
}
|
||||
return strRetVal;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Validation
|
||||
|
||||
private const string CharSet_AllowedNumeric = "0123456789";
|
||||
private const string CharSet_AllowedVersionChars = CharSet_AllowedNumeric + "*;.";
|
||||
|
||||
/// <summary>
|
||||
/// Generic Function to use with Allowed Character Sets above
|
||||
/// </summary>
|
||||
/// <param name="TextToEvaluate">string to evaluate</param>
|
||||
/// <param name="TextToEvaluateWith">Pass in one of the legal character consts declared above</param>
|
||||
/// <returns>true if valid, false otherwise</returns>
|
||||
private static bool ContainsOnlyLegalChars(string TextToEvaluate, string TextToEvaluateWith)
|
||||
{
|
||||
foreach (char c in TextToEvaluate.ToCharArray())
|
||||
{
|
||||
bool bFound = (TextToEvaluateWith.IndexOf(c) >= 0);
|
||||
if (!bFound)
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Used to Validate a Version string of format 12.1.12;12.2.*;12.2.1
|
||||
/// </summary>
|
||||
/// <param name="VersionStr">a Version String</param>
|
||||
/// <returns>true if valid, false otherwise</returns>
|
||||
public static bool IsValidVersionStr(string VersionStr)
|
||||
{
|
||||
if (String.IsNullOrEmpty(VersionStr))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
else if (VersionStr.Length < 1 && VersionStr.Length > 50) // restrice Version String Length
|
||||
{
|
||||
return false;
|
||||
}
|
||||
else if (!ContainsOnlyLegalChars(VersionStr, CharSet_AllowedVersionChars))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region ICloneable Members
|
||||
public object Clone()
|
||||
{
|
||||
Versioning versioning = new Versioning(this._MajorVersion, this._MinorVersion, this._BuildNumber);
|
||||
return versioning;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region IComparable Members
|
||||
|
||||
public int CompareTo(object obj)
|
||||
{
|
||||
if (obj is Versioning)
|
||||
{
|
||||
Versioning v = (Versioning)obj;
|
||||
//*.*.*
|
||||
//*.2.*
|
||||
//1.*.*
|
||||
//1.1.*
|
||||
//1.1.1
|
||||
//2.2.2
|
||||
//2.2.*
|
||||
int nCompare = 0;
|
||||
nCompare = this._MajorVersion.CompareTo(v._MajorVersion);
|
||||
if (nCompare == 0)
|
||||
nCompare = this._MinorVersion.CompareTo(v._MinorVersion);
|
||||
if (nCompare == 0)
|
||||
nCompare = this._BuildNumber.CompareTo(v._BuildNumber);
|
||||
return nCompare;
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new ArgumentException("object is not a Versioning");
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region IVersionSupported Members
|
||||
|
||||
/// <summary>
|
||||
/// Returns true if the Version String passed in is supported/matches Versioning for this object
|
||||
/// </summary>
|
||||
/// <param name="Version">a Version string to validate against</param>
|
||||
/// <returns>true if supported, false otherwise</returns>
|
||||
public bool IsSupported(string Version)
|
||||
{
|
||||
Versioning version = new Versioning(Version);
|
||||
return IsSupported(version);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns true if the Version passed in is supported/matches Versioning for this object
|
||||
/// </summary>
|
||||
/// <param name="Version">a Version Object to validate against</param>
|
||||
/// <returns>true if supported, false otherwise</returns>
|
||||
public bool IsSupported(Versioning Version)
|
||||
{
|
||||
if (Version != null)
|
||||
{
|
||||
int nCompare = this.CompareTo(Version);
|
||||
if (nCompare == 0)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
else if (nCompare == 1)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
else if (nCompare == -1)
|
||||
{
|
||||
if (((this._MajorVersion == STAR_ALL) || (this._MajorVersion == Version._MajorVersion)) &&
|
||||
((this._MinorVersion == STAR_ALL) || (this._MinorVersion == Version._MinorVersion)) &&
|
||||
((this._BuildNumber == STAR_ALL) || (this._BuildNumber == Version._BuildNumber))
|
||||
)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Allows us to easily parse/sort/search multiple versioning classes
|
||||
/// </summary>
|
||||
internal static class Versionings
|
||||
{
|
||||
/// <summary>
|
||||
/// Used to parse multiple ";" seperated versions from a string
|
||||
/// </summary>
|
||||
/// <param name="strVersions">single/multiple version strings, seperated by ";", in the format [Major].[Minor].[Build], like 5.3.3 or 5.4.*</param>
|
||||
/// <returns>a sorted array of versionings or null if error occured</returns>
|
||||
internal static Versioning[] ParseVersions(string strVersions)
|
||||
{
|
||||
if (!Versioning.IsValidVersionStr(strVersions))
|
||||
return null;
|
||||
|
||||
List<Versioning> RetValueVersions = new List<Versioning>();
|
||||
string[] Versions = strVersions.Split(';');
|
||||
foreach (string Version in Versions)
|
||||
RetValueVersions.Add(new Versioning(Version));
|
||||
|
||||
RetValueVersions.Sort();
|
||||
return RetValueVersions.ToArray();
|
||||
}
|
||||
|
||||
#region IsSupportedFile
|
||||
|
||||
/// <summary>
|
||||
/// Use this to find out if a File Version is supported by the passed in Versions string
|
||||
/// </summary>
|
||||
/// <param name="strVersions">single/multiple version strings, seperated by ";", in the format [Major].[Minor].[Build], like 5.3.3 or 5.4.*</param>
|
||||
/// <param name="FileNameNPath">Full File Name and Path</param>
|
||||
/// <returns>true if the File Version is supported by the Versions string</returns>
|
||||
internal static bool IsSupportedFile(string strVersions, string FileNameNPath)
|
||||
{
|
||||
return IsSupported(ParseVersions(strVersions), Versioning.GetFileVersioning(FileNameNPath));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Use this to find out if a File Version is supported by the passed in Versions []
|
||||
/// </summary>
|
||||
/// <param name="Versions">single/multiple versioning objects</param>
|
||||
/// <param name="FileNameNPath">Full File Name and Path</param>
|
||||
/// <returns>true if the File Version is supported by the Versions string</returns>
|
||||
internal static bool IsSupportedFile(Versioning[] Versions, string FileNameNPath)
|
||||
{
|
||||
return IsSupported(Versions, Versioning.GetFileVersioning(FileNameNPath));
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region IsSupported
|
||||
|
||||
/// <summary>
|
||||
/// Pass in a Versions string, and a Version to check against. Returns true, if the Version is IVersionSupported by
|
||||
/// the passed in Versions string.
|
||||
/// </summary>
|
||||
/// <param name="strVersions">single/multiple version strings, seperated by ";", in the format [Major].[Minor].[Build], like 5.3.3 or 5.4.*</param>
|
||||
/// <param name="strVersion">any version string in the format [Major].[Minor].[Build], like 5.3.3 or 5.4.*</param>
|
||||
/// <returns>true, if a Versioning Object in the Versions returns true for IVersionSupported, false otherwise</returns>
|
||||
internal static bool IsSupported(string strVersions, string strVersion)
|
||||
{
|
||||
return IsSupported(ParseVersions(strVersions), new Versioning(strVersion));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Pass in a single/multipe Versions object, and a Version object to check against. Returns true, if the Version is IVersionSupported by
|
||||
/// the passed in Versions Objects.
|
||||
/// </summary>
|
||||
/// <param name="Versions">single/multiple versioning objects</param>
|
||||
/// <param name="Version">single versioning object</param>
|
||||
/// <returns>true, if a Versioning Object in the Versions returns true for IVersionSupported, false otherwise</returns>
|
||||
internal static bool IsSupported(Versioning[] Versions, Versioning Version)
|
||||
{
|
||||
// Let IVersionSupported do all the work
|
||||
foreach (Versioning _version in Versions)
|
||||
{
|
||||
if (_version.IsSupported(Version))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user