using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.Common; using System.Web; using System.Configuration; using System.Data.SqlClient; namespace Bowin.Common.Linq.DB { internal static class ConnectionCache { static ConnectionCache() { IsGlobalConnectionStarted = false; ConnectionContexts = new Dictionary(); } public static bool IsGlobalConnectionStarted { get; set; } public static Dictionary ConnectionContexts { get; set; } } public abstract class DbConnectionManager { public static bool IsGlobalConnectionStarted { get { if (HttpContext.Current != null && HttpContext.Current.Session != null) { return (bool)(HttpContext.Current.Session["IsGlobalConnectionStarted"] ?? false); } else { return ConnectionCache.IsGlobalConnectionStarted; } } set { if (HttpContext.Current != null) { HttpContext.Current.Session["IsGlobalConnectionStarted"] = value; } else { ConnectionCache.IsGlobalConnectionStarted = value; } } } protected static bool ExistsConnection(string contextKey) { if (HttpContext.Current != null) { return HttpContext.Current.Session[contextKey] != null; } else { return ConnectionCache.ConnectionContexts[contextKey] != null; } } public static void AddConnection(string contextKey, DbConnection db) { if (HttpContext.Current != null) { HttpContext.Current.Session[contextKey] = db; } else { ConnectionCache.ConnectionContexts.Add(contextKey, db); } } public static void CloseConnections() { if (HttpContext.Current != null) { foreach (ConnectionStringSettings connectionSetting in System.Configuration.ConfigurationManager.ConnectionStrings) { DbConnection db; db = (DbConnection)HttpContext.Current.Session[connectionSetting.Name]; if (db != null) { if (db.State != System.Data.ConnectionState.Closed) { db.Close(); } } } } else { foreach (var connection in ConnectionCache.ConnectionContexts) { if (connection.Value.State != System.Data.ConnectionState.Closed) { connection.Value.Close(); } } } } public static void ClearConnection() { if (HttpContext.Current != null) { foreach (ConnectionStringSettings connectionSetting in System.Configuration.ConfigurationManager.ConnectionStrings) { HttpContext.Current.Session[connectionSetting.Name] = null; } } else { ConnectionCache.ConnectionContexts = new Dictionary(); } IsGlobalConnectionStarted = false; } internal static DbConnection GetConnection(string contextKey) { if (HttpContext.Current != null) { return (DbConnection)HttpContext.Current.Session[contextKey]; } else { return ConnectionCache.ConnectionContexts[contextKey]; } } } }