Initial Commit

This commit is contained in:
2016-07-21 16:55:03 -04:00
commit b6d5ec4ece
64 changed files with 7870 additions and 0 deletions

Binary file not shown.

Binary file not shown.

BIN
Components/Devart.Data.dll Normal file

Binary file not shown.

311
DB.cs Normal file
View File

@@ -0,0 +1,311 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Data.Common;
using System.Data;
namespace Sdaleo
{
/// <summary>
/// Serves as our main Class for interacting with the DB
/// </summary>
public class DB
{
private IConnectDb _ConnectionStrObj = null;
private DbConnection _DbConnection = null;
/// <summary>
/// Static DB Object Creator
/// </summary>
/// <param name="ConnectionStrObj">pass a valid Connection String Object</param>
/// <returns>a new DB Object</returns>
public static DB Create(IConnectDb ConnectionStrObj)
{
return new DB(ConnectionStrObj);
}
#region Construction
/// <summary>
/// Construct out DB Class with a valid Connection String Obj
/// </summary>
/// <param name="IConnectString">pass a valid Connection String Object</param>
public DB(IConnectDb ConnectionStrObj)
{
if(ConnectionStrObj == null || !ConnectionStrObj.IsValid)
throw new Exception("Invalid Connection Object Passed in.");
_ConnectionStrObj = ConnectionStrObj;
}
/// <summary>
/// Private Constructor * Used for Transaction Processing *
/// </summary>
/// <param name="dbConnection">A valid Connection Object that is in a Transaction State</param>
private DB(DbConnection dbConnection)
{
if (dbConnection == null)
throw new Exception("Invalid Connection Passed in.");
}
#endregion
#region NonQuery
/// <summary>
/// Use this to Run SQL with the ExecuteNonQuery() Command Object
/// </summary>
/// <param name="SqlCommandText">SQL Text/Commands to execute</param>
/// <returns>the result of the ExecuteNonQuery() operation</returns>
public DBRetVal ExecuteNonQuery(string SqlCommandText)
{
DBRetVal retVal = new DBRetVal();
try
{
using (DbConnection conn = DBMS.CreateDbConnection(_ConnectionStrObj.DBType, _ConnectionStrObj.ConnectionString))
{
conn.Open();
using (DbCommand cmd = conn.CreateCommand())
{
cmd.CommandText = SqlCommandText;
if(_ConnectionStrObj.SupportsTimeouts)
cmd.CommandTimeout = (int) _ConnectionStrObj.Timeouts.CommandTimeout;
int nRows = cmd.ExecuteNonQuery();
retVal.SetNonQueryRetVal(nRows);
}
}
}
catch (Exception e)
{
retVal = DBMS.CreateErrorDBRetVal(_ConnectionStrObj.DBType, e);
}
return retVal;
}
/// <summary>
/// Use this to Run SQL with the ExecuteNonQuery() Command Object
/// </summary>
/// <param name="SqlCommandText">SQL Text/Commands to execute</param>
/// <param name="parameters">Allows the use of DBMS Independent parameters</param>
/// <returns>the result of the ExecuteNonQuery() operation</returns>
public DBRetVal ExecuteNonQuery(string SqlCommandText, DBMSIndParameter[] parameters)
{
DBRetVal retVal = new DBRetVal();
try
{
using (DbConnection conn = DBMS.CreateDbConnection(_ConnectionStrObj.DBType, _ConnectionStrObj.ConnectionString))
{
conn.Open();
using (DbCommand cmd = conn.CreateCommand())
{
cmd.CommandText = SqlCommandText;
if (_ConnectionStrObj.SupportsTimeouts)
cmd.CommandTimeout = (int)_ConnectionStrObj.Timeouts.CommandTimeout;
// Add DBMS Specific Parameters
foreach (DbParameter parameter in DBMS.CreateDbParameter(_ConnectionStrObj.DBType, parameters))
cmd.Parameters.Add(parameter);
int nRows = cmd.ExecuteNonQuery();
retVal.SetNonQueryRetVal(nRows);
}
}
}
catch (Exception e)
{
retVal = DBMS.CreateErrorDBRetVal(_ConnectionStrObj.DBType, e);
}
return retVal;
}
#endregion
#region ExecuteScalar
/// <summary>
/// Use this to Run SQL with the ExecuteScalar() Command Object
/// </summary>
/// <param name="SqlText">SQL Text to execute</param>
/// <returns>the result of the ExecuteScalar() operation</returns>
public DBRetVal ExecuteScalar(string SqlText)
{
DBRetVal retVal = new DBRetVal();
try
{
using (DbConnection conn = DBMS.CreateDbConnection(_ConnectionStrObj.DBType, _ConnectionStrObj.ConnectionString))
{
conn.Open();
using (DbCommand cmd = conn.CreateCommand())
{
cmd.CommandText = SqlText;
if (_ConnectionStrObj.SupportsTimeouts)
cmd.CommandTimeout = (int)_ConnectionStrObj.Timeouts.CommandTimeout;
object oResult = cmd.ExecuteScalar();
retVal.SetScalarRetVal(oResult);
}
}
}
catch (Exception e)
{
retVal = DBMS.CreateErrorDBRetVal(_ConnectionStrObj.DBType, e);
}
return retVal;
}
/// <summary>
/// Use this to Run SQL with the ExecuteScalar() Command Object
/// </summary>
/// <param name="SqlText">SQL Text to execute</param>
/// <param name="parameters">Allows the use of DBMS Independent parameters</param>
/// <returns>the result of the ExecuteScalar() operation</returns>
public DBRetVal ExecuteScalar(string SqlText, DBMSIndParameter[] parameters)
{
DBRetVal retVal = new DBRetVal();
try
{
using (DbConnection conn = DBMS.CreateDbConnection(_ConnectionStrObj.DBType, _ConnectionStrObj.ConnectionString))
{
conn.Open();
using (DbCommand cmd = conn.CreateCommand())
{
cmd.CommandText = SqlText;
if (_ConnectionStrObj.SupportsTimeouts)
cmd.CommandTimeout = (int)_ConnectionStrObj.Timeouts.CommandTimeout;
// Add DBMS Specific Parameters
foreach (DbParameter parameter in DBMS.CreateDbParameter(_ConnectionStrObj.DBType, parameters))
cmd.Parameters.Add(parameter);
object oResult = cmd.ExecuteScalar();
retVal.SetScalarRetVal(oResult);
}
}
}
catch (Exception e)
{
retVal = DBMS.CreateErrorDBRetVal(_ConnectionStrObj.DBType, e);
}
return retVal;
}
#endregion
#region DataTable
/// <summary>
/// Use this to Run SQL with the DataAdapter Fill()
/// </summary>
/// <param name="SqlText">SQL Text to execute</param>
/// <returns>the result of the DataAdapter Fill() operation</returns>
public DBRetVal FillDataTable(string SqlText)
{
DBRetVal retVal = new DBRetVal();
try
{
using (DbConnection conn = DBMS.CreateDbConnection(_ConnectionStrObj.DBType, _ConnectionStrObj.ConnectionString))
{
conn.Open();
using (DbCommand cmd = conn.CreateCommand())
{
cmd.CommandText = SqlText;
if (_ConnectionStrObj.SupportsTimeouts)
cmd.CommandTimeout = (int)_ConnectionStrObj.Timeouts.CommandTimeout;
using (DbDataAdapter dataAdapter = DBMS.CreateDbDataAdapter(_ConnectionStrObj.DBType, cmd))
{
DataTable dt = new DataTable();
dataAdapter.Fill(dt);
retVal.SetDataTableRetVal(dt);
}
}
}
}
catch (Exception e)
{
retVal = DBMS.CreateErrorDBRetVal(_ConnectionStrObj.DBType, e);
}
return retVal;
}
/// <summary>
/// Use this to Run SQL with the DataAdapter Fill()
/// </summary>
/// <param name="SqlText">SQL Text to execute</param>
/// <param name="parameters">Allows the use of DBMS Independent parameters</param>
/// <returns>the result of the DataAdapter Fill() operation</returns>
public DBRetVal FillDataTable(string SqlText, DBMSIndParameter[] parameters)
{
DBRetVal retVal = new DBRetVal();
try
{
using (DbConnection conn = DBMS.CreateDbConnection(_ConnectionStrObj.DBType, _ConnectionStrObj.ConnectionString))
{
conn.Open();
using (DbCommand cmd = conn.CreateCommand())
{
cmd.CommandText = SqlText;
if (_ConnectionStrObj.SupportsTimeouts)
cmd.CommandTimeout = (int)_ConnectionStrObj.Timeouts.CommandTimeout;
// Add DBMS Specific Parameters
foreach (DbParameter parameter in DBMS.CreateDbParameter(_ConnectionStrObj.DBType, parameters))
cmd.Parameters.Add(parameter);
using (DbDataAdapter dataAdapter = DBMS.CreateDbDataAdapter(_ConnectionStrObj.DBType, cmd))
{
DataTable dt = new DataTable();
dataAdapter.Fill(dt);
retVal.SetDataTableRetVal(dt);
}
}
}
}
catch (Exception e)
{
retVal = DBMS.CreateErrorDBRetVal(_ConnectionStrObj.DBType, e);
}
return retVal;
}
#endregion
#region Transaction
/// <summary>
/// Use this to run multiple DB Steps and group them into a Single Transaction
/// </summary>
/// <param name="transactionSteps">an array of Transaction Steps to execute</param>
/// <returns>the result of Transaction</returns>
public DBRetVal StartTransaction(TransactionStep[] transactionSteps)
{
DBRetVal retVal = new DBRetVal();
try
{
DB db = new DB(_ConnectionStrObj);
// Enter Transaction
foreach (TransactionStep step in transactionSteps)
{
// Iterate thru each Transaction Step-By-Step
retVal = step(retVal, db);
// Stop The Transaction
if (retVal.ErrorOccured) // Have to Leave the Transaction as well
break;
}
// Leave Transaction
}
catch (Exception e)
{
retVal = DBMS.CreateErrorDBRetVal(_ConnectionStrObj.DBType, e);
}
return retVal;
}
#endregion
}
}

64
DBError.cs Normal file
View File

@@ -0,0 +1,64 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Collections;
namespace Sdaleo
{
/// <summary>
/// Our Custom Database Error Class that DB Functions Return to External Callers
/// </summary>
public class DBError
{
public int nError { get; set; }
public string ErrorMsg { get; set; }
public ICollection Errors { get; set; }
public DBError()
{
nError = -1;
ErrorMsg = String.Empty;
Errors = null;
}
public DBError(int nError, string ErrorMsg, ICollection Errors)
{
this.nError = nError;
this.ErrorMsg = ErrorMsg;
this.Errors = Errors;
}
/// <summary>
/// Used internally to quickly create a custom error object
/// </summary>
/// <param name="ErrorMsg">The Error Message to Display</param>
private const int DATABASE_LAYER_ERROR_NUMBER = 1978;
internal static DBError Create(string ErrorMsg)
{
return new DBError(DATABASE_LAYER_ERROR_NUMBER, ErrorMsg, null);
}
public bool ErrorOccured { get { return (nError != -1 && !String.IsNullOrEmpty(ErrorMsg)); } }
public int GetErrorCount { get { if (Errors != null) { return Errors.Count; } return 0; } }
public List<int> GetAllErrorNumbers
{
get
{
if (Errors != null)
{
List<int> list = new List<int>();
// * DBMS SPECIFIC *
// TO DO
foreach (SqlError error in Errors)
list.Add(error.Number);
//
return list;
}
return null;
}
}
}
}

256
DBInstallOrUpdate.cs Normal file
View File

