using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Odbc;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Text;
namespace Neo.Afx.ComponentModel
{
///
/// Groups some functionality to test connections to either a Database or Web Service.
///
public static class Connection
{
#region TryConnect
///
/// A method for attempting to connect to a DB Server or WebService
///
///
///
///
///
///
///
///
///
public static bool TryConnect(short connectionTypeID, string connectionString, short authTypeID, string authDomain, string authUser, string authPassword, out string errorMessage)
{
errorMessage = "";
try
{
switch (connectionTypeID)
{
case 1: //SQL Server
TryDbConnect(new SqlConnection(connectionString), out errorMessage);
break;
case 2: // OLE DB
TryDbConnect(new OleDbConnection(connectionString), out errorMessage);
break;
case 3: // ODBC
case 4: // Oracle
TryDbConnect(new OdbcConnection(connectionString), out errorMessage);
break;
case 5: // Web
var request = WebRequest.Create(connectionString) as HttpWebRequest;
if (request != null)
{
if (authTypeID == 2) // NetworkCredential
{
request.Credentials = new NetworkCredential(authUser, authPassword, authDomain);
}
using (var response = request.GetResponse() as HttpWebResponse)
{
if (response != null)
{
if (response.StatusCode != HttpStatusCode.OK)
{
errorMessage = "Connection Failed - Error locating web service: " + response.StatusDescription;
}
}
else
{
errorMessage = "Connection Failed - Response is NULL";
}
}
}
else
{
errorMessage = "Connection Failed - Request is NULL";
}
break;
}
}
catch (Exception ex)
{
errorMessage = "Connection Failed - " + ex.Message;
}
return errorMessage.Trim().Length == 0;
}
#endregion
#region TryDbConnect
///
/// Method for attempting to connect to any connection that Inherits from IDBConnection
///
/// An IDbConnection to a database
/// An out parameter that contains an error message should there be one
///
private static bool TryDbConnect(IDbConnection dbConnection, out string errorMessage)
{
errorMessage = "";
using (var connection = dbConnection)
{
try
{
connection.Open();
connection.Close();
}
catch (Exception ex)
{
errorMessage = "Connection Failed - " + ex.Message;
}
}
return errorMessage.Trim().Length == 0;
}
#endregion
}
}