84 lines
2.4 KiB
C#

using System;
using System.Configuration;
using Csla;
using System.Data.SqlClient;
using System.IO;
namespace Volian.Object.Library
{
public static class Database
{
#region Log4Net
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endregion
public static string VEPROMS_Connection
{
get
{
DateTime.Today.ToLongDateString();
ConnectionStringSettings cs = ConfigurationManager.ConnectionStrings["VEPROMS"];
if (cs == null)
{
throw new ApplicationException("Database.cs Could not find connection VEPROMS");
}
return cs.ConnectionString;
}
}
public static SqlConnection VEPROMS_SqlConnection
{
get
{
string strConn = VEPROMS_Connection; // If failure - Fail (Don't try to catch)
// Attempt to make a connection
try
{
SqlConnection cn = new SqlConnection(strConn);
cn.Open();
return cn;
}
catch (SqlException exsql)
{
const string strAttachError = "An attempt to attach an auto-named database for file ";
if (exsql.Message.StartsWith(strAttachError))
{// Check to see if the file is missing
string sFile = exsql.Message.Substring(strAttachError.Length);
sFile = sFile.Substring(0, sFile.IndexOf(" failed"));
// "An attempt to attach an auto-named database for file <mdf file> failed"
if (strConn.ToLower().IndexOf("user instance=true") < 0)
{
throw new ApplicationException("Connection String missing attribute: User Instance=True");
}
if (File.Exists(sFile))
{
throw new ApplicationException("Database file " + sFile + " Cannot be opened\r\n", exsql);
}
else
{
throw new FileNotFoundException("Database file " + sFile + " Not Found", exsql);
}
}
else
{
throw new ApplicationException("Failure on Connect", exsql);
}
}
catch (Exception ex)// Throw Application Exception on Failure
{
if (log.IsErrorEnabled) log.Error("Connection Error", ex);
throw new ApplicationException("Failure on Connect", ex);
}
}
}
public static void LogException(string s,Exception ex)
{
log.Error(s,ex);
int i = 0;
Console.WriteLine("Error - {0}", s);
for (; ex != null; ex = ex.InnerException)
{
Console.WriteLine("{0}{1} - {2}", "".PadLeft(i * 2), ex.GetType().ToString(), ex.Message);
}
}
}
}