@@ -0,0 +1,256 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sdaleo.Internal;
namespace Sdaleo
{
/// <summary>
/// Specify what type of update/install to do.
/// All_IF_EXISTS, will check for script existence and only run the ones that exist
/// </summary>
public enum InstallOrUpdateType
{
ALL_IF_EXISTS,
TABLES,
VIEWS,
SPROCS,
}
/// <summary>
/// Helper class to Install or Update a Database,
/// Before using this class set via DBResources a DBResource that points to SQL Script Files
/// to use in the Install/Update Process, or pass the DBResource in via one of the Constructors
/// ~SQL Script Files, contain SQL Snippets that are broken down to Commands and Identifiers as
/// specified in the internal class SQLParser. Using these commands and Identifiers,
/// you can Install/Update a SQL Server or SQLCE Database with ease
/// </summary>
public class DBInstallOrUpdate
{
#region Public and Private Members
// Public
public uint CurMajorVersion { get; private set; }
public uint CurMinorVersion { get; private set; }
public uint CurRevisionNumber { get; private set; }
// Private
private IConnectDb _DBCredential { get; set; }
private string _uniqueName { get; set; }
private DBResource _DBResouce { get; set; }
private string _VersioningTableName { get; set; }
// SQLScripts
private string[] _TableScripts = null;
private string[] _ViewScripts = null;
private string[] _SprocScripts = null;
#endregion
#region Constructors
/// <summary>
/// Construct a DBInstallOrUpdate Object in order to install tables, views, sprocs, or
/// update an existing database
/// </summary>
/// <param name="DBCredential">Pass in a DBCredential Object to use in this class</param>
/// <param name="uniqueName">specify a unique name, that was used when registering a DBResource via DBResources</param>
/// <param name="CurMajorVersion">Running Application's Current Major Product Version Number (for use in installs/upgrades)</param>
/// <param name="CurMinorVersion">Running Application's Current Minor Product Version Number (for use in installs/upgrades)</param>
/// <param name="CurRevisionNumber">Running Application's Current Revision Number (for use in installs/upgrades)</param>
/// <param name="VersioningTableName">Pass in a Table Name that will be created/updated to contain the latest Application Version Information *used for Update*</param>
public DBInstallOrUpdate(IConnectDb DBCredential, string uniqueName, uint CurMajorVersion, uint CurMinorVersion, uint CurRevisionNumber, string VersioningTableName = "Versioning")
{
if (!DBCredential.IsValid || String.IsNullOrEmpty(uniqueName))
throw new ArgumentException("DBCredential or uniqueName is Invalid");
// Make sure DBResource exists
DBResources.GetDBResource(uniqueName);
// Set all Private Members
ConstructorSetsPrivateMembers(DBCredential, uniqueName, CurMajorVersion, CurMinorVersion, CurRevisionNumber, VersioningTableName);
}
/// <summary>
/// Construct a DBInstallOrUpdate Object in order to install tables, views, sprocs, or
/// update an existing database
/// </summary>
/// <param name="DBCredential">Pass in a DBCredential Object to use in this class</param>
/// <param name="dbResource">pass in a valid DBResource that points to valid SQL Script Locations</param>
/// <param name="uniqueName">specify a unique name to use, that describes the dbResource used to register the resource</param>
/// <param name="CurMajorVersion">Running Application's Current Major Product Version Number (for use in installs/upgrades)</param>
/// <param name="CurMinorVersion">Running Application's Current Minor Product Version Number (for use in installs/upgrades)</param>
/// <param name="CurRevisionNumber">Running Application's Current Revision Number (for use in installs/upgrades)</param>
/// <param name="VersioningTableName">Pass in a Table Name that will be created/updated to contain the latest Application Version Information *used for Update*</param>
public DBInstallOrUpdate(IConnectDb DBCredential, DBResource dbResource, string uniqueName, uint CurMajorVersion, uint CurMinorVersion, uint CurRevisionNumber, string VersioningTableName = "Versioning")
{
if (!DBCredential.IsValid || String.IsNullOrEmpty(uniqueName))
throw new ArgumentException("DBCredential or uniqueName is Invalid");
// Add the DBResource
DBResources.AddDBResource(uniqueName, dbResource);
// Set all Private Members
ConstructorSetsPrivateMembers(DBCredential, uniqueName, CurMajorVersion, CurMinorVersion, CurRevisionNumber, VersioningTableName);
}
/// <summary>
/// Broken out of the Constructors, to centralize member initialization
/// </summary>
private void ConstructorSetsPrivateMembers(IConnectDb DBCredential, string uniqueName, uint CurMajorVersion, uint CurMinorVersion, uint CurRevisionNumber, string VersioningTableName)
{
this._DBCredential = DBCredential;
this._uniqueName = uniqueName;
this.CurMajorVersion = CurMajorVersion;
this.CurMinorVersion = CurMinorVersion;
this.CurRevisionNumber = CurRevisionNumber;
this._VersioningTableName = VersioningTableName;
// Retrieve Scripts
this._TableScripts = DBResources.GetTableDBResourceScripts(_uniqueName);
this._ViewScripts = DBResources.GetViewsDBResourceScripts(_uniqueName);
this._SprocScripts = DBResources.GetSprocsDBResourceScripts(_uniqueName);
}
#endregion
#region Public Methods and Properties
/// <summary>
///
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public DBError InstallOrUpdate(InstallOrUpdateType type)
{
DBError dbError;
if (!HasVersioningTable)
dbError = InstallDatabase(type);
else
dbError = UpdateDatabase(type);
return dbError;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
private bool HasVersioningTable
{
get
{
return true; // for now
}
}
#endregion
#region private Helper Functions
/// <summary>
///
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
private DBError InstallDatabase(InstallOrUpdateType type)
{
DBError dbError = new DBError();
// Install Tables first
if ((type == InstallOrUpdateType.TABLES || type == InstallOrUpdateType.ALL_IF_EXISTS) &&
(_TableScripts != null))
dbError = ExecuteSpecificMySQLCommandsTypesInSQLScripts(null, _TableScripts);
if (dbError.ErrorOccured) return dbError;
// Install Views Next
if ((type == InstallOrUpdateType.VIEWS || type == InstallOrUpdateType.ALL_IF_EXISTS) &&
(_TableScripts != null))
dbError = ExecuteSpecificMySQLCommandsTypesInSQLScripts(null, _ViewScripts);
if (dbError.ErrorOccured) return dbError;
// Install Sprocs Next
if ((type == InstallOrUpdateType.VIEWS || type == InstallOrUpdateType.ALL_IF_EXISTS) &&
(_SprocScripts != null))
dbError = ExecuteSpecificMySQLCommandsTypesInSQLScripts(null, _SprocScripts);
if (dbError.ErrorOccured) return dbError;
return new DBError();
}
/// <summary>
///
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
private DBError UpdateDatabase(InstallOrUpdateType type)
{
DBError dbError = new DBError();
// Install Tables first
if ((type == InstallOrUpdateType.TABLES || type == InstallOrUpdateType.ALL_IF_EXISTS) &&
(_TableScripts != null))
dbError = ExecuteSpecificMySQLCommandsTypesInSQLScripts(null, _TableScripts);
if (dbError.ErrorOccured) return dbError;
// Install Views Next
if ((type == InstallOrUpdateType.VIEWS || type == InstallOrUpdateType.ALL_IF_EXISTS) &&
(_TableScripts != null))
dbError = ExecuteSpecificMySQLCommandsTypesInSQLScripts(null, _ViewScripts);
if (dbError.ErrorOccured) return dbError;
// Install Sprocs Next
if ((type == InstallOrUpdateType.VIEWS || type == InstallOrUpdateType.ALL_IF_EXISTS) &&
(_SprocScripts != null))
dbError = ExecuteSpecificMySQLCommandsTypesInSQLScripts(null, _SprocScripts);
if (dbError.ErrorOccured) return dbError;
return new DBError();
}
/// <summary>
///
/// </summary>
/// <param name="types"></param>
/// <param name="FRLCS_ScriptFiles"></param>
/// <returns></returns>
private DBError ExecuteSpecificMySQLCommandsTypesInSQLScripts(MySQLCommandType[] types, string[] FRLCS_ScriptFiles)
{
foreach (string scriptFile in FRLCS_ScriptFiles)
{
// Retrieve the Commands N' Identifiers for the Script
MySQLCommand[] commands = null;
MySQLIdentifier[] identifiers = null;
if (!GetCommandsAndIdentifiersFromSqlScript(scriptFile, out commands, out identifiers))
{
// argh.. .this should not happen
}
// Only Execute certain types/Versions????
DBError dbError = commands[0].ExecuteScriptBlock(_DBCredential);
if (dbError.ErrorOccured)
{
//commands[0].Line_CommandStart
}
}
return null;
}
/// <summary>
/// Uses DBResources and SQLParser to parse an SQLScript into MySQLCommands and MySQLIdentifiers
/// </summary>
/// <param name="FRLCS_Script">the FRLCS full resource file and path to the script to parse</param>
/// <param name="commands">returns out MySQLCommands found in script</param>
/// <param name="identifiers">returns out MySQLIdentities found in script</param>
/// <returns>true if commands and identifiers were fetched, false otherwise</returns>
private bool GetCommandsAndIdentifiersFromSqlScript(string FRLCS_Script, out MySQLCommand[] commands, out MySQLIdentifier[] identifiers)
{
string[] ScriptContents = DBResources.Read_FRLCS_Script(_uniqueName, FRLCS_Script);
SQLParser.ParseSQLScriptForMySQLCommandsAndIdentifiers(ScriptContents, out commands, out identifiers);
return ((commands != null) && (identifiers != null) && (commands.Length != 0) && (identifiers.Length != 0));
}
#endregion
}
}

211
DBResources.cs Normal file
View File

@@ -0,0 +1,211 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.IO;
namespace Sdaleo
{
/// <summary>
/// For SQL Server you can fill all locations, for SQLCE there are no Views,Sprocs
/// FullResourceLocationContainingScripts, is the full resource folder where the sql scripts are located
/// f.e. Application.DatabaseLayer.SQLScripts
/// SQLScript_FileExt specifies which files to look for (f.e. .sql or .sqlce)
/// </summary>
public struct DBResource
{
public Assembly AssemblyContainingResources;
public string FullResourceLocationContaingScripts_Tables;
public string FullResourceLocationContaingScripts_Views;
public string FullResourceLocationContaingScripts_Sprocs;
public string SQLScript_FileExt;
/// <summary>
/// Useful for SQLCE DBResources, which only contains Tables
/// </summary>
/// <param name="asm">the assembly that contains the resources</param>
/// <param name="FRLCS_Tables">The Location of where the table .sqlce scripts are located, can be blank, if not used, but that would not make sense</param>
/// <param name="FileExt">file extension of the scripts, like .sqlce</param>
public DBResource(Assembly asm, string FRLCS_Tables, string FileExt = ".sqlce")
{
this.AssemblyContainingResources = asm;
this.FullResourceLocationContaingScripts_Tables = FRLCS_Tables;
this.FullResourceLocationContaingScripts_Views = String.Empty;
this.FullResourceLocationContaingScripts_Sprocs = String.Empty;
this.SQLScript_FileExt = FileExt;
}
/// <summary>
/// Useful for SQLServer DBResources, which can contain Tables, Views, Sprocs
/// </summary>
/// <param name="asm">the assembly that contains the resources</param>
/// <param name="FRLCS_Tables">The Location of where the table .sql scripts are located, can be blank, if not used</param>
/// <param name="FRLCS_Views">The Location of where the views .sql scripts are located, can be blank, if not used</param>
/// <param name="FRLCS_Sprocs">The Location of where the sprocs .sql scripts are located, can be blank, if not used</param>
/// <param name="FileExt">file extension of the scripts, like .sql</param>
public DBResource(Assembly asm, string FRLCS_Tables, string FRLCS_Views, string FRLCS_Sprocs, string FileExt = ".sql")
{
this.AssemblyContainingResources = asm;
this.FullResourceLocationContaingScripts_Tables = FRLCS_Tables;
this.FullResourceLocationContaingScripts_Views = FRLCS_Views;
this.FullResourceLocationContaingScripts_Sprocs = FRLCS_Sprocs;
this.SQLScript_FileExt = FileExt;
}
}
/// <summary>
/// This class allows external callers to set SQL Resource Scripts,
/// for easy table, view, sprocs creation and updating
/// </summary>
public static class DBResources
{
#region Private Statics
private static Dictionary<string, DBResource> _DBResources = new Dictionary<string, DBResource>();
#endregion
#region DBResource Add/Get/Delete
/// <summary>
/// Used to Add a DBResource into DatabaseLayer
/// </summary>
/// <param name="uniqueName">Unique Name to identify the Resource by</param>
/// <param name="dbResource">a DBResource structure that must contain the assembly and at least one resource, and the file extension for the scripts</param>
/// <returns>true if added, false otherwise</returns>
public static bool AddDBResource(string uniqueName, DBResource dbResource)
{
if (!String.IsNullOrEmpty(uniqueName) && !_DBResources.ContainsKey(uniqueName))
{
_DBResources.Add(uniqueName, dbResource);
return true;
}
return false;
}
/// <summary>
/// Used to Delete a DBResource from DatabaseLayer
/// </summary>
/// <param name="uniqueName">Unique Name to identify the Resource by</param>
/// <returns>true if deleted, false otherwise</returns>
public static bool DeleteDBResource(string uniqueName)
{
if (!String.IsNullOrEmpty(uniqueName) && _DBResources.ContainsKey(uniqueName))
{
_DBResources.Remove(uniqueName);
return true;
}
return false;
}
/// <summary>
/// Used to Retrieve a DBResource from DatabaseLayer
/// </summary>
/// <param name="uniqueName">Unique Name to identify the Resource by</param>
/// <returns>the DBResource that was previously added by AddDBResource(), otherwise throws an error</returns>
public static DBResource GetDBResource(string uniqueName)
{
if (!String.IsNullOrEmpty(uniqueName) && _DBResources.ContainsKey(uniqueName))
return _DBResources[uniqueName];
else
throw new Exception("DBResource not found. Call AddDBResource First");
}
#endregion
#region Internal Table, View, Sprocs, Resource Getter Functions
/// <summary>
/// Returns the Table Scripts for a specified DBResource
/// </summary>
/// <param name="uniqueName">Unique Name to identify the Resource by</param>
/// <returns>an array of FRLCS Script Names</returns>
internal static string[] GetTableDBResourceScripts(string uniqueName)
{
if (!String.IsNullOrEmpty(GetDBResource(uniqueName).FullResourceLocationContaingScripts_Tables))
return GetScriptsFromResourceLocation(GetDBResource(uniqueName).AssemblyContainingResources, GetDBResource(uniqueName).FullResourceLocationContaingScripts_Tables, GetDBResource(uniqueName).SQLScript_FileExt);
return null;
}
/// <summary>
/// Returns the Views Scripts for a specified DBResource
/// </summary>
/// <param name="uniqueName">Unique Name to identify the Resource by</param>
/// <returns>an array of FRLCS Script Names</returns>
internal static string[] GetViewsDBResourceScripts(string uniqueName)
{
if (!String.IsNullOrEmpty(GetDBResource(uniqueName).FullResourceLocationContaingScripts_Views))
return GetScriptsFromResourceLocation(GetDBResource(uniqueName).AssemblyContainingResources, GetDBResource(uniqueName).FullResourceLocationContaingScripts_Views, GetDBResource(uniqueName).SQLScript_FileExt);
return null;
}
/// <summary>
/// Returns the Sprocs Scripts for a specified DBResource
/// </summary>
/// <param name="uniqueName">Unique Name to identify the Resource by</param>
/// <returns>an array of FRLCS Script Names</returns>
internal static string[] GetSprocsDBResourceScripts(string uniqueName)
{
if(!String.IsNullOrEmpty(GetDBResource(uniqueName).FullResourceLocationContaingScripts_Sprocs))
return GetScriptsFromResourceLocation(GetDBResource(uniqueName).AssemblyContainingResources, GetDBResource(uniqueName).FullResourceLocationContaingScripts_Sprocs, GetDBResource(uniqueName).SQLScript_FileExt);
return null;
}
#endregion
#region Internal ReadScript
/// <summary>
/// Use this to read the contents of a Script from a specified Resource
/// </summary>
/// <param name="uniqueName">Unique Name to identify the Resource by</param>
/// <param name="FRLCS_Script">the Full Resource Location Name N Path of the Script to read</param>
/// <returns>the contents of the script, split by '\n', or null if not found</returns>
internal static string[] Read_FRLCS_Script(string uniqueName, string FRLCS_Script_Name)
{
using (StreamReader stream = new StreamReader(GetDBResource(uniqueName).AssemblyContainingResources.GetManifestResourceStream(FRLCS_Script_Name)))
{
if (stream != null)
{
string txtContent = stream.ReadToEnd();
// Get Rid of carriage returns and new lines
string[] retVal = txtContent.Replace("\r","").Split('\n');
// iterate each line and trim whitespaces
for (int i = 0; i < retVal.Length; ++i)
retVal[i] = retVal[i].Trim();
return retVal;
}
}
return null;
}
#endregion
#region Private Static Helper Functions
/// <summary>
/// Returns the Scripts found from the specified Resource Location
/// </summary>
/// <param name="ResourceLocation">a FRLCS Path to where the Scripts are located</param>
/// <param name="FileExt">File Extension used by the scripts</param>
/// <returns>the FRLCS names of the Scripts, or null if none found</returns>
private static string[] GetScriptsFromResourceLocation(Assembly asm, string ResourceLocation, string FileExt)
{
List<string> scriptsFRLCS = new List<String>();
string[] resourceNames = asm.GetManifestResourceNames();
foreach (string ResourceName in resourceNames)
{
if (ResourceName.StartsWith(ResourceLocation) && ResourceName.EndsWith(FileExt))
scriptsFRLCS.Add(ResourceName); // found
}
scriptsFRLCS.Sort();
return scriptsFRLCS.ToArray();
}
#endregion
}
}

235
DBRetVal.cs Normal file
View File

@@ -0,0 +1,235 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Collections;
namespace Sdaleo
{
/// <summary>
/// Used by Callers to determine DB Operation Outcome
/// </summary>
public enum DBRetValEnum
{
VALUE_FETCHED,
VALUE_NOTFETCHED,
NQ_NO_ROWS_AFFECTED,
NQ_ONE_ROW_AFFECTED,
NQ_MULTIPLE_ROWS_AFFECTED,
FAILED
}
/// <summary>
/// Our Database RetVal Class that DB Callers use to get Values
/// </summary>
public class DBRetVal : DBError
{
public DBRetValEnum Result { get; private set; }
// * Return Values from various DB Calls *
private DataTable RetVal_datatable { get; set; }
private String RetVal_string { get; set; }
private int RetVal_int { get; set; } // for NQ calls
// * Internal Mode *
private enum Mode
{
MODE_INIT,
MODE_VALUE_DT,
MODE_VALUE_STR,
MODE_NQ_INT,
}
private Mode _Mode = Mode.MODE_INIT;
/// <summary>
/// Initialize DBRetVal
/// </summary>
public DBRetVal()
: base()
{
_Mode = Mode.MODE_INIT;
Result = DBRetValEnum.FAILED;
RetVal_datatable = null;
RetVal_string = String.Empty;
RetVal_int = Int32.MinValue;
}
/// <summary>
/// Initialize DBRetVal with Error Info
/// </summary>
public DBRetVal(int nError, string ErrorMsg, ICollection Errors)
: base(nError, ErrorMsg, Errors)
{
_Mode = Mode.MODE_INIT;
Result = DBRetValEnum.FAILED;
RetVal_datatable = null;
RetVal_string = String.Empty;
RetVal_int = Int32.MinValue;
}
#region Validator
/// <summary>
/// Returns True if the Return value of this object is valid
/// </summary>
public bool IsValid
{
get
{
bool bIsValid = false;
switch (_Mode)
{
case Mode.MODE_INIT:
bIsValid = false;
break;
case Mode.MODE_NQ_INT:
bIsValid = (RetVal_int != Int32.MinValue) && (Result != DBRetValEnum.FAILED) && (Result != DBRetValEnum.VALUE_NOTFETCHED);
break;
case Mode.MODE_VALUE_DT:
bIsValid = (RetVal_datatable != null) && (Result != DBRetValEnum.FAILED) && (Result != DBRetValEnum.VALUE_NOTFETCHED);
break;
case Mode.MODE_VALUE_STR:
bIsValid = !String.IsNullOrEmpty(RetVal_string) && (Result != DBRetValEnum.FAILED) && (Result != DBRetValEnum.VALUE_NOTFETCHED);
break;
default:
bIsValid = false;
break;
}
// Double-check that there are no errors in DBError as well,
if (bIsValid)
bIsValid = !ErrorOccured;
return bIsValid;
}
}
#endregion
#region Getters
/// <summary>
/// Get the DataTable Return Value
/// </summary>
/// <returns>valid datatable or throws Exception, if in invalid state</returns>
public DataTable GetDataTableRetVal()
{
if (_Mode == Mode.MODE_VALUE_DT)
{
return RetVal_datatable;
}
else
{
throw new Exception(String.Format("Invalid State {0}. Can not call GetRetVal() for DataTable right now", _Mode.ToString()));
}
}
/// <summary>
/// Get the Scalar/String Return Value
/// </summary>
/// <returns>valid string or throws Exception, if in invalid state</returns>
public string GetScalarRetVal()
{
if (_Mode == Mode.MODE_VALUE_STR)
{
return RetVal_string;
}
else
{
throw new Exception(String.Format("Invalid State {0}. Can not call GetRetVal() for String right now", _Mode.ToString()));
}
}
/// <summary>
/// Get the NQ Return Value
/// </summary>
/// <returns>valid nRows or throws Exception, if in invalid state</returns>
public int GetNonQueryRetVal()
{
if (_Mode == Mode.MODE_NQ_INT)
{
return RetVal_int;
}
else
{
throw new Exception(String.Format("Invalid State {0}. Can not call GetRetValNQ() right now", _Mode.ToString()));
}
}
#endregion
#region Internal Setters
/// <summary>
/// Set the Return Value to a DataTable
/// </summary>
/// <param name="datatable">a valid DataTable</param>
/// <param name="result">a result to pass out * can not be NQ enum *</param>
internal void SetDataTableRetVal(DataTable datatable)
{
_Mode = Mode.MODE_VALUE_DT;
if (datatable == null || (datatable.Rows.Count == 0))
{
Result = DBRetValEnum.VALUE_NOTFETCHED;
}
else
{
Result = DBRetValEnum.VALUE_FETCHED;
RetVal_datatable = datatable;
}
// Clear Others
RetVal_string = String.Empty;
RetVal_int = Int32.MinValue;
}
/// <summary>
/// Set the Return Value to a String (pass in an object to be converted)
/// </summary>
/// <param name="o">a object that should be converted to a String</param>
internal void SetScalarRetVal(object o)
{
_Mode = Mode.MODE_VALUE_STR;
if (o == null || (o.ToString() == String.Empty))
{
Result = DBRetValEnum.VALUE_NOTFETCHED;
}
else
{
RetVal_string = o.ToString();
Result = DBRetValEnum.VALUE_FETCHED;
}
// Clear Others
RetVal_datatable = null;
RetVal_int = Int32.MinValue;
}
/// <summary>
/// Set the Return Value for a NQ Query
/// </summary>
/// <param name="nRows">number of rows affected</param>
internal void SetNonQueryRetVal(int nRows)
{
_Mode = Mode.MODE_NQ_INT;
RetVal_int = nRows;
if (nRows <= 0)
Result = DBRetValEnum.NQ_NO_ROWS_AFFECTED;
else if (nRows == 1)
Result = DBRetValEnum.NQ_ONE_ROW_AFFECTED;
else
Result = DBRetValEnum.NQ_MULTIPLE_ROWS_AFFECTED;
// Clear Others
RetVal_datatable = null;
RetVal_string = String.Empty;
}
#endregion
}
}

38
Definitions.cs Normal file
View File

@@ -0,0 +1,38 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sdaleo
{
/// <summary>
/// DB Management Systems
/// </summary>
public enum DBSystem
{
SQL_SERVER,
SQL_CE,
ADVANTAGE,
CTREE,
MYSQL,
POSTGRES
}
/// <summary>
/// Allows us to pass DBMS Independent Parameters to DB Functions
/// </summary>
public struct DBMSIndParameter
{
public string parameterName { get; set; }
public object Value { get; set; }
}
/// <summary>
/// Transaction Delegate, Used to group multiple DB Steps into a
/// Single Transaction
/// </summary>
/// <param name="prevStepRetVal">The Result of a prior TransactionStep is passed down</param>
/// <param name="db">the DB(Connection) object that should be used in the next step</param>
/// <returns></returns>
public delegate DBRetVal TransactionStep(DBRetVal prevStepRetVal, DB db);
}

58
Interfaces.cs Normal file
View File

@@ -0,0 +1,58 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sdaleo
{
/// <summary>
/// Expose the most basic connection string information for various DB Types
/// </summary>
public interface IConnectDb
{
// Validity & Type
DBSystem DBType { get; }
bool IsValid { get; }
// Connection Properties
string ConnectionString { get; }
string DataSource { get; }
string User { get; }
// Exposes Interfaces, if DB Type Supports it
bool SupportsDBMS { get; }
IamDBMS DBMS { get; }
bool SupportsTimeouts { get; }
IsupportTimeouts Timeouts { get; }
}
/// <summary>
/// Expose DBMS specific Instance and DB information
/// </summary>
public interface IamDBMS
{
// DBMS have instances
string Server { get; }
string Instance { get; }
// DBMS have multiple databases
string Database { get; }
bool IsDatabaseSet { get; }
bool IsDatabaseSetAndNonSystem { get; }
bool IsDatabaseSetAndNonDefault { get; }
IConnectDb WithDatabase(string strDatabaseName);
IConnectDb WithoutDatabase();
}
/// <summary>
/// Expose DB Timeout information
/// </summary>
public interface IsupportTimeouts
{
uint CommandTimeout { get; set; }
uint ConnectionTimeout { get; set; }
IConnectDb WithConnectionTimeout(uint nConnectionTimeout);
IConnectDb WithCommandTimeout(uint nCommandTimeout);
IConnectDb WithTimeouts(uint nConnectionTimeout, uint nCommandTimeout);
}
}

266
Internal/DBMS.cs Normal file
View 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
View 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
View 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
View 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();
}
}
}

View 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
View 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
View 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
}
}

View File

@@ -0,0 +1,36 @@
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("DatabaseLayer")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DatabaseLayer")]
[assembly: AssemblyCopyright("Copyright © 2010")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("f48a9f12-5507-405c-8358-c4365701f2ee")]
// 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 Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

126
Sdaleo.csproj Normal file
View File

@@ -0,0 +1,126 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{C919D6D0-E0AE-4D7A-B13D-350FCB4A22FF}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Sdaleo</RootNamespace>
<AssemblyName>Sdaleo</AssemblyName>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<SccProjectName>
</SccProjectName>
<SccLocalPath>
</SccLocalPath>
<SccAuxPath>
</SccAuxPath>
<SccProvider>
</SccProvider>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>..\Target\Debug\</OutputPath>
<DefineConstants>TRACE;DEBUG;NET35</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>..\Target\Release\</OutputPath>
<DefineConstants>TRACE;NET35</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Advantage.Data.Provider">
<HintPath>Components\Advantage.Data.Provider.dll</HintPath>
</Reference>
<Reference Include="Devart.Data">
<HintPath>Components\Devart.Data.dll</HintPath>
</Reference>
<Reference Include="Devart.Data.PostgreSql">
<HintPath>Components\Devart.Data.PostgreSql.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Data.SqlServerCe, Version=3.5.1.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91, processorArchitecture=MSIL" />
<Reference Include="System.ServiceProcess" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="DBError.cs" />
<Compile Include="DB.cs" />
<Compile Include="DBInstallOrUpdate.cs" />
<Compile Include="DBResources.cs" />
<Compile Include="DBRetVal.cs" />
<Compile Include="Definitions.cs" />
<Compile Include="Interfaces.cs" />
<Compile Include="Internal\ObjTool.cs" />
<Compile Include="Internal\RegKey.cs" />
<Compile Include="Internal\SQLParser.cs" />
<Compile Include="Internal\Versioning.cs" />
<Compile Include="Systems\Advantage\Credential.cs" />
<Compile Include="Systems\Advantage\Database.cs" />
<Compile Include="Systems\Advantage\General.cs" />
<Compile Include="Systems\Advantage\Internal\Validation.cs" />
<Compile Include="Systems\CTree\Credential.cs" />
<Compile Include="Systems\CTree\Database.cs" />
<Compile Include="Systems\CTree\General.cs" />
<Compile Include="Systems\CTree\Internal\Validation.cs" />
<Compile Include="Systems\MySql\Credential.cs" />
<Compile Include="Systems\MySql\Database.cs" />
<Compile Include="Systems\MySql\General.cs" />
<Compile Include="Systems\MySql\Internal\Validation.cs" />
<Compile Include="Systems\Postgres\Credential.cs" />
<Compile Include="Systems\Postgres\Database.cs" />
<Compile Include="Systems\Postgres\General.cs" />
<Compile Include="Systems\Postgres\Internal\Validation.cs" />
<Compile Include="Systems\SQLCE\Credential.cs" />
<Compile Include="Systems\SQLCE\Database.cs" />
<Compile Include="Systems\SQLCE\General.cs" />
<Compile Include="Systems\SQLCE\Internal\ErrorConst.cs" />
<Compile Include="Systems\SQLCE\Internal\Validation.cs" />
<Compile Include="Systems\SQLCE\Table.cs" />
<Compile Include="Systems\SQLServer\Credential.cs" />
<Compile Include="Internal\SecuredPassword.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Internal\DBMS.cs" />
<Compile Include="Systems\SQLServer\Database.cs" />
<Compile Include="Systems\SQLServer\General.cs" />
<Compile Include="Systems\SQLServer\Internal\SQLInfoEnumerator.cs" />
<Compile Include="Systems\SQLServer\Internal\ErrorConst.cs" />
<Compile Include="Systems\SQLServer\Utilities.cs" />
<Compile Include="Systems\SQLServer\Internal\Validation.cs" />
<Compile Include="Systems\SQLServer\Security.cs" />
<Compile Include="Systems\SQLServer\Table.cs" />
<Compile Include="Internal\UDL.cs" />
<Compile Include="Systems\SystemAvailable.cs" />
<Compile Include="Systems\ValidationConsts.cs" />
</ItemGroup>
<ItemGroup>
<Content Include="Components\Advantage.Data.Provider.dll" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Components\Devart.Data.dll" />
<EmbeddedResource Include="Components\Devart.Data.PostgreSql.dll" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

6
Sdaleo.csproj.user Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<ProjectView>ShowAllFiles</ProjectView>
</PropertyGroup>
</Project>

10
Sdaleo.csproj.vspscc Normal file
View File

@@ -0,0 +1,10 @@
""
{
"FILE_VERSION" = "9237"
"ENLISTMENT_CHOICE" = "NEVER"
"PROJECT_FILE_RELATIVE_PATH" = ""
"NUMBER_OF_EXCLUDED_FILES" = "0"
"ORIGINAL_PROJECT_FILE_PATH" = ""
"NUMBER_OF_NESTED_PROJECTS" = "0"
"SOURCE_CONTROL_SETTINGS_PROVIDER" = "PROVIDER"
}

View File

