-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConnectionManager.cs
More file actions
65 lines (60 loc) · 2.24 KB
/
Copy pathConnectionManager.cs
File metadata and controls
65 lines (60 loc) · 2.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
using System;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
namespace Bss.Entities
{
public class ConnectionManager
{
public static SqlConnection BuildSqlConnection(string connectionString, string preSlqCommand)
{
SqlConnection result = new SqlConnection(connectionString);
StateChangeEventHandler sceh = null;
if (!string.IsNullOrEmpty(preSlqCommand))
{
sceh = CreateStateChangeEventHandler(preSlqCommand);
result.StateChange += sceh;
}
result.Disposed += CreateConnectionDisposedEventHandler(sceh);
return result;
}
private static StateChangeEventHandler CreateStateChangeEventHandler(string preSlqCommand)
{
return (sender, args) =>
{
if (args.OriginalState == ConnectionState.Closed
&& args.CurrentState == ConnectionState.Open
&& !string.IsNullOrEmpty(preSlqCommand))
try
{
using (SqlCommand _Command = ((SqlConnection)sender).CreateCommand())
{
_Command.CommandType = CommandType.Text;
_Command.CommandText = preSlqCommand;
_Command.ExecuteNonQuery();
}
}
catch (Exception e)
{
Trace.TraceError($"Error while executing connection pre-command : {e.Message}");
}
};
}
private static EventHandler CreateConnectionDisposedEventHandler(StateChangeEventHandler sceh)
{
EventHandler result = null;
result = (sender, e) =>
{
SqlConnection sqlConnection = sender as SqlConnection;
if (sqlConnection != null)
{
if(sceh != null)
sqlConnection.StateChange -= sceh;
sqlConnection.Disposed -= result;
Trace.TraceInformation("Sql connection is disposed");
}
};
return result;
}
}
}