123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124 |
- 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<string, DbConnection>();
- }
- public static bool IsGlobalConnectionStarted { get; set; }
- public static Dictionary<string, DbConnection> 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;
- }
- }
- }
- 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<string, DbConnection>();
- }
- IsGlobalConnectionStarted = false;
- }
- internal static DbConnection GetConnection(string contextKey)
- {
- if (HttpContext.Current != null)
- {
- return (DbConnection)HttpContext.Current.Session[contextKey];
- }
- else
- {
- return ConnectionCache.ConnectionContexts[contextKey];
- }
- }
- }
- }
|