@@ -0,0 +1,137 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sdaleo.Systems.Advantage
{
/// <summary>
/// Handles SQL CE Credentials, to be
/// used by all our SQL CE Functions
/// </summary>
public class AdvantageCredential : IComparable, ICloneable, IConnectDb
{
#region IConnectDb
/// <summary>
/// Let Callers know this is a SQLCE Connection Object
/// </summary>
public DBSystem DBType { get { return DBSystem.ADVANTAGE; } }
/// <summary>
/// Check to see if the Credential Object consists of valid input
/// </summary>
public bool IsValid
{
get
{
if (!ValidationConsts.IsValidFileNameNPath(DataSource))
return false;
// For ADS i believe we always want a user and Password
//if (!String.IsNullOrEmpty(_UDL.Password) && !ValidationConsts.Generic.IsValidPassword(_UDL.Password))
// return false;
return true;
}
}
/// <summary>
///
/// </summary>
public string ConnectionString { get { return _UDL.ConnectionString; } }
/// <summary>
/// SQL CE uses the File Name and Path as the Datasource
/// </summary>
public string DataSource { get { return _UDL.DataSource; } }
/// <summary>
/// SQL CE doesn't use User
/// </summary>
public string User { get { return _UDL.Username; } }
/// <summary>
/// SQL CE doesn't support DBMS like behaviors
/// </summary>
public bool SupportsDBMS { get { return false; } }
/// <summary>
/// SQL CE doesn't support DBMS like behaviors
/// </summary>
public IamDBMS DBMS { get { return null; } }
/// <summary>
/// SQL CE doesn't support Timeouts
/// </summary>
public bool SupportsTimeouts { get { return false; } }
/// <summary>
/// SQL CE doesn't support Timeouts
/// </summary>
public IsupportTimeouts Timeouts { get { return null; } }
#endregion
private UDL _UDL = null;
#region AdvantageCredential Credential Constructors
/// <summary>
/// Create a SQL CE Connection from an UDL Object
/// </summary>
/// <param name="udl"></param>
internal AdvantageCredential(UDL udl)
{
if (udl != null)
_UDL = udl;
}
/// <summary>
/// Create an Untrusted SQLCE Credential * No Encryption Used *
/// </summary>
public AdvantageCredential(string FileNameNPath)
{
_UDL = new UDL(FileNameNPath, String.Empty);
}
/// <summary>
/// Create a Trusted SQLCE Credential * Encryption Used *
/// </summary>
public AdvantageCredential(string FileNameNPath, string strPassword)
{
_UDL = new UDL(FileNameNPath, strPassword);
}
#endregion
#region ICloneable Members
public object Clone()
{
AdvantageCredential credential = new AdvantageCredential((UDL)this._UDL.Clone());
return credential;
}
#endregion
#region IComparable Members
public int CompareTo(object obj)
{
AdvantageCredential otherCredential = obj as AdvantageCredential;
if (otherCredential != null)
{
int nCompare = _UDL.CompareTo(otherCredential._UDL);
return nCompare;
}
else
{
throw new ArgumentException("Object is not a AdvantageCredential");
}
}
#endregion
}
}

View File

@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sdaleo.Systems.Advantage
{
class AdvantageDatabase
{
}
}

View File

@@ -0,0 +1,11 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sdaleo.Systems.Advantage
{
class General
{
}
}

View File

@@ -0,0 +1,11 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sdaleo.Systems.Advantage.Internal
{
class Validation
{
}
}

View File

@@ -0,0 +1,11 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sdaleo.Systems.CTree
{
class Credential
{
}
}

11
Systems/CTree/Database.cs Normal file
View File

@@ -0,0 +1,11 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sdaleo.Systems.CTree
{
class Database
{
}
}

11
Systems/CTree/General.cs Normal file
View File

@@ -0,0 +1,11 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sdaleo.Systems.CTree
{
class General
{
}
}

View File

@@ -0,0 +1,11 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sdaleo.Systems.CTree.Internal
{
class Validation
{
}
}

View File

@@ -0,0 +1,11 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sdaleo.Systems.MySql
{
class Credential
{
}
}

11
Systems/MySql/Database.cs Normal file
View File

@@ -0,0 +1,11 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sdaleo.Systems.MySql
{
class Database
{
}
}

11
Systems/MySql/General.cs Normal file
View File

@@ -0,0 +1,11 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sdaleo.Systems.MySql
{
class General
{
}
}

View File

@@ -0,0 +1,11 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sdaleo.Systems.MySql.Internal
{
class Validation
{
}
}

View File

@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sdaleo.Systems.Postgres.Internal;
namespace Sdaleo.Systems.Postgres
{
/// <summary>
/// Handles SQL CE Credentials, to be
/// used by all our SQL CE Functions
/// </summary>
public class PgSqlCredential
{
}
}

View File

@@ -0,0 +1,11 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sdaleo.Systems.Postgres
{
class Database
{
}
}

View File

@@ -0,0 +1,11 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sdaleo.Systems.Postgres
{
class General
{
}
}

View File

@@ -0,0 +1,166 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sdaleo.Systems.Postgres.Internal
{
/// <summary>
/// Central Location for Postgres Input Validation
/// </summary>
internal class Validation
{
#region Private Character Validation Declaration
private const string CharSet_AllowedCharsAlphaNum = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
private const string CharSet_AllowedCharsServerName = CharSet_AllowedCharsAlphaNum + ":\\ _!@#$%^&()-+{}[],.;`~";
private const string CharSet_AllowedCharsInstanceName = CharSet_AllowedCharsAlphaNum + ":\\ _!@#$%^&()-+{}[],.;`~";
private const string CharSet_AllowedCharsPassword = CharSet_AllowedCharsAlphaNum + "_!@#$%^&()-+{}[],.;`~";
private const string CharSet_AllowedCharsTableName = CharSet_AllowedCharsAlphaNum + " -_";
/// <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;
}
#endregion
#region Name Validators
/// <summary>
/// Main Validation Function to validate Server Names
/// </summary>
/// <param name="strServerName">Name of a Server</param>
/// <returns>true if valid, false otherise</returns>
internal static bool IsValidServerName(string strServerName)
{
if (String.IsNullOrEmpty(strServerName))
{
return false;
}
else if (strServerName.Length < 1 || strServerName.Length > 248) // limit server Name length
{
return false;
}
else if (!ContainsOnlyLegalChars(strServerName, CharSet_AllowedCharsServerName))
{
return false;
}
else
{
return true;
}
}
/// <summary>
/// Main Validation Function to validate Instance Names
/// </summary>
/// <param name="strInstanceName">Name of an Instance</param>
/// <returns>true if valid, false otherise</returns>
internal static bool IsValidInstanceName(string strInstanceName)
{
if (string.IsNullOrEmpty(strInstanceName))
{
return false;
}
else if (strInstanceName.Length < 1 || strInstanceName.Length > 18) // limit Instance Name length
{
return false;
}
else if (!ContainsOnlyLegalChars(strInstanceName, CharSet_AllowedCharsInstanceName))
{
return false;
}
else
{
return true;
}
}
/// <summary>
/// Main Validation Function to validate Passwords
/// </summary>
/// <param name="strPassword">Password</param>
/// <returns>true if valid, false otherise</returns>
internal static bool IsValidPassword(string strPassword)
{
if (String.IsNullOrEmpty(strPassword))
{
return false;
}
else if (strPassword.Length < 1 || strPassword.Length > 40) // limit Password Length
{
return false;
}
else if (!ContainsOnlyLegalChars(strPassword, CharSet_AllowedCharsPassword))
{
return false;
}
else
{
return true;
}
}
/// <summary>
/// Main Validation Function to validate TableName
/// </summary>
/// <param name="strTableName">Name of Table</param>
/// <returns>true if valid, false otherwise</returns>
internal static bool IsValidTableName(string strTableName)
{
if (string.IsNullOrEmpty(strTableName))
{
return false;
}
else if (strTableName.Length < 1 || strTableName.Length > 52) // limit Table Name length
{
return false;
}
else if (!ContainsOnlyLegalChars(strTableName, CharSet_AllowedCharsTableName))
{
return false;
}
else
{
return true;
}
}
#endregion
#region Combination Validators
/// <summary>
/// Validates that the passedin string has both a valid server and a valid Instance
/// </summary>
/// <param name="strServerNameNInstance">a string to check for server and instance</param>
/// <returns>true if valid, false otherwise</returns>
internal static bool IsValidServerNameAndInstanceName(string strServerNameNInstance)
{
if (!string.IsNullOrEmpty(strServerNameNInstance) && (strServerNameNInstance.IndexOf('\\') >= 0))
{
int nIndexLast = strServerNameNInstance.LastIndexOf('\\');
string[] values = new String[] { strServerNameNInstance.Substring(0, nIndexLast), strServerNameNInstance.Substring(nIndexLast + 1) };
if (values.Length == 2)
return IsValidServerName(values[0]) && IsValidInstanceName(values[1]);
}
return false;
}
#endregion
}
}

135
Systems/SQLCE/Credential.cs Normal file
View File

@@ -0,0 +1,135 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sdaleo.Systems.SQLCE
{
/// <summary>
/// Handles SQL CE Credentials, to be
/// used by all our SQL CE Functions
/// </summary>
public class SQLCECredential : IComparable, ICloneable, IConnectDb
{
#region IConnectDb
/// <summary>
/// Let Callers know this is a SQLCE Connection Object
/// </summary>
public DBSystem DBType { get { return DBSystem.SQL_CE; } }
/// <summary>
/// Check to see if the Credential Object consists of valid input
/// </summary>
public bool IsValid
{
get
{
if (!ValidationConsts.IsValidFileNameNPath(DataSource))
return false;
if (!String.IsNullOrEmpty(_UDL.Password) && !ValidationConsts.Generic.IsValidPassword(_UDL.Password))
return false;
return true;
}
}
/// <summary>
///
/// </summary>
public string ConnectionString { get { return _UDL.ConnectionString; } }
/// <summary>
/// SQL CE uses the File Name and Path as the Datasource
/// </summary>
public string DataSource { get { return _UDL.DataSource; } }
/// <summary>
/// SQL CE doesn't use User
/// </summary>
public string User { get { return _UDL.Username; } }
/// <summary>
/// SQL CE doesn't support DBMS like behaviors
/// </summary>
public bool SupportsDBMS { get { return false; } }
/// <summary>
/// SQL CE doesn't support DBMS like behaviors
/// </summary>
public IamDBMS DBMS { get { return null; } }
/// <summary>
/// SQL CE doesn't support Timeouts
/// </summary>
public bool SupportsTimeouts { get { return false; } }
/// <summary>
/// SQL CE doesn't support Timeouts
/// </summary>
public IsupportTimeouts Timeouts { get { return null; } }
#endregion
private UDL _UDL = null;
#region SQLCE Credential Constructors
/// <summary>
/// Create a SQL CE Connection from an UDL Object
/// </summary>
/// <param name="udl"></param>
internal SQLCECredential(UDL udl)
{
if (udl != null)
_UDL = udl;
}
/// <summary>
/// Create an Untrusted SQLCE Credential * No Encryption Used *
/// </summary>
public SQLCECredential(string FileNameNPath)
{
_UDL = new UDL(FileNameNPath, String.Empty);
}
/// <summary>
/// Create a Trusted SQLCE Credential * Encryption Used *
/// </summary>
public SQLCECredential(string FileNameNPath, string strPassword)
{
_UDL = new UDL(FileNameNPath, strPassword);
}
#endregion
#region ICloneable Members
public object Clone()
{
SQLCECredential credential = new SQLCECredential((UDL)this._UDL.Clone());
return credential;
}
#endregion
#region IComparable Members
public int CompareTo(object obj)
{
SQLCECredential otherCredential = obj as SQLCECredential;
if (otherCredential != null)
{
int nCompare = _UDL.CompareTo(otherCredential._UDL);
return nCompare;
}
else
{
throw new ArgumentException("Object is not a SQLCECredential");
}
}
#endregion
}
}

247
Systems/SQLCE/Database.cs Normal file
View File

@@ -0,0 +1,247 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data.SqlServerCe;
namespace Sdaleo.Systems.SQLCE
{
/// <summary>
/// Specific actions for SQL CE Databases
/// </summary>
public class SQLCEDatabase
{
#region Database Create / Exists
/// <summary>
/// Checks to see if we can query the specified server for the Database (Existence check)
/// </summary>
/// <param name="credential">SQL CE Credentials</param>
/// <param name="bExists">Returns true if the Database Exists, false otherwise</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError DatabaseExists(IConnectDb credential, out bool bExists)
{
bExists = false;
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_CE);
if (dbError.ErrorOccured)
return dbError;
// Check for File Existence
if (File.Exists(credential.DataSource))
{
bExists = true;
return dbError;
}
else
return DBError.Create("Database File does not exist");
}
/// <summary>
/// Create a new Database with the specified Credentials
/// </summary>
/// <param name="credential">SQL CE Credentials</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError DatabaseCreate(IConnectDb credential)
{
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_CE);
if (dbError.ErrorOccured)
return dbError;
// First Create the Directory if it doesn't exists
string path = Path.GetDirectoryName(credential.DataSource);
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
// Now try to create the database if it doesn't exists
bool bExists = false;
dbError = DatabaseExists(credential, out bExists);
if (!bExists)
{
try
{
using (SqlCeEngine engine = new SqlCeEngine(credential.ConnectionString))
{
engine.CreateDatabase();
}
}
catch (SqlCeException e)
{
dbError = DBMS.CreateErrorDBRetVal(DBSystem.SQL_CE, e);
}
}
return dbError;
}
#endregion
#region Database Copy / Delete
/// <summary>
/// Copies a specified SQL CE Database to a new specified Database
/// </summary>
/// <param name="SourceCredential">SQL CE Credentials of Source Database</param>
/// <param name="DestinationCredential">SQLCE Credential of Destination Database To be copied To</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError DatabaseCopy(IConnectDb SourceCredential, IConnectDb DestinationCredential)
{
DBError dbError = ValidationConsts.IsCredentialValid(SourceCredential, DBSystem.SQL_CE);
if (dbError.ErrorOccured)
return dbError;
dbError = ValidationConsts.IsCredentialValid(DestinationCredential, DBSystem.SQL_CE);
if (dbError.ErrorOccured)
return dbError;
// Make sure the Source Database exists
bool bExists = false;
dbError = DatabaseExists(SourceCredential, out bExists);
if (!bExists)
return dbError;
// Make sure the Destination Database does NOT Exist
bExists = false;
dbError = DatabaseExists(DestinationCredential, out bExists);
if (bExists)
return DBError.Create("Destination Credential Database already exists");
try
{
File.Copy(SourceCredential.DataSource, DestinationCredential.DataSource);
}
catch (Exception ex)
{
dbError = DBError.Create(ex.Message);
}
return dbError;
}
/// <summary>
/// Delete a specified SQLCE Database
/// </summary>
/// <param name="credential">SQL CE Credentials</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError DatabaseDelete(IConnectDb credential)
{
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_CE);
if (dbError.ErrorOccured)
return dbError;
// Make sure the Source Database exists
bool bExists = false;
dbError = DatabaseExists(credential, out bExists);
if (!bExists)
return dbError;
try
{
File.Delete(credential.DataSource);
}
catch (Exception ex)
{
dbError = DBError.Create(ex.Message);
}
return dbError;
}
#endregion
#region Database Integrity
/// <summary>
/// Shrinks the specified Database to reclaim wasted space
/// </summary>
/// <param name="credential">SQL CE Credentials</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError DatabaseShrink(IConnectDb credential)
{
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_CE);
if (dbError.ErrorOccured)
return dbError;
// Now try to shrink the database if it exists
bool bExists = false;
dbError = DatabaseExists(credential, out bExists);
if (bExists)
{
try
{
using (SqlCeEngine engine = new SqlCeEngine(credential.ConnectionString))
{
engine.Shrink();
}
}
catch (SqlCeException e)
{
dbError = DBMS.CreateErrorDBRetVal(DBSystem.SQL_CE, e);
}
}
return dbError;
}
/// <summary>
/// Verifies the specified Database in case it is corrupted
/// </summary>
/// <param name="credential">SQL CE Credentials</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError DatabaseVerify(IConnectDb credential)
{
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_CE);
if (dbError.ErrorOccured)
return dbError;
// Now try to repair the database if it exists
bool bExists = false;
dbError = DatabaseExists(credential, out bExists);
if (bExists)
{
try
{
using (SqlCeEngine engine = new SqlCeEngine(credential.ConnectionString))
{
engine.Verify();
}
}
catch (SqlCeException e)
{
dbError = DBMS.CreateErrorDBRetVal(DBSystem.SQL_CE, e);
}
}
return dbError;
}
/// <summary>
/// Repairs the specified Database in case it is corrupted
/// </summary>
/// <param name="credential">SQL CE Credentials</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError DatabaseRepair(IConnectDb credential)
{
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_CE);
if (dbError.ErrorOccured)
return dbError;
// Now try to repair the database if it exists
bool bExists = false;
dbError = DatabaseExists(credential, out bExists);
if (bExists)
{
try
{
using (SqlCeEngine engine = new SqlCeEngine(credential.ConnectionString))
{
// Specify null destination connection string for in-place repair
engine.Repair(null, RepairOption.RecoverAllPossibleRows);
}
}
catch (SqlCeException e)
{
dbError = DBMS.CreateErrorDBRetVal(DBSystem.SQL_CE, e);
}
}
return dbError;
}
#endregion
}
}

41
Systems/SQLCE/General.cs Normal file
View File

@@ -0,0 +1,41 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sdaleo.Systems.SQLCE
{
/// <summary>
/// General SQL CE Functions
/// </summary>
public class SQLCEGeneral
{
/// <summary>
/// Quick Check function to see if the passed in credential allows us to connect to the database,
/// It also verifies that there are any Tables in the Database
/// </summary>
/// <param name="credential">SQL CE Credentials</param>
/// <param name="CanConnect">Returns true if successfull in connecting to the database</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError SQLCECheckConnection(IConnectDb credential, out bool CanConnect)
{
CanConnect = false;
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_CE);
if (dbError.ErrorOccured)
return dbError;
// First Verify that the Database Exists
bool bExists = false;
dbError = SQLCEDatabase.DatabaseExists(credential, out bExists);
if (!bExists)
return dbError;
////
// TODO: Make sure that we can read any tables from the db
////
return null;
}
}
}

View File

@@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sdaleo.Systems.SQLCE
{
/// <summary>
/// SQL CE Database Error Constants to Use to handle specific Errors
/// </summary>
internal static class ErrorConst
{
}
}

View File

@@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sdaleo.Systems;
namespace Sdaleo.Systems.SQLCE
{
/// <summary>
/// SQL CE Custom Validation
/// </summary>
internal static class Validation
{
/// <summary>
/// validate SQL CE Table Names
/// </summary>
/// <param name="strTableName"></param>
/// <returns></returns>
public static DBError IsValidTableName(string strTableName)
{
if (string.IsNullOrEmpty(strTableName))
{
return DBError.Create("TableName is null");
}
else if (strTableName.Length < 1 || strTableName.Length > 52) // limit Table Name length
{
return DBError.Create("TableName length is invalid");
}
else if (!ValidationConsts.ContainsOnlyLegalChars(strTableName, ValidationConsts.CharSet_AllowedTableNames))
{
return DBError.Create("TableName contains illegal characters");
}
else
{
return new DBError();
}
}
}
}

95
Systems/SQLCE/Table.cs Normal file
View File

@@ -0,0 +1,95 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace Sdaleo.Systems.SQLCE
{
/// <summary>
/// Specific actions for SQL CE Tables in a Database
/// </summary>
public class SQLCETable
{
/// <summary>
/// Returns all the Table Names for the specified SQL CE Credential
/// </summary>
/// <param name="credential">SQL CE Credentials</param>
/// <param name="Tables">array of table names, or null if error occured</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError Tables(IConnectDb credential, out string[] Tables)
{
Tables = null;
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_CE);
if (dbError.ErrorOccured)
return dbError;
// Execute the Query
string sql = "Select [TABLE_NAME] From INFORMATION_SCHEMA.TABLES Order By [TABLE_NAME]";
DB db = DB.Create(credential);
DBRetVal retVal = db.FillDataTable(sql);
if (retVal.IsValid)
{
List<String> retList = new List<string>();
foreach (DataRow row in retVal.GetDataTableRetVal().Rows)
retList.Add(row["TABLE_NAME"].ToString());
Tables = retList.ToArray();
}
return retVal;
}
/// <summary>
/// Check to see if the Table Exists on the specified SQL CE Credentials
/// </summary>
/// <param name="credential">SQL CE Credentials</param>
/// <param name="TableName">Specify the TableName to check for (required)</param>
/// <param name="bExists">true if exists, false otherwise</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError TableExists(IConnectDb credential, string TableName, out bool bExists)
{
bExists = false;
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_CE);
if (dbError.ErrorOccured)
return dbError;
dbError = Validation.IsValidTableName(TableName);
if (dbError.ErrorOccured)
return dbError;
// Execute the Query
string sql = String.Format("Select [TABLE_NAME] From INFORMATION_SCHEMA.TABLES Where [TABLE_NAME] = '{0}' Order By [TABLE_NAME]", TableName);
DB db = DB.Create(credential);
DBRetVal retVal = db.ExecuteScalar(sql);
bExists = !retVal.IsValid;
return retVal;
}
/// <summary>
/// Changes the Table Name for the specified Table
/// </summary>
/// <param name="credential">SSQL CE Credentials</param>
/// <param name="TableName">Name of Table (required)</param>
/// <param name="TableNameNew">Name of Table New (required)</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError TableRename(IConnectDb credential, string TableName, string TableNameNew)
{
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_CE);
if (dbError.ErrorOccured)
return dbError;
dbError = Validation.IsValidTableName(TableName);
if (dbError.ErrorOccured)
return dbError;
dbError = Validation.IsValidTableName(TableNameNew);
if (dbError.ErrorOccured)
return dbError;
// Execute the Query
string sql = String.Format("sp_rename @objname = '{0}', @newname = '{1}', @objtype = 'OBJECT'", TableName, TableNameNew);
DB db = DB.Create(credential);
DBRetVal retVal = db.ExecuteNonQuery(sql);
return retVal;
}
}
}

View File

