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

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