@@ -0,0 +1,279 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sdaleo.Systems.SQLServer
{
/// <summary>
/// Handles SQL Server Credentials, to be
/// used by all our SQL Server Functions
/// </summary>
public class SQLServerCredential : IComparable, ICloneable, IConnectDb, IamDBMS, IsupportTimeouts
{
#region IConnectDb
/// <summary>
/// Let Callers know this is a SQL Server Connection Object
/// </summary>
public DBSystem DBType { get { return DBSystem.SQL_SERVER; } }
/// <summary>
/// Check to see if the Credential Object consists of valid input
/// </summary>
public bool IsValid
{
get
{
if (!Validation.IsValidDataSource(_UDL.DataSource))
return false;
if (!_UDL.TrustedConnection && !ValidationConsts.Generic.IsValidUserCredential(_UDL.Username, _UDL.Password))
return false;
if (!String.IsNullOrEmpty(_UDL.DataBase) && IsDatabaseSet)
return false;
return true;
}
}
/// <summary>
///
/// </summary>
public string ConnectionString { get { return _UDL.ConnectionString; } }
/// <summary>
/// SQL Server uses Server N' Instance
/// </summary>
public string DataSource { get { return _UDL.DataSource; } }
/// <summary>
/// SQL Server requires a user
/// </summary>
public string User { get { return _UDL.Username; } }
/// <summary>
/// SQL Server supports is a DBMS
/// </summary>
public bool SupportsDBMS { get { return true; } }
/// <summary>
/// SQL Server is a DBMS
/// </summary>
public IamDBMS DBMS { get { return this; } }
/// <summary>
/// SQL Server supports Timeouts
/// </summary>
public bool SupportsTimeouts { get { return true; } }
/// <summary>
/// SQL Server supports Timeouts
/// </summary>
public IsupportTimeouts Timeouts { get { return this; } }
#endregion
private UDL _UDL = null;
#region SQL Server Credential Constructors
/// <summary>
/// Create a SQL Server Connection from an UDL Object
/// </summary>
/// <param name="udl"></param>
internal SQLServerCredential(UDL udl)
{
if (udl != null)
_UDL = udl;
}
/// <summary>
/// Create an Untrusted SQLServer Credential with an Initial DB Specified
/// </summary>
public SQLServerCredential(string strServer, string strInstance, string strDatabase, string strUser, string strPassword)
{
_UDL = new UDL(strDatabase, strUser, strPassword, strServer, strInstance);
}
/// <summary>
/// Create an Untrusted SQLServer Credential with no Initial DB Specified
/// </summary>
public SQLServerCredential(string strServer, string strInstance, string strUser, string strPassword)
{
_UDL = new UDL(String.Empty, strUser, strPassword, strServer, strInstance);
}
/// <summary>
/// Create a Trusted SQLServer Credential with an Initial DB Specified
/// </summary>
public SQLServerCredential(string strServer, string strInstance, string strDatabase)
{
_UDL = new UDL(strDatabase, String.Empty, String.Empty, strServer, strInstance, true);
}
/// <summary>
/// Create a Trusted SQLServer Credential with no Initial DB Specified
/// </summary>
public SQLServerCredential(string strServer, string strInstance)
{
_UDL = new UDL(String.Empty, String.Empty, String.Empty, strServer, strInstance, true);
}
/// <summary>
/// Create a Trusted SQLServer Credential with SQLExpress on the Local Machine to Attach a DB File (Creates a User Instance)
/// </summary>
/// <param name="strAttachDBFile"></param>
public SQLServerCredential(string strAttachSQLDBFile)
{
_UDL = new UDL(String.Empty, String.Empty, String.Empty, String.Empty, "SQLEXPRESS", strAttachSQLDBFile, true, false);
}
#endregion
#region IamDBMS
public string Server { get { return _UDL.ServerAddress; } }
public string Instance { get { return _UDL.InstanceName; } }
public string Database { get { return _UDL.DataBase; } }
public bool IsDatabaseSet
{
get
{
DBError dbError = Validation.IsValidDatabaseName(Database);
return !dbError.ErrorOccured;
}
}
public bool IsDatabaseSetAndNonSystem
{
get
{
if (IsDatabaseSet && !SQLServerUtilities.IsSystemDatabaseName(Database))
return true;
return false;
}
}
public bool IsDatabaseSetAndNonDefault
{
get
{
if (IsDatabaseSet && !SQLServerUtilities.IsDefaultDatabaseName(Database))
return true;
return false;
}
}
/// <summary>
/// Use this to quickly create a new SQLServerCredential with a different DatabaseName
/// </summary>
/// <param name="strDatabaseName">Name of Database To Set</param>
/// <returns>a new SQLServerCredential Object</returns>
public IConnectDb WithDatabase(string strDatabaseName)
{
// Create a new Credential Object and change the DatabaseName
SQLServerCredential credential = (SQLServerCredential)Clone();
credential._UDL.DataBase = strDatabaseName;
return credential;
}
/// <summary>
/// Use this to quickly create a new SQLServerCredential with no DatabaseName defined
/// </summary>
/// <returns>a new SQLServerCredential Object</returns>
public IConnectDb WithoutDatabase()
{
return WithDatabase(String.Empty);
}
#endregion
#region IsupportTimeouts
public const int DEFAULT_COMMAND_TIMEOUT = 45;
private uint _CommandTimeout = DEFAULT_COMMAND_TIMEOUT;
public uint CommandTimeout
{
get { return _CommandTimeout; }
set { _CommandTimeout = value; }
}
public uint ConnectionTimeout { get { return _UDL.ConnectionTimeout; } set { _UDL.ConnectionTimeout = value; } }
/// <summary>
/// Use this to quickly create a new SQLServerCredential with a different connection timeout
/// </summary>
/// <param name="nConnectionTimeout">Specify the Connection Timeout</param>
/// <returns>a new SQLServerCredential Object</returns>
public IConnectDb WithConnectionTimeout(uint nConnectionTimeout)
{
// Create a new Credential Object and change the Timeouts
SQLServerCredential credential = (SQLServerCredential)Clone();
credential.ConnectionTimeout = nConnectionTimeout;
return credential;
}
/// <summary>
/// Use this to quickly create a new SQLServerCredential with a different command timeout
/// </summary>
/// <param name="nCommandTimeout">Specify the Command Timeout</param>
/// <returns>a new SQLServerCredential Object</returns>
public IConnectDb WithCommandTimeout(uint nCommandTimeout)
{
// Create a new Credential Object and change the Timeouts
SQLServerCredential credential = (SQLServerCredential)Clone();
credential.CommandTimeout = nCommandTimeout;
return credential;
}
/// <summary>
/// Use this to quickly create a new SQLServerCredential with different Timeouts
/// </summary>
/// <param name="nConnectionTimeout">Specify the Connection Timeout</param>
/// <param name="nCommandTimeout">Specify the Command Timeout</param>
/// <returns>a new SQLServerCredential Object</returns>
public IConnectDb WithTimeouts(uint nConnectionTimeout, uint nCommandTimeout)
{
// Create a new Credential Object and change the Timeouts
SQLServerCredential credential = (SQLServerCredential)Clone();
credential.ConnectionTimeout = nConnectionTimeout;
credential.CommandTimeout = nCommandTimeout;
return credential;
}
#endregion
#region ICloneable Members
public object Clone()
{
SQLServerCredential credential = new SQLServerCredential((UDL)this._UDL.Clone());
credential.CommandTimeout = this.CommandTimeout;
return credential;
}
#endregion
#region IComparable Members
public int CompareTo(object obj)
{
SQLServerCredential otherCredential = obj as SQLServerCredential;
if (otherCredential != null)
{
int nCompare = _UDL.CompareTo(otherCredential._UDL);
return nCompare;
}
else
{
throw new ArgumentException("Object is not a SQLServerCredential");
}
}
#endregion
}
}

View File

@@ -0,0 +1,572 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace Sdaleo.Systems.SQLServer
{
/// <summary>
/// Specific actions for SQL Server Databases
/// </summary>
public class SQLServerDatabase
{
#region Database List
/// <summary>
/// Returns a array of any found Databases on the specified SQL Server intance
/// </summary>
/// <param name="credential">SQL Server Credentials</param>
/// <param name="DatabaseList">list of Databases if any found, or null if not</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError DatabasesListAll(IConnectDb credential, out string[] DatabaseList)
{
DatabaseList = null;
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_SERVER);
if (dbError.ErrorOccured)
return dbError;
// Execute the Query
string sql = "SELECT [name] FROM sys.databases";
DB db = DB.Create(credential.DBMS.WithoutDatabase());
DBRetVal retVal = db.FillDataTable(sql);
if (retVal.IsValid)
{
List<string> DataBaseNames = new List<String>();
foreach (DataRow row in retVal.GetDataTableRetVal().Rows)
DataBaseNames.Add(row["name"].ToString());
DatabaseList = DataBaseNames.ToArray();
}
return retVal;
}
/// <summary>
/// Returns a array of any found Databases that are NOT SQL Default Databases (like master, model, etc);
/// </summary>
/// <param name="credential">SQL Server Credentials</param>
/// <param name="DatabaseList">list of Databases if any found, or null if not</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError DatabasesListNonDefault(IConnectDb credential, out string[] DatabaseList)
{
DatabaseList = null;
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_SERVER);
if (dbError.ErrorOccured)
return dbError;
// Look for all Databases that are Non-Default
string[] DatabaseListAll = null;
DBError retVal = DatabasesListAll(credential, out DatabaseListAll);
if(!retVal.ErrorOccured && DatabaseListAll != null)
{
List<String> DatabaseListNonDefault = new List<String>();
foreach (string DatabaseName in DatabaseListAll)
{
if(!SQLServerUtilities.IsDefaultDatabaseName(DatabaseName))
DatabaseListNonDefault.Add(DatabaseName);
}
DatabaseList = DatabaseListNonDefault.ToArray();
}
return retVal;
}
#endregion
#region Alter Database
/// <summary>
/// Use this to Raise the specified Database to it's highest Compatibility Level as allowed
/// on the specified SQLServer (2005/2008/etc.)
/// </summary>
/// <param name="credential">SQL Server Credentials with Database Info</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError DatabaseRaiseCompatibility(IConnectDb credential)
{
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_SERVER);
if (dbError.ErrorOccured)
return dbError;
if (!credential.DBMS.IsDatabaseSetAndNonSystem)
return DBError.Create("Invalid Database Passed In via Credential");
// How to change compatibility level has changed in sql server 2008 (so we'll try to
// use the newer way of doing it if we can.
string sql = string.Empty;
SQLServerVersion ServerVersion;
DBError dberror = SQLServerGeneral.GetSQLServerVersion(credential, out ServerVersion);
if (dberror.ErrorOccured)
return dberror;
switch (ServerVersion)
{
case SQLServerVersion.SQL_SERVER_2008:
sql = String.Format("ALTER DATABASE [{0}] SET COMPATIBILITY_LEVEL = {1}", credential.DBMS.Database, (int)ServerVersion);
break;
default:
sql = String.Format("EXEC sp_dbcmptlevel [{0}], {1}", credential.DBMS.Database, (int)ServerVersion);
break;
}
// Execute the Query and return result
DB db = DB.Create(credential.DBMS.WithoutDatabase());
DBRetVal retVal = db.ExecuteNonQuery(sql);
return retVal;
}
/// <summary>
/// Allows the caller to set the Database into Single User Mode. This is * microsoft recommended *
/// for certain type of operations on the Database to make sure nobody else can use the DB.
/// Note: If Database is in Use * This will timeout
/// </summary>
/// <param name="credential">SQL Server Credentials with Database Info</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError DatabaseSetToSingleUserMode(IConnectDb credential)
{
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_SERVER);
if (dbError.ErrorOccured)
return dbError;
if (!credential.DBMS.IsDatabaseSetAndNonSystem)
return DBError.Create("Invalid Database Passed In via Credential");
// Execute the Query and return result
string sql = String.Format("ALTER DATABASE [{0}] SET SINGLE_USER", credential.DBMS.Database);
DB db = DB.Create(credential.DBMS.WithoutDatabase());
DBRetVal retVal = db.ExecuteNonQuery(sql);
return retVal;
}
/// <summary>
/// Allows the caller to set the Database into Multi User Mode. This should be called
/// if the caller called DatabaseSetToSingleUserMode() previously
/// </summary>
/// <param name="credential">SQL Server Credentials with Database Info</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError DatabaseSetToMultiUserMode(IConnectDb credential)
{
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_SERVER);
if (dbError.ErrorOccured)
return dbError;
if (!credential.DBMS.IsDatabaseSetAndNonSystem)
return DBError.Create("Invalid Database Passed In via Credential");
// Execute the Query and return result
string sql = String.Format("ALTER DATABASE [{0}] SET MULTI_USER", credential.DBMS.Database);
DB db = DB.Create(credential.DBMS.WithoutDatabase());
DBRetVal retVal = db.ExecuteNonQuery(sql);
return retVal;
}
/// <summary>
/// Calls DBCC SHRINKDATABASE and DBCC UPDATEUSAGE on the passed in Database
/// </summary>
/// <param name="credential">SQL Server Credentials with Database Info</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError DatabaseShrink(IConnectDb credential)
{
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_SERVER);
if (dbError.ErrorOccured)
return dbError;
if (!credential.DBMS.IsDatabaseSetAndNonSystem)
return DBError.Create("Invalid Database Passed In via Credential");
// Execute the Query and return result
DB db = DB.Create(credential.DBMS.WithoutDatabase());
string sql = String.Format("DBCC SHRINKDATABASE ([{0}])", credential.DBMS.Database);
DBRetVal retVal = db.ExecuteNonQuery(sql);
if (!retVal.ErrorOccured)
{
sql = String.Format("DBCC UPDATEUSAGE ([{0}])", credential.DBMS.Database);
retVal = db.ExecuteNonQuery(sql);
}
return retVal;
}
/// <summary>
/// Iterates all tables on the database and enables/disables all trigers for each table
/// </summary>
/// <param name="credential">SQL Server Credentials with Database Info</param>
/// <param name="bEnable">true to enable, false to disable</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError EnableDisableAllTriggers(IConnectDb credential, bool bEnable)
{
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_SERVER);
if (dbError.ErrorOccured)
return dbError;
if (!credential.DBMS.IsDatabaseSetAndNonSystem)
return DBError.Create("Invalid Database Passed In via Credential");
// Get All Table Names from the Database
string[] TableNames = null;
DBError dberror = SQLServerTable.Tables(credential, out TableNames);
if (dberror.ErrorOccured)
return dberror;
// Execute the Query and return result
DB db = DB.Create(credential);
DBRetVal retVal = new DBRetVal();
foreach (string TableName in TableNames)
{
// Execute the Query for each Table
string sql = String.Format("ALTER TABLE [{0}] {1} TRIGGER ALL", TableName, (bEnable ? "ENABLE" : "DISABLE"));
retVal = db.ExecuteNonQuery(sql);
if (retVal.ErrorOccured)
break;
}
return retVal;
}
#endregion
#region Databae Create / Exists
/// <summary>
/// Checks to see if we can query the specified server for the Database (Existence check)
/// </summary>
/// <param name="credential">SQL Server Credentials with Database Info</param>
/// <param name="bExists">Returns true if the Database Exists, false otherwise</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError DatabaseExists(IConnectDb credential, out bool bExists)
{
bExists = false;
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_SERVER);
if (dbError.ErrorOccured)
return dbError;
if (!credential.DBMS.IsDatabaseSetAndNonSystem)
return DBError.Create("Invalid Database Passed In via Credential");
// Execute the Query and return result
string sql = String.Format("EXEC sp_helpdb @dbname = [{0}]", credential.DBMS.Database);
DB db = DB.Create(credential.DBMS.WithoutDatabase());
DBRetVal retVal = db.ExecuteNonQuery(sql);
bExists = !retVal.ErrorOccured;
return retVal;
}
/// <summary>
/// Create a new Database with the specified DatabaseName in the specified DataPath, if specified, or DefaultPath otherwise
/// </summary>
/// <param name="credential">SQL Server Credentials with Database Info</param>
/// <param name="DataPath">Data Path to Create Database in (not required)</param>
/// <param name="TryAttachDBOnError">true to allow Attach Database when error occurs, false otherwise</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError DatabaseCreate(IConnectDb credential, string DataPath, bool TryAttachDBOnError)
{
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_SERVER);
if (dbError.ErrorOccured)
return dbError;
if (!credential.DBMS.IsDatabaseSetAndNonSystem)
return DBError.Create("Invalid Database Passed In via Credential");
// if DataPath is empty, get default datapath for SQL ServerInstance
if (String.IsNullOrEmpty(DataPath))
SQLServerGeneral.SQLServerDefaultPath(credential.DBMS.WithoutDatabase(), out DataPath);
// Fill in Database FileName and Path Details
string sql = String.Format("CREATE DATABASE [{0}] ", credential.DBMS.Database);
if (!String.IsNullOrEmpty(DataPath))
sql += String.Format(@"ON (NAME = [{0}_dat], FILENAME = '{1}\{0}.dat') LOG ON (NAME = [{0}_log], FILENAME = '{1}\{0}_log.ldf')", credential.DBMS.Database, DataPath);
// Execute the Command
DB db = DB.Create(credential.DBMS.WithoutDatabase());
DBRetVal retVal = db.ExecuteNonQuery(sql);
// Upon DB Creation error, see if we could possibly attach the DB
bool bErrorOccuredThatCouldMaybeBeResolvedByAttaching = false;
if (retVal.ErrorOccured && !retVal.GetAllErrorNumbers.Contains(ErrorConst.ERROR_DB_ALREADY_EXISTS) && (
retVal.GetAllErrorNumbers.Contains(ErrorConst.ERROR_DB_SOME_FILE_NAMES_COULD_NOT_BE_CREATED) ||
retVal.GetAllErrorNumbers.Contains(ErrorConst.ERROR_DB_CAN_NOT_CREATE_FILE_BECAUSE_IT_ALREADY_EXISTS) ||
retVal.GetAllErrorNumbers.Contains(ErrorConst.ERROR_DB_THERE_ALREADY_IS_AN_OBJECT_IN_THE_DB_WITH_THIS_NAME)))
{
bErrorOccuredThatCouldMaybeBeResolvedByAttaching = true;
}
// Upon Error, and if we are allowed to attach && datapath is valid, try to attach
if (retVal.ErrorOccured && TryAttachDBOnError && bErrorOccuredThatCouldMaybeBeResolvedByAttaching && !String.IsNullOrEmpty(DataPath))
{
String[] strFileNames = new String[]
{
string.Format(@"{1}\{0}.dat", credential.DBMS.Database, DataPath),
string.Format(@"{1}\{0}_log.ldf", credential.DBMS.Database, DataPath)
};
DBError retValError = DatabaseAttach(credential, strFileNames);
return retValError;
}
return retVal;
}
#endregion
#region Database Attach / Dettach
/// <summary>
/// Attaches a Database to an SQL Server Instance
/// </summary>
/// <param name="credential">SQL Server Credentials with Database Info</param>
/// <param name="strFileNames">Pass in the filenames when attaching Database (required)</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError DatabaseAttach(IConnectDb credential, string[] strFileNames)
{
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_SERVER);
if (dbError.ErrorOccured)
return dbError;
if (!credential.DBMS.IsDatabaseSetAndNonSystem)
return DBError.Create("Invalid Database Passed In via Credential");
if ((strFileNames == null || strFileNames.Length == 0))
return DBError.Create("Invalid FileNames Passed In");
// Generate the SQL Query
string sql = String.Format("EXEC sp_attach_db @dbname = [{0}]", credential.DBMS.Database);
for (int i = 0; i < strFileNames.Length; ++i)
sql = sql + String.Format(", @filename{0:d1} = '{1}'", (i + 1), strFileNames[i]);
// Execute the Query
DB db = DB.Create(credential.DBMS.WithoutDatabase());
DBRetVal retVal = db.ExecuteNonQuery(sql);
// If Error Occured try renaming dat files to mdf * legacy code *
bool bRetryAttachingErrorOccured = false;
if (retVal.ErrorOccured &&
(retVal.GetAllErrorNumbers.Contains(ErrorConst.ERROR_DB_THERE_ALREADY_IS_AN_OBJECT_IN_THE_DB_WITH_THIS_NAME) ||
retVal.GetAllErrorNumbers.Contains(ErrorConst.ERROR_DB_DEVICE_ACTIVATION_FAILED)))
{
bRetryAttachingErrorOccured = true;
}
// Retry on Attach if failure occured &
// filenames contain .dat files & we have an attach specific error * LEGACY CODE Usuage *
if (retVal.ErrorOccured && bRetryAttachingErrorOccured)
{
bool bRetry = false;
List<string> retryArr = new List<string>();
foreach (string strFileName in strFileNames)
{
if (strFileName.Contains(".dat"))
{
strFileName.Replace(".dat", ".mdf");
bRetry = true;
}
retryArr.Add(strFileName);
}
// Only do an actually retry if .dat files were replaced
if (bRetry)
return DatabaseAttach(credential, retryArr.ToArray());
}
return retVal;
}
/// <summary>
/// Dettaches a Database from an SQL Server Instance
/// </summary>
/// <param name="credential">SQL Server Credentials with Database Info</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError DatabaseDettach(IConnectDb credential)
{
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_SERVER);
if (dbError.ErrorOccured)
return dbError;
if (!credential.DBMS.IsDatabaseSetAndNonSystem)
return DBError.Create("Invalid Database Passed In via Credential");
// Execute the Query and return result
string sql = String.Format("sp_detach_db @dbname = [{0}]", credential.DBMS.Database);
DB db = DB.Create(credential.DBMS.WithoutDatabase());
DBRetVal retVal = db.ExecuteNonQuery(sql);
return retVal;
}
#endregion
#region Database Copy
/// <summary>
/// Copies a specified Database on the specified SQLServer into a new specified Database
/// </summary>
/// <param name="credential">SQL Server Credentials with Database Info</param>
/// <param name="DatabaseNameDest">Name of Database To be copied To (required)</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError DatabaseCopy(IConnectDb credential, string DatabaseNameDest)
{
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_SERVER);
if (dbError.ErrorOccured)
return dbError;
if (!credential.DBMS.IsDatabaseSetAndNonSystem)
return DBError.Create("Invalid Database Passed In via Credential");
dbError = Validation.IsValidDatabaseName(DatabaseNameDest);
if (dbError.ErrorOccured)
return dbError;
string strDefaultPath;
DBError dberror = SQLServerGeneral.SQLServerDefaultPath(credential, out strDefaultPath);
if (dberror.ErrorOccured)
return dberror;
// First Step - Backup the source database to a custom Backup file
string sql = String.Format(@"BACKUP DATABASE [{0}] TO DISK = '{1}\{0}.DB Backup' WITH INIT, NAME = '{0} Backup', PASSWORD = 'dbCopy Backup', MEDIAPASSWORD = 'XaseY 1-33', INIT , FORMAT", credential.DBMS.Database, strDefaultPath);
DB db = DB.Create(credential.DBMS.WithoutDatabase());
DBRetVal retVal = db.ExecuteNonQuery(sql);
if (retVal.ErrorOccured)
return retVal;
// Second Step - Retrieve the dat & log Logical Names for the newly backed-up Database
string strDataLogical = string.Empty;
string strLogLogical = string.Empty;
sql = String.Format(@"RESTORE FILELISTONLY FROM DISK = '{0}\{1}.DB Backup' WITH FILE = 1, PASSWORD = 'dbCopy Backup', MEDIAPASSWORD = 'XaseY 1-33'", strDefaultPath, credential.DBMS.Database);
retVal = db.FillDataTable(sql);
if (!retVal.IsValid)
return retVal;
foreach (DataRow row in retVal.GetDataTableRetVal().Rows)
{
switch (row["Type"].ToString())
{
case "D":
strDataLogical = row["LogicalName"].ToString();
break;
case "L":
strLogLogical = row["LogicalName"].ToString();
break;
}
}
if (String.IsNullOrEmpty(strDataLogical) || String.IsNullOrEmpty(strLogLogical))
return DBError.Create("DataLogical or LogLogical could not be found");
// Third Step - Restore Backup file to the new Database name
sql = String.Format(@"RESTORE DATABASE [{0}] FROM DISK = '{1}\{2}.DB Backup' WITH FILE = 1, PASSWORD = 'dbCopy Backup', MEDIAPASSWORD = 'XaseY 1-33', MOVE '{3}' TO '{1}\{0}.dat', MOVE '{4}' TO '{1}\{0}_log.ldf', RECOVERY, REPLACE", DatabaseNameDest, strDefaultPath, credential.DBMS.Database, strDataLogical, strLogLogical);
retVal = db.ExecuteNonQuery(sql);
if (retVal.ErrorOccured)
{
// try again
retVal = db.ExecuteNonQuery(sql);
if (!retVal.IsValid)
return retVal;
}
// Fourth Step - Try to Delete the Backup file (No Need to have a potentially massive data file just sitting there
// ~SQL Server blocked access to procedure 'sys.xp_cmdshell' of component 'xp_cmdshell' because this component is turned off as part of the
// security configuration for this server. A system administrator can enable the use of 'xp_cmdshell' by using sp_configure.
// For more information about enabling 'xp_cmdshell', see "Surface Area Configuration" in SQL Server Books Online
// sql = String.Format("exec master.dbo.xp_cmdshell 'del /Q /F \"{0}\\{1}.DB Backup\"'", strDefaultPath, DatabaseNameSrc);
// db.ExecuteNonQuery(sql);
// Legacy Usuage, we are leaving the Backup File behind (*leaking the file* so to speak)
return retVal;
}
/// <summary>
/// Copies a specified Database on the specified SQLServer into a new specified Database onto a different specified Instance * Must be on Same Server *
/// </summary>
/// <param name="credentialSrc">SQL Server Credentials with Database Info to be copied from (required)</param>
/// <param name="credentialDest">SQL Server Credentials with Database Info to be copied to (required)</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError DatabaseCopySepInst(IConnectDb credentialSrc, IConnectDb credentialDst)
{
DBError dbError = ValidationConsts.IsCredentialValid(credentialSrc, DBSystem.SQL_SERVER);
if (dbError.ErrorOccured)
return dbError;
if (!credentialSrc.DBMS.IsDatabaseSetAndNonSystem)
return DBError.Create("Invalid Database Passed In via Credential");
dbError = ValidationConsts.IsCredentialValid(credentialDst, DBSystem.SQL_SERVER);
if (dbError.ErrorOccured)
return dbError;
if (!credentialDst.DBMS.IsDatabaseSetAndNonSystem)
return DBError.Create("Invalid Database Passed In via Credential");
if (String.Compare(credentialSrc.DBMS.Server, credentialDst.DBMS.Server, true) != 0)
return DBError.Create("Must be on the Same Server");
if (String.Compare(credentialSrc.DBMS.Instance, credentialDst.DBMS.Instance, true) == 0)
return DBError.Create("Can not be the same Instance");
// Get Src Default Path *of the DB*
string strDefaultPathSrc;
DBError dberror = SQLServerGeneral.SQLServerDefaultPath(credentialSrc, out strDefaultPathSrc);
if (dberror.ErrorOccured)
return dberror;
// Get Dest Default Path *of the Server*
string strDefaultPathDest;
dberror = SQLServerGeneral.SQLServerDefaultPath(credentialDst, out strDefaultPathDest);
if (dberror.ErrorOccured)
return dberror;
// Make sure that both Paths aren't the same *Two instances should never have the same path!*
if (strDefaultPathSrc.ToUpper() == strDefaultPathDest.ToUpper())
return DBError.Create(String.Format("The File Path of the Source Database {0} and the Destination Database {1} on Server {1} are identical.", credentialSrc.DBMS.Database, credentialDst.DBMS.Database, credentialDst.DBMS.Server));
// Create Src N' Dest Connections * No Limit on the Command timeout *
// Could be very large database that we are trying to copy
DB dbSrc = DB.Create(credentialSrc.DBMS.WithoutDatabase().Timeouts.WithCommandTimeout(0));
DB dbDst = DB.Create(credentialDst.DBMS.WithoutDatabase().Timeouts.WithCommandTimeout(0));
// First Step - Backup the source database to a custom DB Backup file to the DESTINATION path
string sql = String.Format(@"BACKUP DATABASE [{0}] TO DISK = '{1}\{0}.DB Backup' WITH INIT, NAME = '{0} Backup', PASSWORD = 'dbCopy Backup', MEDIAPASSWORD = 'XaseY 1-33', INIT , FORMAT", credentialSrc.DBMS.Database, strDefaultPathSrc);
DBRetVal retVal = dbSrc.ExecuteNonQuery(sql);
if (retVal.ErrorOccured)
return retVal;
// Second Step - Retrieve the dat & log Logical Names for the newly backed-up Database File
string strDataLogical = string.Empty;
string strLogLogical = string.Empty;
sql = String.Format(@"RESTORE FILELISTONLY FROM DISK = '{0}\{1}.DB Backup' WITH FILE = 1, PASSWORD = 'dbCopy Backup', MEDIAPASSWORD = 'XaseY 1-33'", strDefaultPathSrc, credentialSrc.DBMS.Database);
retVal = dbSrc.FillDataTable(sql);
if (!retVal.IsValid)
return retVal;
foreach (DataRow row in retVal.GetDataTableRetVal().Rows)
{
switch (row["Type"].ToString())
{
case "D":
strDataLogical = row["LogicalName"].ToString();
break;
case "L":
strLogLogical = row["LogicalName"].ToString();
break;
}
}
if (String.IsNullOrEmpty(strDataLogical) || String.IsNullOrEmpty(strLogLogical))
return DBError.Create(String.Format("The retrieval of Logical Names for Database '{0}' failed for Server Instance '{1}' in Path '{2}'.", credentialSrc.DBMS.Database, credentialSrc.DataSource, strDefaultPathDest));
// Third Step - Restore Backup file to the new Database name onto the new (Dest) instance
sql = String.Format(@"RESTORE DATABASE [{0}] FROM DISK = '{1}\{2}.DB Backup' WITH FILE = 1, PASSWORD = 'dbCopy Backup', MEDIAPASSWORD = 'XaseY 1-33', MOVE '{3}' TO '{5}\{0}.dat', MOVE '{4}' TO '{5}\{0}_log.ldf', RECOVERY, REPLACE", credentialDst.DBMS.Database, strDefaultPathSrc, credentialSrc.DBMS.Database, strDataLogical, strLogLogical, strDefaultPathDest);
retVal = dbDst.ExecuteNonQuery(sql);
if (!retVal.ErrorOccured)
{
// try again
retVal = dbDst.ExecuteNonQuery(sql);
if (!retVal.IsValid)
return retVal;
}
// Fourth Step - Try to Delete the Backup file (No Need to have a potentially massive data file just sitting there
// ~SQL Server blocked access to procedure 'sys.xp_cmdshell' of component 'xp_cmdshell' because this component is turned off as part of the
// security configuration for this server. A system administrator can enable the use of 'xp_cmdshell' by using sp_configure.
// For more information about enabling 'xp_cmdshell', see "Surface Area Configuration" in SQL Server Books Online
// sql = String.Format("exec master.dbo.xp_cmdshell 'del /Q /F \"{0}\\{1}.DB Backup\"'", strDefaultPath, DatabaseNameSrc);
// db.RunSQLCommandTextExecuteNonQuery(sql);
// Legacy Usuage, we are leaving the Backup File behind (*leaking the file* so to speak)
return retVal;
}
#endregion
}
}

View File

@@ -0,0 +1,482 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Net;
using System.ServiceProcess;
namespace Sdaleo.Systems.SQLServer
{
#region SQLServer General Enums
/// <summary>
/// SQL Server Versions as specified by SQL Server
/// </summary>
public enum SQLServerVersion
{
SQL_SERVER_2000 = 80,
SQL_SERVER_2005 = 90,
SQL_SERVER_2008 = 100,
}
#endregion
/// <summary>
/// General SQL Server Functions
/// </summary>
public class SQLServerGeneral
{
#region SQL Version Functions
/// <summary>
/// Retrieves the SQL Server Version Information from the specified SQL Server Instance
/// (* Prefered Function to use *)
/// </summary>
/// <param name="credential">SQL Server Credentials</param>
/// <param name="version">we pass out the SQL Server Specific Version</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError GetSQLServerVersion(IConnectDb credential, out SQLServerVersion version)
{
version = SQLServerVersion.SQL_SERVER_2000; // Default behavior
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_SERVER);
if (dbError.ErrorOccured)
return dbError;
int nVersion = (int)SQLServerVersion.SQL_SERVER_2000;
DBError dberror = GetSQLServerVersion(credential, out nVersion);
if (dberror.ErrorOccured)
return dberror;
// SQLServerVersion numbers are multiple of 10's
nVersion = nVersion * 10;
try
{
version = (SQLServerVersion)Enum.Parse(typeof(SQLServerVersion), nVersion.ToString());
}
catch (Exception e)
{
dberror = DBError.Create(e.Message);
}
return dberror;
}
/// <summary>
/// Retrieves the SQL Server Version String Information from the specified SQL Server Instance
/// </summary>
/// <param name="credential">SQL Server Credentials</param>
/// <param name="strVersion">we pass out the SQL Server Specific Version String</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError GetSQLServerVersion(IConnectDb credential, out string strVersion)
{
strVersion = string.Empty;
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_SERVER);
if (dbError.ErrorOccured)
return dbError;
// Execute the Query
string sql = "EXEC sp_server_info @attribute_id = 2";
DB db = DB.Create(credential.DBMS.WithoutDatabase());
DBRetVal retVal = db.FillDataTable(sql);
if (retVal.IsValid)
{
strVersion = retVal.GetDataTableRetVal().Rows[0]["attribute_value"].ToString();
strVersion.Replace("\t", ""); // remove tabs
}
return retVal;
}
/// <summary>
/// Retrieves the SQL Server Version Integer Information from the specified SQL Server Instance
/// </summary>
/// <param name="credential">SQL Server Credentials</param>
/// <param name="nVersion">we pass out the SQL Server Specific Version Int</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError GetSQLServerVersion(IConnectDb credential, out int nVersion)
{
nVersion = 0;
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_SERVER);
if (dbError.ErrorOccured)
return dbError;
// Execute the Query
string sql = "SELECT CONVERT(char(20), SERVERPROPERTY('ProductVersion'))";
DB db = DB.Create(credential.DBMS.WithoutDatabase());
DBRetVal retVal = db.ExecuteScalar(sql);
if(retVal.IsValid)
{
string strVersion = retVal.GetScalarRetVal();
String[] strVersionSplit = strVersion.Split('.');
int.TryParse(strVersionSplit[0], out nVersion);
}
return retVal;
}
#endregion
#region SQL File N' Disk functions
/// <summary>
/// Retrieves the default path for the SQL Server Instance or for the Database on the SQL Server.
/// Leave Database blank in the credential to find the default path for the Server.
/// </summary>
/// <param name="credential">SQL Server Credentials</param>
/// <param name="DefaultPath">default path found or "" if not</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError SQLServerDefaultPath(IConnectDb credential, out string DefaultPath)
{
DefaultPath = string.Empty;
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_SERVER);
if (dbError.ErrorOccured)
return dbError;
// Get the Path for the default Path for the Database if Specified
string sql = String.Empty;
if (credential.DBMS.IsDatabaseSetAndNonSystem)
sql = String.Format("SELECT filename FROM [{0}]..sysfiles", credential.DBMS.Database);
else
sql = "SELECT filename FROM master..sysfiles where [name]='master'";
// Execute the Query
DB db = DB.Create(credential.DBMS.WithoutDatabase());
DBRetVal retVal = db.ExecuteScalar(sql);
if ((retVal.IsValid) && !String.IsNullOrEmpty(retVal.GetScalarRetVal()))
{
string strResult = retVal.GetScalarRetVal();
int indx = strResult.LastIndexOf('\\');
if (indx >= 0)
strResult = strResult.Remove(indx);
DefaultPath = strResult;
}
return retVal;
}
/// <summary>
/// Function retries an array of the Fixed HardDrives/Disks that are available on the Server
/// </summary>
/// <param name="credential">SQL Server Credentials</param>
/// <param name="fixedDisks">an array of all the fixed disk's drive letters (i.e. C), empty list, if error occured</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError SQLServerFixedDisks(IConnectDb credential, out string[] fixedDisks)
{
fixedDisks = null;
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_SERVER);
if (dbError.ErrorOccured)
return dbError;
// Execute the Query
string sql = "EXEC master..xp_fixeddrives";
DB db = DB.Create(credential.DBMS.WithoutDatabase());
DBRetVal retVal = db.FillDataTable(sql);
List<String> retList = new List<String>();
if (retVal.IsValid)
{
foreach (DataRow row in retVal.GetDataTableRetVal().Rows)
retList.Add(row["drive"].ToString());
}
fixedDisks = retList.ToArray();
return retVal;
}
/// <summary>
/// Function retries an array of directories for the specified Path on the specified SQL Server
/// </summary>
/// <param name="credential">SQL Server Credentials</param>
/// <param name="Path">a valid path that exists on the server, i.e. C:\Program Files</param>
/// <param name="Directories">an array of all directories found in the specified path, empty list if no directories found or if error occured</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError SQLServerGetDirectoriesInPath(IConnectDb credential, string Path, out string[] Directories)
{
Directories = null;
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_SERVER);
if (dbError.ErrorOccured)
return dbError;
// Execute the Query
string sql = String.Format("EXEC master..xp_dirtree '{0}', 1, 1", Path);
DB db = DB.Create(credential.DBMS.WithoutDatabase());
DBRetVal retVal = db.FillDataTable(sql);
List<String> retList = new List<String>();
if (retVal.IsValid)
{
foreach (DataRow row in retVal.GetDataTableRetVal().Rows)
{
bool bIsDirectory = (row["file"].ToString() == "0");
if (bIsDirectory)
retList.Add(row["subdirectory"].ToString());
}
}
Directories = retList.ToArray();
return retVal;
}
/// <summary>
/// Function retries an array of files for the specified Path on the specified SQL Server
/// </summary>
/// <param name="credential">SQL Server Credentials</param>
/// <param name="Path">a valid path that exists on the server, i.e. C:\Program Files</param>
/// <param name="Files">an array of all files found in the specified path, empty list if no files found or if error occured</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError SQLServerGetFilesInPath(IConnectDb credential, string Path, out string[] Files)
{
Files = null;
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_SERVER);
if (dbError.ErrorOccured)
return dbError;
// Execute the Query
string sql = String.Format("EXEC master..xp_dirtree '{0}', 1, 1", Path);
DB db = DB.Create(credential.DBMS.WithoutDatabase());
DBRetVal retVal = db.FillDataTable(sql);
List<String> retList = new List<String>();
if (retVal.IsValid)
{
foreach (DataRow row in retVal.GetDataTableRetVal().Rows)
{
bool bIsFile = (row["file"].ToString() == "1");
if (bIsFile)
retList.Add(row["subdirectory"].ToString());
}
}
Files = retList.ToArray();
return retVal;
}
#endregion
#region SQL Connection Checkers
/// <summary>
/// Quick Check function to see if the passed in credential allows us to connect to the server
/// If Credential contains a Database, then it will verify the Database's Existence
/// </summary>
/// <param name="credential">SQL Server Credentials</param>
/// <param name="nConnectionTimeout">Specify the ConnectionTimout</param>
/// <param name="CanConnect">Returns true if successfull in connecting to the server</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError SQLServerCheckConnection(IConnectDb credential, uint nConnectionTimeout, out bool CanConnect)
{
// the SQL Server should at least have a master db, so this list should never be empty,
// if it is, an error must have occured, either with the credential or with the server
CanConnect = false;
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_SERVER);
if (dbError.ErrorOccured)
return dbError;
// Execute Query
string[] Databases = null;
DBError dberror = SQLServerDatabase.DatabasesListAll(credential.DBMS.WithoutDatabase().Timeouts.WithConnectionTimeout(nConnectionTimeout), out Databases);
if (dberror.ErrorOccured || (Databases == null) || (Databases.Length == 0))
CanConnect = false;
else
CanConnect = true;
// Check Database Existence, if specified
if (CanConnect)
{
dbError = Validation.IsValidDatabaseName(credential.DBMS.Database);
if (!dberror.ErrorOccured)
{
// Verify that the Database exists
bool bFound = false;
foreach (string db in Databases)
{
if (db.ToUpper() == credential.DBMS.Database.ToUpper())
{
bFound = true;
break;
}
}
// Let the Caller know if they can connect to the Database
CanConnect = bFound;
}
}
return dberror;
}
/// <summary>
/// Quick Check function to see if the passed in credential allows us to connect to the
/// server, read some data, as well as check SysAdmin Rights for the passed in Credential
/// If Credential contains a Database, then it will verify the Database's Existence
/// </summary>
/// <param name="credential">SQL Server Credentials</param>
/// <param name="nConnectionTimeout">Specify the ConnectionTimout</param>
/// <param name="IsValid">true, if passed in credential connects and is a sysadmin, false otherwise</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError SQLServerCheckConnectionNCredential(IConnectDb credential, uint nConnectionTimeout, out bool IsValid)
{
IsValid = false;
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_SERVER);
if (dbError.ErrorOccured)
return dbError;
DBError dberror = SQLServerCheckConnection(credential, nConnectionTimeout, out IsValid);
if (dberror.ErrorOccured || !IsValid)
return dberror;
// Now also make sure that the credential is a SysAdmin
dberror = SQLServerSecurity.LoginIsSysAdmin(credential, credential.User, out IsValid);
return dberror;
}
#endregion
#region SQL Browse
/// <summary>
/// Returns a array of any found valid SQL Server intances * Using the SQLBrowse Functionallity *
/// If SQLBrowse fails, will look in the Registry
/// This Function can take a long time, depending on the Network
/// </summary>
/// <returns>list of valid SQLServers or null if error occured</returns>
public static string[] SQLServerNamesAndInstaces()
{
// Call the SQL Browse Function
List<String> validSQLServerInstances = new List<string>();
string[] SQLServersRaw = SQLInfoEnumerator.EnumerateSQLServers();
foreach (string SQLServerRaw in SQLServersRaw)
{
// Target name is empty - so add any valid instances found
if (Validation.IsValidServerNameAndInstanceName(SQLServerRaw))
validSQLServerInstances.Add(SQLServerRaw);
}
// Last thing to try if EnumerateSQLServers() failed is to query the registry
// for all possible SQL Server Installations there * and return those *
if (validSQLServerInstances.Count == 0)
{
string strInstalledInstances = RegKey.GetKey<string>(HKEYRoot.LocalMachine, "Microsoft\\Microsoft SQL Server", "InstalledInstances", String.Empty);
if (!String.IsNullOrEmpty(strInstalledInstances))
{
string MachineName = Dns.GetHostName();
// Add any Registry Found Instances
string[] Instances = strInstalledInstances.Split(' ');
foreach (string Instance in Instances)
validSQLServerInstances.Add(MachineName + "\\" + Instance);
}
}
return validSQLServerInstances.ToArray();
}
#endregion
#region SQL Service Functions
/// <summary>
/// Use this to start a SQL Service on the specified Server. You must have Windows admin/SController rights to
/// that machine in order for this function to work
/// </summary>
/// <param name="ServerOrServerNInstance">Name of the SQL Server or SQL ServerNInstance you want to start (required)</param>
/// <param name="WaitTimeoutInSeconds">Set to Value > 0 to force a wait for the specified amount of seconds(not required)</param>
/// <returns>true if Service was started or was already running, false if an error occured</returns>
public static bool SQLServerServiceStart(string ServerOrServerNInstance, int WaitTimeoutInSeconds)
{
string Server = string.Empty;
string Instance = string.Empty;
if (String.IsNullOrEmpty(ServerOrServerNInstance))
return false;
if (!SQLServerUtilities.SplitServerOrServerNInstance(ServerOrServerNInstance, out Server, out Instance))
return false;
// Construct the proper service name
string Service = string.Empty;
if (!String.IsNullOrEmpty(Instance))
Service = String.Format("MSSQL${0}", Instance);
else
Service = "MSSQLSERVER";
string MachineName = Dns.GetHostName();
bool bIsOnThisMachine = (MachineName.ToLower() == Server.ToLower());
try
{
ServiceController service = null;
if (bIsOnThisMachine)
service = new ServiceController(Service);
else
service = new ServiceController(Service, Server);
bool bStartService = (service.Status != ServiceControllerStatus.Running);
if (bStartService)
{
service.Start();
if (WaitTimeoutInSeconds > 0)
{
TimeSpan timeout = TimeSpan.FromSeconds(WaitTimeoutInSeconds);
service.WaitForStatus(ServiceControllerStatus.Running, timeout);
return (service.Status == ServiceControllerStatus.Running);
}
}
return true;
}
catch (Exception) { /* ignore */ }
return false;
}
/// <summary>
/// Use this to stop a SQL Service on the specified Server. You must have Windows admin/SController rights to
/// that machine in order for this function to work
/// </summary>
/// <param name="ServerOrServerNInstance">Name of the SQL Server or SQL ServerNInstance you want to stop (required)</param>
/// <param name="WaitTimeoutInSeconds">Set to Value > 0 to force a wait for the specified amount of seconds(not required)</param>
/// <returns>true if Service was stopped or was already stopped, false if an error occured</returns>
public static bool SQLServerServiceStop(string ServerOrServerNInstance, int WaitTimeoutInSeconds)
{
string Server = string.Empty;
string Instance = string.Empty;
if (String.IsNullOrEmpty(ServerOrServerNInstance))
return false;
if (!SQLServerUtilities.SplitServerOrServerNInstance(ServerOrServerNInstance, out Server, out Instance))
return false;
// Construct the proper service name
string Service = string.Empty;
if (!String.IsNullOrEmpty(Instance))
Service = String.Format("MSSQL${0}", Instance);
else
Service = "MSSQLSERVER";
string MachineName = Dns.GetHostName();
bool bIsOnThisMachine = (MachineName.ToLower() == Server.ToLower());
try
{
ServiceController service = null;
if (bIsOnThisMachine)
service = new ServiceController(Service);
else
service = new ServiceController(Service, Server);
bool bStopService = (service.Status != ServiceControllerStatus.Stopped);
if (bStopService)
{
service.Stop();
if (WaitTimeoutInSeconds > 0)
{
TimeSpan timeout = TimeSpan.FromSeconds(WaitTimeoutInSeconds);
service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
return (service.Status == ServiceControllerStatus.Stopped);
}
}
return true;
}
catch (Exception) { /* ignore */ }
return false;
}
/// <summary>
/// Use this to restart a SQL Service on the specified Server. You must have Windows admin/SController rights to
/// that machine in order for this function to work
/// </summary>
/// <param name="ServerOrServerNInstance">Name of the SQL Server or SQL ServerNInstance you want to restart (required)</param>
/// <param name="WaitTimeoutInSeconds">Set to Value > 0 to force a wait for the specified amount of seconds(not required)</param>
/// <returns>true if Service was restared successfully, false if an error occured</returns>
public static bool SQLServerServiceRestart(string ServerOrServerNInstance, int WaitTimeoutInSeconds)
{
return SQLServerServiceStop(ServerOrServerNInstance, WaitTimeoutInSeconds) && SQLServerServiceStart(ServerOrServerNInstance, WaitTimeoutInSeconds);
}
#endregion
}
}

View File

@@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sdaleo.Systems.SQLServer
{
/// <summary>
/// Database Error Constants to Use to handle specific Error
/// </summary>
internal static class ErrorConst
{
public const int ERROR_DB_ALREADY_EXISTS = 1801;
public const int ERROR_DB_SOME_FILE_NAMES_COULD_NOT_BE_CREATED = 1802;
public const int ERROR_DB_CAN_NOT_CREATE_FILE_BECAUSE_IT_ALREADY_EXISTS = 5170;
public const int ERROR_DB_THERE_ALREADY_IS_AN_OBJECT_IN_THE_DB_WITH_THIS_NAME = 3092;
public const int ERROR_DB_DEVICE_ACTIVATION_FAILED = 5105;
}
}

View File

@@ -0,0 +1,189 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace Sdaleo.Systems.SQLServer
{
/// <summary>
/// Summary description for SQLInfoEnumerator.
/// This class Enumerates a network for SQL Server instances and returns a list.
/// For a given SQL Server instance a list of all available databases is returned
/// For more information see
/// </summary>
/// <see cref="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/odbc/htm/odbcsqlbrowseconnect.asp"/>
/// <seealso cref="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dncscol/html/csharp09192002.asp"/>
internal class SQLInfoEnumerator
{
#region ODBC32 external function definitions
[DllImport("odbc32.dll")]
private static extern short SQLAllocHandle(short handleType, IntPtr inputHandle, out IntPtr outputHandlePtr);
[DllImport("odbc32.dll")]
private static extern short SQLSetEnvAttr(IntPtr environmentHandle, int attribute, IntPtr valuePtr, int stringLength);
[DllImport("odbc32.dll")]
private static extern short SQLFreeHandle(short hType, IntPtr Handle);
[DllImport("odbc32.dll", CharSet = CharSet.Ansi)]
private static extern short SQLBrowseConnect(IntPtr handleConnection, StringBuilder inConnection, short stringLength, StringBuilder outConnection, short bufferLength, out short stringLength2Ptr);
#endregion
#region Constants
private const string SQL_DRIVER_STR = "DRIVER={SQL SERVER};";
private const short SQL_SUCCESS = 0;
private const short SQL_SUCCESS_WITH_INFO = 1;
private const short SQL_HANDLE_ENV = 1;
private const short SQL_HANDLE_DBC = 2;
private const int SQL_ATTR_ODBC_VERSION = 200;
private const int SQL_OV_ODBC3 = 3;
private const short SQL_NEED_DATA = 99;
private const short DEFAULT_RESULT_SIZE = 1024;
private const string START_STR = "{";
private const string END_STR = "}";
#endregion
/// <summary>
/// Enumerate the SQL Servers returning a list (if any exist)
/// </summary>
/// <returns></returns>
internal static string[] EnumerateSQLServers()
{
return RetrieveInformation(SQL_DRIVER_STR);
}
/// <summary>
/// Enumerate the specified SQL server returning a list of databases (if any exist)
/// </summary>
/// <returns></returns>
internal static string[] EnumerateSQLServersDatabases(string SQLServerNInstance)
{
return RetrieveInformation(SQL_DRIVER_STR + "SERVER=" + SQLServerNInstance + ";");
}
/// <summary>
/// Enumerate the specified SQL server returning a list of databases (if any exist)
/// </summary>
/// <returns></returns>
internal static string[] EnumerateSQLServersDatabases(string SQLServerNInstance, string Username, string Password)
{
return RetrieveInformation(SQL_DRIVER_STR + "SERVER=" + SQLServerNInstance + ";" + "UID=" + Username + ";" + "PWD=" + Password + ";");
}
/// <summary>
/// Enumerate for SQLServer/Databases based on the passed information it the string
/// The more information provided to SQLBrowseConnect the more granular it gets so
/// if only DRIVER=SQL SERVER passed then a list of all SQL Servers is returned
/// If DRIVER=SQL SERVER;Server=ServerName is passed then a list of all Databases on the
/// servers is returned etc
/// </summary>
/// <param name="InputParam">A valid string to query for</param>
/// <returns></returns>
private static string[] RetrieveInformation(string InputParam)
{
IntPtr m_environmentHandle = IntPtr.Zero;
IntPtr m_connectionHandle = IntPtr.Zero;
StringBuilder inConnection = new StringBuilder(InputParam);
short stringLength = (short)inConnection.Length;
StringBuilder outConnection = new StringBuilder(DEFAULT_RESULT_SIZE);
short stringLength2Ptr = 0;
bool bConnectSuccessful = false;
try
{
// Prepare the SQL Environment Handles
if ((IsSQLSuccess(SQLAllocHandle(SQL_HANDLE_ENV, m_environmentHandle, out m_environmentHandle))) &&
(IsSQLSuccess(SQLSetEnvAttr(m_environmentHandle, SQL_ATTR_ODBC_VERSION, (IntPtr)SQL_OV_ODBC3, 0))) &&
(IsSQLSuccess(SQLAllocHandle(SQL_HANDLE_DBC, m_environmentHandle, out m_connectionHandle))))
{
// Fetch the Data * First get the size of the buffer, then call it to get the buffer *
if (IsSQLDataSuccess(SQLBrowseConnect(m_connectionHandle, inConnection, stringLength, null, 0, out stringLength2Ptr)) &&
IsSQLDataSuccess(SQLBrowseConnect(m_connectionHandle, inConnection, stringLength, outConnection, stringLength2Ptr, out stringLength2Ptr))
)
{
bConnectSuccessful = true;
}
}
}
catch { /* ignore */ }
finally
{
FreeConnection(m_connectionHandle);
FreeConnection(m_environmentHandle);
}
if (bConnectSuccessful && outConnection.ToString() != "")
{
return ParseSQLOutConnection(outConnection.ToString());
}
else
{
return null;
}
}
#region Helper Functions
/// <summary>
/// For quick SQL Return value evaluation
/// </summary>
private static bool IsSQLSuccess(short SQL_VALUE)
{
if (SQL_VALUE == SQL_SUCCESS || SQL_VALUE == SQL_SUCCESS_WITH_INFO)
return true;
else
return false;
}
/// <summary>
/// For quick SQL Return value evaluation
/// </summary>
private static bool IsSQLDataSuccess(short SQL_VALUE)
{
if (SQL_VALUE == SQL_SUCCESS || SQL_VALUE == SQL_SUCCESS_WITH_INFO || SQL_VALUE == SQL_NEED_DATA)
return true;
else
return false;
}
/// <summary>
/// Parse an outConnection string returned from SQLBrowseConnect
/// </summary>
/// <param name="outConnection">string to parse</param>
/// <returns>Parsed Server names, or Empty Array if none found</returns>
private static string[] ParseSQLOutConnection(string outConnection)
{
int m_Start = outConnection.IndexOf(START_STR) + 1;
int m_lenString = outConnection.IndexOf(END_STR) - m_Start;
if ((m_Start > 0) && (m_lenString > 0))
{
outConnection = outConnection.Substring(m_Start, m_lenString);
}
else
{
outConnection = string.Empty;
}
return outConnection.Split(",".ToCharArray());
}
/// <summary>
/// Call this to Free a SQL handle
/// </summary>
private static void FreeConnection(IntPtr handleToFree)
{
if (handleToFree != IntPtr.Zero)
SQLFreeHandle(SQL_HANDLE_DBC, handleToFree);
}
#endregion
}
}

View File

@@ -0,0 +1,100 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sdaleo.Systems.SQLServer
{
/// <summary>
/// Central Location for SQL Server Input Validation
/// </summary>
internal class Validation
{
/// <summary>
/// Main Validation Function to validate DatabaseName
/// </summary>
/// <param name="strDatabaseName">Name of Database</param>
/// <returns>true if valid, false otherise</returns>
internal static DBError IsValidDatabaseName(string strDatabaseName)
{
if (string.IsNullOrEmpty(strDatabaseName))
{
return DBError.Create("DatabaseName is null");
}
else if (strDatabaseName.Length < 1 || strDatabaseName.Length > 52) // limit database Name length
{
return DBError.Create("DatabaseName length is invalid");
}
else if (!ValidationConsts.ContainsOnlyLegalChars(strDatabaseName, ValidationConsts.CharSet_AllowedDatabaseNames))
{
return DBError.Create("DatabaseName contains illegal characters");
}
else
{
return new DBError();
}
}
/// <summary>
/// validate SQL Server Table Names
/// </summary>
/// <param name="strTableName"></param>
/// <returns></returns>
public static DBError IsValidTableName(string strTableName)
{
if (string.IsNullOrEmpty(strTableName))
{
return DBError.Create("TableName is null");
}
else if (strTableName.Length < 1 || strTableName.Length > 52) // limit Table Name length
{
return DBError.Create("TableName length is invalid");
}
else if (!ValidationConsts.ContainsOnlyLegalChars(strTableName, ValidationConsts.CharSet_AllowedTableNames))
{
return DBError.Create("TableName contains illegal characters");
}
else
{
return new DBError();
}
}
/// <summary>
/// Validates a DataSource String which can include a Server and Instance, or just be a Server
/// </summary>
/// <param name="strDataSource">a DataSource String</param>
/// <returns>true if valid, false otherise</returns>
internal static bool IsValidDataSource(string strDataSource)
{
if (!string.IsNullOrEmpty(strDataSource) && (strDataSource.IndexOf('\\') >= 0))
{
string[] values = strDataSource.Split('\\');
if (values.Length == 2)
return ValidationConsts.Generic.IsValidServerName(values[0]) && ValidationConsts.Generic.IsValidInstanceName(values[1]);
}
else if (!string.IsNullOrEmpty(strDataSource) && (strDataSource.IndexOf('\\') == 0))
{
return ValidationConsts.Generic.IsValidServerName(strDataSource);
}
return false;
}
/// <summary>
/// Validates that the passedin string has both a valid server and a valid Instance
/// </summary>
/// <param name="strServerNameNInstance">a string to check for server and instance</param>
/// <returns>true if valid, false otherwise</returns>
internal static bool IsValidServerNameAndInstanceName(string strServerNameNInstance)
{
if (!string.IsNullOrEmpty(strServerNameNInstance) && (strServerNameNInstance.IndexOf('\\') >= 0))
{
string[] values = strServerNameNInstance.Split('\\');
if (values.Length == 2)
return ValidationConsts.Generic.IsValidServerName(values[0]) && ValidationConsts.Generic.IsValidInstanceName(values[1]);
}
return false;
}
}
}

View File

@@ -0,0 +1,778 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace Sdaleo.Systems.SQLServer
{
#region SQLServer Security Enums
/// <summary>
/// Server Roles as specified in SQL Server
/// </summary>
public enum SQLServerRole
{
sysadmin,
securityadmin,
serveradmin,
setupadmin,
processadmin,
diskadmin,
dbcreator,
bulkadmin,
}
/// <summary>
/// User Roles as specified in SQL Server
/// </summary>
public enum SQLServerUserRole
{
db_accessadmin,
db_backupoperator,
db_datareader,
db_datawriter,
db_ddladmin,
db_denydatareader,
db_denydatawriter,
db_owner,
db_securityadmin,
}
/// <summary>
/// These are the SQL Actions you can take on
/// SQLTablePermissions or SQLServerDatabasePermissions
/// </summary>
public enum SQLServerPermissionAction
{
GRANT,
REVOKE,
DENY
}
/// <summary>
/// User Permissions on any User Database ('_' must be stripped before using in in sql)
/// </summary>
public enum SQLServerDatabasePermission
{
CREATE_DATABASE, // <--- permission only allowed on 'Master' Database
CONNECT,
CREATE_TABLE,
CREATE_DEFAULT,
CREATE_FUNCTION,
CREATE_PROCEDURE,
CREATE_RULE,
CREATE_VIEW,
BACKUP_DATABASE,
BACKUP_LOG
}
#endregion
/// <summary>
/// Security/Permission SQL Server Related
/// </summary>
public class SQLServerSecurity
{
#region Internal Security Helper Functions
/// <summary>
/// We must strip out the '_' on the SQLServerDatabasePermission Enum to use it in an SQL Query
/// </summary>
internal static string SQLServerDatabasePermission_ToString(SQLServerDatabasePermission DatabasePermission)
{
return DatabasePermission.ToString().Replace('_', ' ');
}
/// <summary>
/// Quick Helper function to get an SQLServerDatabasePermission[] that has all Permissions defined
/// </summary>
internal static SQLServerDatabasePermission[] SQLServerDatabasePermission_ToArray()
{
return (SQLServerDatabasePermission[])Enum.GetValues(typeof(SQLServerDatabasePermission));
}
/// <summary>
/// Returns generated SQL Database Permissions string for the specified Database,Username with the specified permissions
/// </summary>
/// <param name="Username">Name of an existing User (required)</param>
/// <param name="Action">Permission Action to take (required)</param>
/// <param name="databasePermissions">array of User Database permissions (required)</param>
/// <param name="bIsMasterDB">Some User Permission require to be executed ONLY on the Master Database, set to true if this is sql is being generated for 'master'</param>
/// <returns>a Database permission string or empty string if error occured</returns>
internal static string BuildSQLServerDatabasePermissionsStr(string Username, SQLServerDatabasePermission[] databasePermissions, SQLServerPermissionAction Action, bool bIsMasterDB)
{
if (String.IsNullOrEmpty(Username) || (databasePermissions == null))
return string.Empty;
// add Action
string sql = Action.ToString() + " ";
// add each permission individually
for (int i = 0; i < databasePermissions.Length; ++i)
{
// Skip certain permissions, unless this is the Master DB
if ((databasePermissions[i] == SQLServerDatabasePermission.CREATE_DATABASE) && !bIsMasterDB)
continue;
sql += SQLServerDatabasePermission_ToString(databasePermissions[i]);
bool bIsLast = (i == (databasePermissions.Length - 1));
if (!bIsLast)
sql += ",";
}
// add action adjective
if (Action == SQLServerPermissionAction.REVOKE)
sql += " FROM ";
else
sql += " TO ";
// add user
sql += string.Format("[{0}]", Username);
return sql;
}
#endregion
#region Database User Role
/// <summary>
/// Use this to add a specified User Role to a specified User in the DB
/// </summary>
/// <param name="credential">SQL Server Credentials with Database Info</param>
/// <param name="Username">an existing Username to add role to (required)</param>
/// <param name="Role">Role to add to specified MemberName</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public DBError DatabaseUserRoleAdd(IConnectDb credential, string Username, SQLServerUserRole Role)
{
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_SERVER);
if (dbError.ErrorOccured)
return dbError;
if (!credential.DBMS.IsDatabaseSetAndNonSystem)
return DBError.Create("Invalid Database Passed In via Credential");
if (!ValidationConsts.Generic.IsValidUserName(Username))
return DBError.Create("Invalid Username Passed In");
// Execute the Query
string sql = String.Format("sp_addrolemember @membername = '{0}', @rolename = '{1}'", Username, Role.ToString());
DB db = DB.Create(credential);
DBRetVal retVal = db.ExecuteNonQuery(sql);
return retVal;
}
/// <summary>
/// Use this to drop a specified User Role from a specified User in the DB
/// </summary>
/// <param name="credential">SQL Server Credentials with Database Info</param>
/// <param name="Username">an existing Username to drop role from (required)</param>
/// <param name="Role">Role to drop from specified MemberName</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError DatabaseUserRoleDrop(IConnectDb credential, string Username, SQLServerUserRole Role)
{
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_SERVER);
if (dbError.ErrorOccured)
return dbError;
if (!credential.DBMS.IsDatabaseSetAndNonSystem)
return DBError.Create("Invalid Database Passed In via Credential");
if (!ValidationConsts.Generic.IsValidUserName(Username))
return DBError.Create("Invalid Username Passed In");
// Execute and return the Query
string sql = String.Format("sp_droprolemember @membername = '{0}', @rolename = '{1}'", Username, Role.ToString());
DB db = DB.Create(credential);
DBRetVal retVal = db.ExecuteNonQuery(sql);
return retVal;
}
#endregion
#region Database User
/// <summary>
/// Use this to query if the Username already exists as an SQL Database User (Does not query Server users ONLY DB Users)
/// </summary>
/// <param name="credential">SQL Server Credentials with Database Info</param>
/// <param name="Username">Specify the Username to Query for (required)</param>
/// <param name="bExists">True if the User exists in the specified Database, False otherwise</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError DatabaseUserExists(IConnectDb credential, string Username, out bool bExists)
{
bExists = false;
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_SERVER);
if (dbError.ErrorOccured)
return dbError;
if (!credential.DBMS.IsDatabaseSetAndNonSystem)
return DBError.Create("Invalid Database Passed In via Credential");
if (!ValidationConsts.Generic.IsValidUserName(Username))
return DBError.Create("Invalid Username Passed In");
// Execute the Query and return
string sql = string.Format("SELECT [name] FROM sys.database_principals WHERE [type_desc]='SQL_USER' and [name] = '{0}'", Username);
DB db = DB.Create(credential);
DBRetVal retVal = db.ExecuteScalar(sql);
bExists = retVal.IsValid;
return retVal;
}
/// <summary>
/// Use this to retrieve a list of all the Database users for the specified SQL Server with DB Credentials
/// </summary>
/// <param name="credential">SQL Server Credentials with Database Info</param>
/// <param name="Users">a list of Database User, or Null if error occured</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError DatabaseUsers(IConnectDb credential, out string[] Users)
{
Users = null;
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_SERVER);
if (dbError.ErrorOccured)
return dbError;
if (!credential.DBMS.IsDatabaseSetAndNonSystem)
return DBError.Create("Invalid Database Passed In via Credential");
// Execute the Query
string sql = "SELECT [name] FROM sys.database_principals WHERE [type_desc]='SQL_USER'";
DB db = DB.Create(credential);
DBRetVal retVal = db.FillDataTable(sql);
if (retVal.IsValid)
{
List<String> retList = new List<string>();
foreach (DataRow row in retVal.GetDataTableRetVal().Rows)
retList.Add(row["name"].ToString());
Users = retList.ToArray();
}
return retVal;
}
/// <summary>
/// Add a new Username to the Specified Database for the specified Login
/// </summary>
/// <param name="credential">SQL Server Credentials</param>
/// <param name="Username">Specify the Username for the database (can be same as LoginName) (required)</param>
/// <param name="Loginname">Specify the LoginName (valid SQL Server Login Name) to create Username for (required)</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError DatabaseUserAdd(IConnectDb credential, string Username, string LoginName)
{
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_SERVER);
if (dbError.ErrorOccured)
return dbError;
if (!credential.DBMS.IsDatabaseSetAndNonSystem)
return DBError.Create("Invalid Database Passed In via Credential");
if (!ValidationConsts.Generic.IsValidUserName(Username))
return DBError.Create("Invalid Username Passed In");
if (!ValidationConsts.Generic.IsValidUserName(LoginName))
return DBError.Create("Invalid LoginName Passed In");
// Execute the Query
string sql = string.Format("CREATE USER [{0}] FOR LOGIN [{1}] WITH DEFAULT_SCHEMA = [{0}]", Username, LoginName);
DB db = DB.Create(credential);
DBRetVal retVal = db.ExecuteNonQuery(sql);
if (!retVal.ErrorOccured)
{
// Since SQL 2005, We should create a SCHEMA for each User
sql = string.Format("CREATE SCHEMA [{0}] AUTHORIZATION [{0}]", Username);
retVal = db.ExecuteNonQuery(sql);
}
return retVal;
}
/// <summary>
/// Drops an existing Username from the Specified Database
/// </summary>
/// <param name="credential">SQL Server Credentials with Database Info</param>
/// <param name="Username">Specify the Username for the database (required)</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError DatabaseUserDrop(IConnectDb credential, string Username)
{
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_SERVER);
if (dbError.ErrorOccured)
return dbError;
if (!credential.DBMS.IsDatabaseSetAndNonSystem)
return DBError.Create("Invalid Database Passed In via Credential");
if (!ValidationConsts.Generic.IsValidUserName(Username))
return DBError.Create("Invalid Username Passed In");
// Since SQL 2005, We must drop the SCHEMA first for each User
string sql = string.Format("DROP SCHEMA [{0}]", Username);
DB db = DB.Create(credential);
DBRetVal retVal = db.ExecuteNonQuery(sql);
if (!retVal.ErrorOccured)
{
sql = string.Format("DROP USER [{0}]", Username);
retVal = db.ExecuteNonQuery(sql);
}
return retVal;
}
#endregion
#region Database User Permission
/// <summary>
/// Automatically grant,deny,revoke all permissions on the database for the specified user
/// </summary>
/// <param name="credential">SQL Server Credentials with Database Info</param>
/// <param name="Username">Specify the Username for the database (required)</param>
/// <param name="action">GRANT,DENY, or REVOKE 'Permission_All' Permission on that db</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError DatabaseUserPermissionsAll(IConnectDb credential, string Username, SQLServerPermissionAction action)
{
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_SERVER);
if (dbError.ErrorOccured)
return dbError;
if (!credential.DBMS.IsDatabaseSetAndNonSystem)
return DBError.Create("Invalid Database Passed In via Credential");
if (!ValidationConsts.Generic.IsValidUserName(Username))
return DBError.Create("Invalid Username Passed In");
// Execute and return
return DatabaseUserPermissions(credential, Username, SQLServerDatabasePermission_ToArray(), action);
}
/// <summary>
/// Allows you to specify permissions to grant,deny,revoke on the database for the specified user
/// </summary>
/// <param name="credential">SQL Server Credentials with Database Info</param>
/// <param name="Username">Specify the Username for the database (required)</param>
/// <param name="permissions">an array of permissions to take action on on db</param>
/// <param name="action">GRANT,DENY, or REVOKE specified Permissions on that db</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError DatabaseUserPermissions(IConnectDb credential, string Username, SQLServerDatabasePermission[] permissions, SQLServerPermissionAction action)
{
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_SERVER);
if (dbError.ErrorOccured)
return dbError;
if (!credential.DBMS.IsDatabaseSetAndNonSystem)
return DBError.Create("Invalid Database Passed In via Credential");
if (!ValidationConsts.Generic.IsValidUserName(Username))
return DBError.Create("Invalid Username Passed In");
// Execute the Query
string sql = BuildSQLServerDatabasePermissionsStr(Username, permissions, action, SQLServerUtilities.IsSQLServerMasterDatabaseName(credential.DBMS.Database));
DB db = DB.Create(credential);
DBRetVal retVal = db.ExecuteNonQuery(sql);
return retVal;
}
#endregion
#region Database Ownership
/// <summary>
/// Changes the Specified Database's Ownership to be owned by the specified LoginName
/// </summary>
/// <param name="credential">SQL Server Credentials with Database Info</param>
/// <param name="LoginName">Specify the Login Name to To take over Database Ownership for (required)</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError DatabaseChangeOwnership(IConnectDb credential, string LoginName)
{
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_SERVER);
if (dbError.ErrorOccured)
return dbError;
if (!credential.DBMS.IsDatabaseSetAndNonSystem)
return DBError.Create("Invalid Database Passed In via Credential");
if (!ValidationConsts.Generic.IsValidUserName(LoginName))
return DBError.Create("Invalid LoginName Passed In");
// Make sure that Login doesn't already own that Database
bool bContinue = true;
string[] ownedDBs = null;
DBError dberror = DatabasesOwnedByLogin(credential.DBMS.WithoutDatabase(), LoginName, out ownedDBs);
if (!dberror.ErrorOccured && ownedDBs != null)
{
foreach (string dbName in ownedDBs)
{
if (dbName.ToLower() == credential.DBMS.Database.ToLower())
{
bContinue = false;
break;
}
}
}
// Change the Database Ownership
if (bContinue)
{
DB db = DB.Create(credential.DBMS.WithoutDatabase());
string sql = String.Format("ALTER Authorization On Database::[{0}] To [{1}])", credential.DBMS.Database, LoginName);
DBRetVal retVal = db.ExecuteNonQuery(sql);
return retVal;
}
return dberror;
}
/// <summary>
/// Retrieve the SQL Login that is the Owner of the specified Database for the specified SQL Server
/// </summary>
/// <param name="credential">SQL Server Credentials with Database Info</param>
/// <param name="Owner">Name of DB Owner</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError DatabaseOwner(IConnectDb credential, out string Owner)
{
Owner = String.Empty;
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_SERVER);
if (dbError.ErrorOccured)
return dbError;
if (!credential.DBMS.IsDatabaseSetAndNonSystem)
return DBError.Create("Invalid Database Passed In via Credential");
// Execute the Query
DB db = DB.Create(credential);
string sql = String.Format("Select suser_sname(owner_sid) from sys.databases where [name] = '{0}'", credential.DBMS.Database);
DBRetVal retVal = db.ExecuteScalar(sql);
if (retVal.IsValid)
Owner = retVal.GetScalarRetVal();
return retVal;
}
/// <summary>
/// Use this to retrieve all Databases that are owned by the specified Login for the specified SQL Server
/// </summary>
/// <param name="credential">SQL Server Credentials</param>
/// <param name="LoginName">Specify the Login Name to Query Database Ownership for (required)</param>
/// <param name="DatabasesOwned">DatabaseNames that are owned by this Login, null if none are found or error occured</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError DatabasesOwnedByLogin(IConnectDb credential, string LoginName, out string[] DatabasesOwned)
{
DatabasesOwned = null;
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_SERVER);
if (dbError.ErrorOccured)
return dbError;
if (!credential.DBMS.IsDatabaseSetAndNonSystem)
return DBError.Create("Invalid Database Passed In via Credential");
if (!ValidationConsts.Generic.IsValidUserName(LoginName))
return DBError.Create("Invalid LoginName Passed In");
// Execute the Query
string sql = String.Format("Select [name] from sys.databases where [owner_sid] = SUSER_SID('{0}')", LoginName);
DB db = DB.Create(credential);
DBRetVal retVal = db.FillDataTable(sql);
if (retVal.IsValid)
{
List<String> retList = new List<String>();
foreach (DataRow row in retVal.GetDataTableRetVal().Rows)
retList.Add(row["name"].ToString());
DatabasesOwned = retList.ToArray();
}
return retVal;
}
#endregion
#region Login Roles
/// <summary>
/// Use this to add a specified Server Role to a specified Login in the DB
/// </summary>
/// <param name="credential">SQL Server Credentials</param>
/// <param name="LoginName">existing login name to add server role to (required)</param>
/// <param name="Role">Role to add to specified LoginName</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError LoginRoleAdd(IConnectDb credential, string LoginName, SQLServerRole Role)
{
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_SERVER);
if (dbError.ErrorOccured)
return dbError;
if (!credential.DBMS.IsDatabaseSetAndNonSystem)
return DBError.Create("Invalid Database Passed In via Credential");
if (!ValidationConsts.Generic.IsValidUserName(LoginName))
return DBError.Create("Invalid LoginName Passed In");
// Execute the Query and Return
string sql = String.Format("sp_addsrvrolemember @loginame = '{0}', @rolename = '{1}'", LoginName, Role.ToString());
DB db = DB.Create(credential.DBMS.WithoutDatabase());
DBRetVal retVal = db.ExecuteNonQuery(sql);
return retVal;
}
/// <summary>
/// Use this to drop a specified Server Role from a specified Login in the DB
/// </summary>
/// <param name="credential">SQL Server Credentials</param>
/// <param name="LoginName">existing login name to drop server role from (required)</param>
/// <param name="Role">Role to drop from a specified LoginName</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError LoginRoleDrop(IConnectDb credential, string LoginName, SQLServerRole Role)
{
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_SERVER);
if (dbError.ErrorOccured)
return dbError;
if (!credential.DBMS.IsDatabaseSetAndNonSystem)
return DBError.Create("Invalid Database Passed In via Credential");
if (!ValidationConsts.Generic.IsValidUserName(LoginName))
return DBError.Create("Invalid LoginName Passed In");
// Execute Query
string sql = String.Format("sp_dropsrvrolemember @loginame = '{0}', @rolename = '{1}'", LoginName, Role.ToString());
DB db = DB.Create(credential.DBMS.WithoutDatabase());
DBRetVal retVal = db.ExecuteNonQuery(sql);
return retVal;
}
/// <summary>
/// Use this to query the SQLServer for the roles that are defined for the specified LoginName
/// </summary>
/// <param name="credential">SQL Server Credentials</param>
/// <param name="LoginName">existing login name to query server roles for</param>
/// <param name="Roles">Roles Corresponding the the ServerLogin</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError LoginRoles(IConnectDb credential, string LoginName, out SQLServerRole[] Roles)
{
Roles = null;
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_SERVER);
if (dbError.ErrorOccured)
return dbError;
if (!credential.DBMS.IsDatabaseSetAndNonSystem)
return DBError.Create("Invalid Database Passed In via Credential");
if (!ValidationConsts.Generic.IsValidUserName(LoginName))
return DBError.Create("Invalid LoginName Passed In");
// Build SQL String
string sql = "SELECT * FROM sys.server_role_members rm JOIN sys.server_principals Roles ON ";
sql += "rm.role_principal_id = Roles.principal_id JOIN sys.server_principals Logins ON ";
sql += "rm.member_principal_id = Logins.principal_id ";
sql += String.Format("Where Logins.name = '{0}'", LoginName);
DB db = DB.Create(credential.DBMS.WithoutDatabase());
// Fetch the Data
DBRetVal retVal = db.FillDataTable(sql);
if (retVal.IsValid)
{
List<SQLServerRole> retList = new List<SQLServerRole>();
foreach (DataRow row in retVal.GetDataTableRetVal().Rows)
{
SQLServerRole role = (SQLServerRole)Enum.Parse(typeof(SQLServerRole), row["name"].ToString());
retList.Add(role);
}
Roles = retList.ToArray();
}
return retVal;
}
#endregion
#region Login
/// <summary>
/// Easy Check to see if the passed in Login has SysAdmin rights (Full Control)
/// </summary>
/// <param name="credential">SQL Server Credentials</param>
/// <param name="LoginName">existing login name to query sysadmin role for</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError LoginIsSysAdmin(IConnectDb credential, string LoginName, out bool IsAdmin)
{
IsAdmin = false;
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_SERVER);
if (dbError.ErrorOccured)
return dbError;
if (!credential.DBMS.IsDatabaseSetAndNonSystem)
return DBError.Create("Invalid Database Passed In via Credential");
if (!ValidationConsts.Generic.IsValidUserName(LoginName))
return DBError.Create("Invalid LoginName Passed In");
SQLServerRole[] roles = null;
DBError dberror = LoginRoles(credential, LoginName, out roles);
if (dberror.ErrorOccured)
return dberror;
IsAdmin = roles.Contains(SQLServerRole.sysadmin);
return dberror;
}
/// <summary>
/// Use this to query if the LoginName already exists as an SQL Server User (Does not query db User ONLY server Users)
/// </summary>
/// <param name="credential">SQL Server Credentials</param>
/// <param name="LoginName">Specify the Login Name to Query for (required)</param>
/// <param name="bExists">true if login already exist as an SQL User in the system, false otherwise</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError LoginExists(IConnectDb credential, string LoginName, out bool bExists)
{
bExists = true;
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_SERVER);
if (dbError.ErrorOccured)
return dbError;
if (!credential.DBMS.IsDatabaseSetAndNonSystem)
return DBError.Create("Invalid Database Passed In via Credential");
if (!ValidationConsts.Generic.IsValidUserName(LoginName))
return DBError.Create("Invalid LoginName Passed In");
// Execute Query
string sql = string.Format("SELECT [name] FROM sys.sql_logins WHERE [name] = '{0}'", LoginName);
DB db = DB.Create(credential.DBMS.WithoutDatabase());
DBRetVal retVal = db.ExecuteScalar(sql);
bExists = retVal.IsValid;
return retVal;
}
/// <summary>
/// Use this to retrieve all the SQL Logins for the specified Server
/// </summary>
/// <param name="credential">SQL Server Credentials</param>
/// <param name="ServerLogins">All SQL Server Logins on the specified server, or null if error occured</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError Logins(IConnectDb credential, out string[] ServerLogins)
{
ServerLogins = null;
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_SERVER);
if (dbError.ErrorOccured)
return dbError;
if (!credential.DBMS.IsDatabaseSetAndNonSystem)
return DBError.Create("Invalid Database Passed In via Credential");
string sql = "SELECT [name] FROM sys.sql_logins";
DB db = DB.Create(credential.DBMS.WithoutDatabase());
DBRetVal retVal = db.FillDataTable(sql);
if (retVal.IsValid)
{
List<String> retList = new List<string>();
foreach (DataRow row in retVal.GetDataTableRetVal().Rows)
retList.Add(row["name"].ToString());
ServerLogins = retList.ToArray();
}
return retVal;
}
/// <summary>
/// Adds a Login to the SQL Server Instance
/// </summary>
/// <param name="credential">SQL Server Credentials</param>
/// <param name="LoginName">LoginName (required)</param>
/// <param name="LoginPassword">LoginPassword (required)</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError LoginAdd(IConnectDb credential, string LoginName, string LoginPassword)
{
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_SERVER);
if (dbError.ErrorOccured)
return dbError;
if (!credential.DBMS.IsDatabaseSetAndNonSystem)
return DBError.Create("Invalid Database Passed In via Credential");
if (!ValidationConsts.Generic.IsValidUserName(LoginName))
return DBError.Create("Invalid LoginName Passed In");
if (!ValidationConsts.Generic.IsValidPassword(LoginPassword))
return DBError.Create("Invalid LoginPassword Passed In");
// Execute the Query
string sql = String.Format("CREATE LOGIN [{0}] WITH PASSWORD = '{1}', CHECK_EXPIRATION = OFF, CHECK_POLICY = OFF", LoginName, LoginPassword);
DB db = DB.Create(credential.DBMS.WithoutDatabase());
DBRetVal retVal = db.ExecuteNonQuery(sql);
return retVal;
}
/// <summary>
/// Drops a Login from the SQL Server Instance
/// </summary>
/// <param name="credential">SQL Server Credentials</param>
/// <param name="LoginName">LoginName (required)</param>
/// <param name="FallbackLoginName">Fallback Login used to change ownership to, in case error occurs because LoginName owns Databases (not required)</param>
/// <returns>true if successful, false otherwise</returns>
public static DBError LoginDrop(IConnectDb credential, string LoginName, string FallbackLoginName)
{
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_SERVER);
if (dbError.ErrorOccured)
return dbError;
if (!credential.DBMS.IsDatabaseSetAndNonSystem)
return DBError.Create("Invalid Database Passed In via Credential");
if (!ValidationConsts.Generic.IsValidUserName(LoginName))
return DBError.Create("Invalid LoginName Passed In");
// If User owns Databases, the Login Drop will fail, so
// query for existing databases
string[] ownedDBs = null;
DBError dberror = DatabasesOwnedByLogin(credential, LoginName, out ownedDBs);
// If Fallback Login was specified, use it to change the ownership on the Databases
if (ValidationConsts.Generic.IsValidUserName(FallbackLoginName) && (ownedDBs != null))
{
foreach (string ownedDB in ownedDBs)
{
dberror = DatabaseChangeOwnership(credential.DBMS.WithDatabase(ownedDB), FallbackLoginName);
if (dberror.ErrorOccured)
return dberror;
}
// Query Ownership again
dberror = DatabasesOwnedByLogin(credential, LoginName, out ownedDBs);
}
// If ther are no Owned DBs, this should succeed
if (ownedDBs == null)
{
DB db = DB.Create(credential.DBMS.WithoutDatabase());
string sql = String.Format("DROP LOGIN [{0}]", LoginName);
DBRetVal retVal = db.ExecuteNonQuery(sql);
return retVal;
}
return dberror;
}
/// <summary>
/// Changes the Password for the Login Name being passed in. The Login Name can be the same name as the User specified
/// via Credential (if that is the case, you must update your credential object, when this function returns true)
/// </summary>
/// <param name="credential">SQL Server Credentials</param>
/// <param name="LoginName">LoginName to change password for(can be the same/different than the User passed in thru credential) (required)</param>
/// <param name="NewLoginPassword">NewLoginPassword (required)</param>
/// <returns>true if successful * Password was changed for the passed in LoginName *, false otherwise</returns>
public static DBError LoginChangePassword(IConnectDb credential, string LoginName, string NewLoginPassword)
{
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_SERVER);
if (dbError.ErrorOccured)
return dbError;
if (!credential.DBMS.IsDatabaseSetAndNonSystem)
return DBError.Create("Invalid Database Passed In via Credential");
if (!ValidationConsts.Generic.IsValidUserName(LoginName))
return DBError.Create("Invalid LoginName Passed In");
if (!ValidationConsts.Generic.IsValidPassword(NewLoginPassword))
return DBError.Create("Invalid NewLoginPassword Passed In");
// Execute the Query and Return
string sql = string.Format("ALTER LOGIN [{0}] WITH PASSWORD = '{1}'", LoginName, NewLoginPassword);
DB db = DB.Create(credential.DBMS.WithoutDatabase());
DBRetVal retVal = db.ExecuteNonQuery(sql);
return retVal;
}
#endregion
}
}

318
Systems/SQLServer/Table.cs Normal file
View File

@@ -0,0 +1,318 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace Sdaleo.Systems.SQLServer
{
#region SQLServer Table Enums
/// <summary>
/// User Permissions on a Table
/// </summary>
public enum SQLServerTablePermission
{
SELECT,
UPDATE,
INSERT,
DELETE,
REFERENCES,
// EXECUTE // <-- not a table permission
}
#endregion
/// <summary>
/// Specific actions for SQL Server Tables in a Database
/// </summary>
public class SQLServerTable
{
#region Internal Table Helper Functions
/// <summary>
/// We must strip out the '_' on the SQLTablePermission Enum to use it in an SQL Query
/// </summary>
internal static string SQLTablePermission_ToString(SQLServerTablePermission TablePermission)
{
return TablePermission.ToString().Replace('_', ' ');
}
/// <summary>
/// Quick Helper function to get an SQLTablePermission[] that has all Permissions defined
/// </summary>
internal static SQLServerTablePermission[] SQLServerTablePermission_ToArray()
{
return (SQLServerTablePermission[])Enum.GetValues(typeof(SQLServerTablePermission));
}
/// <summary>
/// Returns a generated SQL Table Permissions string for the specified Table,Username with the specified permissions
/// </summary>
/// <param name="TableName">Name of a Table(required)</param>
/// <param name="Username">Name of an existing User that exists in that Database where the Table Resides (required)</param>
/// <param name="Action">Permission Action to take</param>
/// <param name="tablePermissions">array of permissions</param>
/// <returns>a table permission string or empty string if error occured</returns>
internal static string BuildSQLServerTablePermissionsStr(String TableName, string Username, SQLServerPermissionAction Action, SQLServerTablePermission[] tablePermissions)
{
if (String.IsNullOrEmpty(TableName) || String.IsNullOrEmpty(Username) || (tablePermissions == null))
return string.Empty;
// First the Action
string sql = Action.ToString() + " ";
// add each permission individually
for (int i = 0; i < tablePermissions.Length; ++i)
{
sql += SQLTablePermission_ToString(tablePermissions[i]);
bool bIsLast = (i == (tablePermissions.Length - 1));
if (!bIsLast)
sql += ",";
}
// Add Table
sql += String.Format(" ON [{1}]", TableName);
// add action adjective
if (Action == SQLServerPermissionAction.REVOKE)
sql += " FROM ";
else
sql += " TO ";
// add user
sql += string.Format("[{0}]", Username);
return sql;
}
#endregion
#region Table Permission
/// <summary>
/// Automatically grant,deny,revoke all permissions on the specified table for the specified user
/// </summary>
/// <param name="credential">SQL Server Credentials with Database Info</param>
/// <param name="Username">Specify the Username for the database (required)</param>
/// <param name="TableName">Specify the TableName to set permissions on (required)</param>
/// <param name="action">GRANT,DENY, or REVOKE 'Permission_All' Permission on that db</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError TableUserPermissionsAll(IConnectDb credential, string Username, string TableName, SQLServerPermissionAction action)
{
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_SERVER);
if (dbError.ErrorOccured)
return dbError;
if (!credential.DBMS.IsDatabaseSetAndNonSystem)
return DBError.Create("Invalid Database Passed In via Credential");
if (!ValidationConsts.Generic.IsValidUserName(Username))
return DBError.Create("Invalid Username Passed In");
dbError = Validation.IsValidTableName(TableName);
if (dbError.ErrorOccured)
return dbError;
// Get All Permissions
SQLServerTablePermission[] permissions = SQLServerTablePermission_ToArray();
// Perform the Action
return TableUserPermissions(credential, Username, TableName, permissions, action);
}
/// <summary>
/// Allows you to specify permissions to grant,deny,revoke on the specified table for the specified user
/// </summary>
/// <param name="credential">SQL Server Credentials with Database Info</param>
/// <param name="Username">Specify the Username for the database (required)</param>
/// <param name="TableName">Specify the TableName to set permissions on (required)</param>
/// <param name="permissions">an array of permissions to take action on on db</param>
/// <param name="action">GRANT,DENY, or REVOKE specified Permissions on that db</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError TableUserPermissions(IConnectDb credential, string Username, string TableName, SQLServerTablePermission[] permissions, SQLServerPermissionAction action)
{
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_SERVER);
if (dbError.ErrorOccured)
return dbError;
if (!credential.DBMS.IsDatabaseSetAndNonSystem)
return DBError.Create("Invalid Database Passed In via Credential");
if (!ValidationConsts.Generic.IsValidUserName(Username))
return DBError.Create("Invalid Username Passed In");
dbError = Validation.IsValidTableName(TableName);
if (dbError.ErrorOccured)
return dbError;
// Build the SQL and Execute the Query
string sql = BuildSQLServerTablePermissionsStr(TableName, Username, action, permissions);
DB db = DB.Create(credential);
DBRetVal retVal = db.ExecuteNonQuery(sql);
return retVal;
}
#endregion
#region Table Index
/// <summary>
/// Reindexes all Indexes on the Specified Table.
/// </summary>
/// <param name="credential">SQL Server Credentials with Database Info</param>
/// <param name="TableName">Specify the TableName to set permissions on (required)</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError TableReindex(IConnectDb credential, string TableName)
{
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_SERVER);
if (dbError.ErrorOccured)
return dbError;
if (!credential.DBMS.IsDatabaseSetAndNonSystem)
return DBError.Create("Invalid Database Passed In via Credential");
dbError = Validation.IsValidTableName(TableName);
if (dbError.ErrorOccured)
return dbError;
// Execute the Query
string sql = String.Format("DBCC DBREINDEX(\"{0}\", \" \", 90);", TableName);
DB db = DB.Create(credential);
DBRetVal retVal = db.ExecuteNonQuery(sql);
return retVal;
}
/// <summary>
/// Runs DBCC INDEXDEFRAG on the Specified Database, Table and Index
/// </summary>
/// <param name="credential">SQL Server Credentials with Database Info</param>
/// <param name="TableName">Name of Table (required)</param>
/// <param name="Index">Name of Index (required)</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError TableIndexDefrag(IConnectDb credential, string TableName, string IndexName)
{
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_SERVER);
if (dbError.ErrorOccured)
return dbError;
if (!credential.DBMS.IsDatabaseSetAndNonSystem)
return DBError.Create("Invalid Database Passed In via Credential");
dbError = Validation.IsValidTableName(TableName);
if (dbError.ErrorOccured)
return dbError;
if (String.IsNullOrEmpty(IndexName))
return DBError.Create("Invalid IndexName Passed In");
// Execute the Query
string sql = String.Format("DBCC INDEXDEFRAG ([{0}], [{1}], [{2}]) WITH NO_INFOMSGS", credential.DBMS.Database, TableName, IndexName);
DB db = DB.Create(credential);
DBRetVal retVal = db.ExecuteNonQuery(sql);
return retVal;
}
#endregion
#region Common Table Functions
/// <summary>
/// Returns all the Table Names for the specified Database
/// </summary>
/// <param name="credential">SQL Server Credentials with Database Info</param>
/// <param name="Tables">array of table names, or null if error occured</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError Tables(IConnectDb credential, out string[] Tables)
{
Tables = null;
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_SERVER);
if (dbError.ErrorOccured)
return dbError;
if (!credential.DBMS.IsDatabaseSetAndNonSystem)
return DBError.Create("Invalid Database Passed In via Credential");
// Execute the Query
string sql = "SELECT [name] FROM sys.Tables ORDER BY [name]";
DB db = DB.Create(credential);
DBRetVal retVal = db.FillDataTable(sql);
if (retVal.IsValid)
{
List<String> retList = new List<string>();
foreach (DataRow row in retVal.GetDataTableRetVal().Rows)
retList.Add(row["name"].ToString());
Tables = retList.ToArray();
}
return retVal;
}
/// <summary>
/// Check to see if the Table Exists on the specified Database
/// </summary>
/// <param name="credential">SQL Server Credentials with Database Info</param>
/// <param name="TableName">Specify the TableName to check for (required)</param>
/// <param name="bExists">true if exists, false otherwise</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError TableExists(IConnectDb credential, string TableName, out bool bExists)
{
bExists = false;
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_SERVER);
if (dbError.ErrorOccured)
return dbError;
if (!credential.DBMS.IsDatabaseSetAndNonSystem)
return DBError.Create("Invalid Database Passed In via Credential");
dbError = Validation.IsValidTableName(TableName);
if (dbError.ErrorOccured)
return dbError;
// Execute the Query
string sql = String.Format("SELECT [name] FROM sys.Tables WHERE [name]='{0}' ORDER BY [name]", TableName);
DB db = DB.Create(credential);
DBRetVal retVal = db.ExecuteScalar(sql);
bExists = !retVal.IsValid;
return retVal;
}
/// <summary>
/// Changes the Table Name for the specified Table
/// </summary>
/// <param name="credential">SQL Server Credentials with Database Info</param>
/// <param name="TableName">Name of Table (required)</param>
/// <param name="TableNameNew">Name of Table New (required)</param>
/// <returns>DBError Object with ErrorOccured, if error Occured</returns>
public static DBError TableRename(IConnectDb credential, string TableName, string TableNameNew)
{
DBError dbError = ValidationConsts.IsCredentialValid(credential, DBSystem.SQL_SERVER);
if (dbError.ErrorOccured)
return dbError;
if (!credential.DBMS.IsDatabaseSetAndNonSystem)
return DBError.Create("Invalid Database Passed In via Credential");
dbError = Validation.IsValidTableName(TableName);
if (dbError.ErrorOccured)
return dbError;
dbError = Validation.IsValidTableName(TableNameNew);
if (dbError.ErrorOccured)
return dbError;
// Update the Index Names using SMO * UNTESTED *
//Server server = DataType.ConvertCredentialToSMOServer(credential);
//foreach (Index index in server.Databases[credential.Database].Tables[TableName].Indexes)
// index.Name = index.Name.Replace(TableName, TableNameNew);
//server.Databases[credential.Database].Tables[TableName].Alter();
// Execute the Query
string sql = String.Format("EXEC sp_rename @objname = [{0}], @newname = [{1}], @objtype = 'OBJECT'", TableName, TableNameNew);
DB db = DB.Create(credential);
DBRetVal retVal = db.ExecuteNonQuery(sql);
return retVal;
}
#endregion
}
}

View File

@@ -0,0 +1,103 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sdaleo.Systems.SQLServer
{
#region SQLServer Utility Enums
/// <summary>
/// Default Databases that are usually part of an SQL Server
/// </summary>
internal enum SQLServerDefaultDatabase
{
master,
model,
msdb,
tempdb,
Northwind,
pubs
}
#endregion
/// <summary>
/// SQLServer Helper Utilites
/// </summary>
public class SQLServerUtilities
{
/// <summary>
/// Splits a DataSource String to it's ServerAddress and InstanceName components
/// </summary>
/// <param name="ServerOrServerNInstance">a DataSource string containing either Server or Server And Instance</param>
/// <param name="Server">Returns ServerAddress, if found</param>
/// <param name="Instance">Returns Instance name, if found</param>
/// <returns>True, if successfull, false otherwise</returns>
public static bool SplitServerOrServerNInstance(string ServerOrServerNInstance, out string Server, out string Instance)
{
Server = String.Empty;
Instance = String.Empty;
if (!string.IsNullOrEmpty(ServerOrServerNInstance) && (ServerOrServerNInstance.IndexOf('\\') >= 0))
{
string[] values = ServerOrServerNInstance.Split('\\');
if (values.Length == 2)
{
if(ValidationConsts.Generic.IsValidServerName(values[0]))
Server = values[0];
if(ValidationConsts.Generic.IsValidInstanceName(values[1]))
Instance = values[1];
return (!String.IsNullOrEmpty(Server) && !String.IsNullOrEmpty(Instance));
}
else
{
return false;
}
}
else if (!string.IsNullOrEmpty(ServerOrServerNInstance) && (ServerOrServerNInstance.IndexOf('\\') == 0))
{
if (ValidationConsts.Generic.IsValidServerName(ServerOrServerNInstance))
Server = ServerOrServerNInstance;
return (!String.IsNullOrEmpty(Server));
}
return false;
}
// Easy Access to SQL Master Database
public static string SQLServerMasterDatabaseName { get { return SQLServerDefaultDatabase.master.ToString(); } }
public static bool IsSQLServerMasterDatabaseName(string strDatabaseName) { return (SQLServerMasterDatabaseName.ToUpper() == strDatabaseName.ToUpper()); }
/// <summary>
/// Easy Check for Default Database * Any SQL Server Default Database *
/// </summary>
/// <param name="strDatabaseName">Name of Database to check for</param>
/// <returns>true if this is an SQL Server Default Database, false otherwise</returns>
public static bool IsDefaultDatabaseName(string strDatabaseName)
{
foreach (string strName in Enum.GetNames(typeof(SQLServerDefaultDatabase)))
{
if (strName.ToUpper() == strDatabaseName.ToUpper())
return true;
}
return false;
}
/// <summary>
/// Easy Check for System Database * Same as Default Database but does not inclue Northwind, or Pubs *
/// </summary>
/// <param name="strDatabaseName">Name of Database to check for</param>
/// <returns>true if this is an SQL Server System Database, false otherwise</returns>
public static bool IsSystemDatabaseName(string strDatabaseName)
{
foreach (string strName in Enum.GetNames(typeof(SQLServerDefaultDatabase)))
{
if (strName.ToUpper() == strDatabaseName.ToUpper() &&
(strDatabaseName.ToUpper() != "NORTHWIND") &&
(strDatabaseName.ToUpper() != "PUBS"))
return true;
}
return false;
}
}
}

View File

@@ -0,0 +1,90 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace Sdaleo.Systems
{
/// <summary>
/// This class will try to load the needed assembly(s) for the specified DB System.
/// If the Assembly load fails, we know that this system won't work (isn't available)
/// </summary>
public static class SystemAvailable
{
/// <summary>
/// Keep track of previous checks, no need to do it over and over again
/// </summary>
private static Dictionary<DBSystem, bool> _PrevCheckMap = new Dictionary<DBSystem, bool>();
/// <summary>
/// Try to load the assembly(s) for the specified DB System
/// </summary>
/// <param name="dbsystem">DB system to load assembly(s) for</param>
/// <returns>true, if successfully loaded, false otherwise</returns>
public static bool Check(DBSystem dbsystem)
{
try
{
// Performance Optimization
if (_PrevCheckMap.ContainsKey(dbsystem))
return _PrevCheckMap[dbsystem];
// ... Else we must check
switch (dbsystem)
{
case DBSystem.SQL_SERVER:
{
Assembly asm = Assembly.Load("System.Data");
_PrevCheckMap[dbsystem] = (asm != null);
return _PrevCheckMap[dbsystem];
}
case DBSystem.SQL_CE:
{
Assembly asm = Assembly.Load("System.Data.SqlServerCe");
_PrevCheckMap[dbsystem] = (asm != null);
return _PrevCheckMap[dbsystem];
}
case DBSystem.ADVANTAGE:
{
Assembly asm = Assembly.Load("Advantage.Data.Provider");
_PrevCheckMap[dbsystem] = (asm != null);
return _PrevCheckMap[dbsystem];
}
case DBSystem.CTREE:
{
Assembly asm = Assembly.Load("System.Data.SqlServerCe");
_PrevCheckMap[dbsystem] = (asm != null);
return _PrevCheckMap[dbsystem];
}
case DBSystem.MYSQL:
{
Assembly asm = Assembly.Load("System.Data.SqlServerCe");
_PrevCheckMap[dbsystem] = (asm != null);
return _PrevCheckMap[dbsystem];
}
case DBSystem.POSTGRES:
{
Assembly asm = Assembly.Load("Devart.Data");
if(asm != null)
asm = Assembly.Load("Devart.Data.PostgreSql");
_PrevCheckMap[dbsystem] = (asm != null);
return _PrevCheckMap[dbsystem];
}
default:
_PrevCheckMap[dbsystem] = false;
return false;
}
}
catch (Exception) { /* ignore */ }
_PrevCheckMap[dbsystem] = false;
return false;
}
}
}

247
Systems/ValidationConsts.cs Normal file
View File

@@ -0,0 +1,247 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace Sdaleo.Systems
{
/// <summary>
/// Validation Consts used throughout Validation of Parameters
/// </summary>
public static class ValidationConsts
{
#region Validation Consts
// Common
public const string CharSet_CharsNum = "0123456789";
public const string CharSet_CharsAlpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
public const string CharSet_CharsAlphaNum = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
public const string CharSet_CharsSambaComputerNames = CharSet_CharsAlphaNum + " -_";
public const string CharSet_CharsIPAddress = CharSet_CharsNum + ".";
public const string CharSet_CharsSpecialKeyboardAscii = " -_!@#$%^&*()_{}\\|:\":/?.,<>~`*-+[]'";
// Not Allowed
public const string CharSet_NotAllowedInFileNames = @"\/:*?<>|" + "\"";
public const string CharSet_NotAllowedInDirectorPaths = @"/*?<>|" + "\"";
// Allowed
public const string CharSet_AllowedUserNames = CharSet_CharsNum + " -_";
public const string CharSet_AllowedPasswords = CharSet_CharsNum + CharSet_CharsSpecialKeyboardAscii;
public const string CharSet_AllowedServerNames = CharSet_CharsSambaComputerNames + CharSet_CharsIPAddress; // we allow IP addresses as computer names
public const string CharSet_AllowedInstanceNames = CharSet_CharsAlphaNum + "$-_";
public const string CharSet_AllowedDatabaseNames = CharSet_CharsAlphaNum + CharSet_CharsSpecialKeyboardAscii;
public const string CharSet_AllowedTableNames = CharSet_CharsNum + " -_";
/// <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 sets declared above</param>
/// <returns>true if valid, false otherwise</returns>
public 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;
}
#endregion
#region CredentialValidation
/// <summary>
/// Use this to validate a credential object against a specific system
/// </summary>
/// <param name="credential">credential object to validate</param>
/// <param name="system">the system to validate against</param>
/// <returns>DBerror that either contains or doesn't contain an error</returns>
public static DBError IsCredentialValid(IConnectDb credential, DBSystem system)
{
if (credential == null)
return DBError.Create("Invalid Credential Object Passed In");
else if (credential.DBType != system)
return DBError.Create("Credential Object doesn't match system");
else if (!credential.IsValid)
return DBError.Create("Credential is invalid");
else
return new DBError();
}
#endregion
/// <summary>
/// Common Generally Generic Validation Functions that should be the same across the board
/// for all DBMS systems
/// </summary>
public static class Generic
{
/// <summary>
/// Main Validation Function to validate Usernames
/// </summary>
/// <param name="strUserName">Username to validate</param>
/// <returns>true if valid, false otherise</returns>
public static bool IsValidUserName(string strUserName)
{
if (String.IsNullOrEmpty(strUserName))
{
return false;
}
else if (strUserName.Length < 1 || strUserName.Length > 128) // limit User Name length
{
return false;
}
else if (!ContainsOnlyLegalChars(strUserName, CharSet_AllowedUserNames))
{
return false;
}
else
{
return true;
}
}
/// <summary>
/// Main Validation Function to validate Passwords
/// </summary>
/// <param name="strPassword">Password to validate</param>
/// <returns>true if valid, false otherise</returns>
public static bool IsValidPassword(string strPassword)
{
if (String.IsNullOrEmpty(strPassword))
{
return false;
}
else if (strPassword.Length < 1 || strPassword.Length > 128) // limit Password Length
{
return false;
}
else if (!ContainsOnlyLegalChars(strPassword, CharSet_AllowedPasswords))
{
return false;
}
else
{
return true;
}
}
/// <summary>
/// Calls IsValidUser && IsValidPassword
/// </summary>
/// <returns>true if valid, false otherise</returns>
internal static bool IsValidUserCredential(string strUserName, string strPassword)
{
return IsValidUserName(strUserName) && IsValidPassword(strPassword);
}
/// <summary>
/// Main Validation Function to validate Server Names
/// </summary>
/// <param name="strServerName">Name of a Server</param>
/// <returns>true if valid, false otherise</returns>
internal static bool IsValidServerName(string strServerName)
{
if (String.IsNullOrEmpty(strServerName))
{
return false;
}
// The maximum length for NetBIOS names is 15 characters. The maximum length for DNS computer names
// in an Active Directory environment is 24 characters
else if (strServerName.Length < 1 || strServerName.Length > 24) // limit server Name length
{
return false;
}
else if (!ContainsOnlyLegalChars(strServerName, CharSet_AllowedServerNames))
{
return false;
}
else
{
return true;
}
}
/// <summary>
/// Main Validation Function to validate Instancse Names
/// </summary>
/// <param name="strInstanceName">Name of an Instance</param>
/// <returns>true if valid, false otherise</returns>
internal static bool IsValidInstanceName(string strInstanceName)
{
if (string.IsNullOrEmpty(strInstanceName))
{
return false;
}
else if (strInstanceName.Length < 1 || strInstanceName.Length > 16) // limit Instance Name length
{
return false;
}
else if (!ContainsOnlyLegalChars(strInstanceName, CharSet_AllowedInstanceNames))
{
return false;
}
else
{
return true;
}
}
}
#region FileName and Path Validation
/// <summary>
/// Check to see if the filename is valid
/// </summary>
/// <param name="Filename">filename to check</param>
/// <returns>true if valid, false otherwise</returns>
public static bool IsValidFileName(string Filename)
{
if (!String.IsNullOrEmpty(Filename))
{
bool bIsValid = !ContainsOnlyLegalChars(Filename, CharSet_NotAllowedInFileNames);
return bIsValid;
}
return false;
}
/// <summary>
/// Check to see if directory path is valid
/// </summary>
/// <param name="Path">directory path</param>
/// <returns>true if valid, false otherwise</returns>
public static bool IsValidDirectoryPath(string Path)
{
if (!String.IsNullOrEmpty(Path))
{
bool bIsValid = !ContainsOnlyLegalChars(Path, CharSet_NotAllowedInDirectorPaths);
return bIsValid;
}
return false;
}
/// <summary>
/// Check to see if directory and file name are valid
/// </summary>
/// <param name="FileNameNPath">filename including path information</param>
/// <returns>true if valid, false otherwise</returns>
public static bool IsValidFileNameNPath(string FileNameNPath)
{
if(!String.IsNullOrEmpty(FileNameNPath))
{
string path = Path.GetDirectoryName(FileNameNPath);
string file = Path.GetFileName(FileNameNPath);
bool bValid = IsValidDirectoryPath(path) && IsValidFileName(file);
return bValid;
}
return false;
}
#endregion
}
}

Binary file not shown.

View File

@@ -0,0 +1,10 @@
C:\_ROOT_\PlexProjects\Sdaleo\obj\Debug\ResolveAssemblyReference.cache
C:\_ROOT_\PlexProjects\Target\Debug\Sdaleo.dll
C:\_ROOT_\PlexProjects\Target\Debug\Sdaleo.pdb
C:\_ROOT_\PlexProjects\Sdaleo\obj\Debug\Sdaleo.dll
C:\_ROOT_\PlexProjects\Sdaleo\obj\Debug\Sdaleo.pdb
C:\_ROOT_ (Sync'd)\PlexProjects\Target\Debug\Sdaleo.dll
C:\_ROOT_ (Sync'd)\PlexProjects\Target\Debug\Sdaleo.pdb
C:\_ROOT_ (Sync'd)\PlexProjects\Sdaleo\obj\Debug\ResolveAssemblyReference.cache
C:\_ROOT_ (Sync'd)\PlexProjects\Sdaleo\obj\Debug\Sdaleo.dll
C:\_ROOT_ (Sync'd)\PlexProjects\Sdaleo\obj\Debug\Sdaleo.pdb

BIN
obj/Debug/Sdaleo.dll Normal file

Binary file not shown.

BIN
obj/Debug/Sdaleo.pdb Normal file

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,5 @@
C:\_ROOT_ (Sync'd)\PlexProjects\Target\Release\Sdaleo.dll
C:\_ROOT_ (Sync'd)\PlexProjects\Target\Release\Sdaleo.pdb
C:\_ROOT_ (Sync'd)\PlexProjects\Sdaleo\obj\Release\ResolveAssemblyReference.cache
C:\_ROOT_ (Sync'd)\PlexProjects\Sdaleo\obj\Release\Sdaleo.dll
C:\_ROOT_ (Sync'd)\PlexProjects\Sdaleo\obj\Release\Sdaleo.pdb

BIN
obj/Release/Sdaleo.dll Normal file

Binary file not shown.

BIN
obj/Release/Sdaleo.pdb Normal file

Binary file not shown.