001.
using
System;
002.
using
System.Collections.Generic;
003.
using
System.Linq;
004.
using
System.Web;
005.
006.
using
System.Data;
007.
using
System.Data.SqlClient;
008.
using
System.Globalization;
009.
using
System.IO;
010.
using
System.Text.RegularExpressions;
011.
using
System.Web.Configuration;
012.
013.
#region ========== Class SqlDatabaseManager ==========
014.
/// <summary>
015.
/// Summary description for SqlDatabase
016.
/// </summary>
017.
public
class
SqlDatabaseManager
018.
{
019.
#region ========== Global Variables ==========
020.
private
SqlConnection sqlConnection;
021.
private
SqlCommand sqlCommand;
022.
private
SqlTransaction sqlTransaction;
023.
private
List<
string
> errorCommand;
024.
025.
private
string
sqlConnectionString =
string
.Empty;
026.
private
string
sqlConnectionKeyName =
string
.Empty;
027.
private
string
sqlCommandString =
string
.Empty;
028.
private
string
commandMessage =
"You must execute command."
;
029.
private
bool
commandSuccess =
false
;
030.
private
bool
transaction =
false
;
031.
private
int
rowsAffected = 0;
032.
#endregion
033.
034.
#region ========= Constructor ==========
035.
/// <summary>
036.
/// Use sql connection string from web.config configulation.
037.
/// </summary>
038.
public
SqlDatabaseManager()
039.
{
040.
if
(WebConfigurationManager.ConnectionStrings[
"SqlConnectionString"
] !=
null
)
041.
{
042.
043.
044.
045.
046.
047.
048.
049.
sqlConnectionKeyName =
"SqlConnectionString"
;
050.
sqlConnectionString = WebConfigurationManager.ConnectionStrings[
"SqlConnectionString"
].ToString();
051.
sqlConnection =
new
SqlConnection(sqlConnectionString);
052.
}
053.
else
054.
{
055.
sqlConnection =
new
SqlConnection();
056.
}
057.
}
058.
059.
/// <summary>
060.
/// Use sql connection string from web.config configulation by key name.
061.
/// </summary>
062.
public
SqlDatabaseManager(
string
SqlConnectionKeyName)
063.
{
064.
sqlConnectionKeyName = SqlConnectionKeyName;
065.
sqlConnectionString = WebConfigurationManager.ConnectionStrings[sqlConnectionKeyName].ToString();
066.
sqlConnection =
new
SqlConnection(sqlConnectionString);
067.
}
068.
069.
/// <summary>
070.
/// Use sql connection string by user define.
071.
/// </summary>
072.
public
SqlDatabaseManager(
string
SqlConnectionKeyName,
string
SqlConnectionString)
073.
{
074.
sqlConnectionKeyName = SqlConnectionKeyName;
075.
sqlConnectionString = SqlConnectionString;
076.
sqlConnection =
new
SqlConnection(sqlConnectionString);
077.
}
078.
#endregion
079.
080.
#region ========== Property ==========
081.
/// <summary>
082.
/// Gets or sets Sql connection key name from web.config.
083.
/// </summary>
084.
public
virtual
string
ConnectionKeyName
085.
{
086.
get
{
return
sqlConnectionKeyName; }
087.
set
088.
{
089.
sqlConnectionKeyName = value;
090.
sqlConnectionString = WebConfigurationManager.ConnectionStrings[sqlConnectionKeyName].ToString();
091.
sqlConnection =
new
SqlConnection(sqlConnectionString);
092.
}
093.
}
094.
095.
/// <summary>
096.
/// Gets or sets Sql connection.
097.
/// </summary>
098.
public
virtual
string
ConnectionString
099.
{
100.
get
{
return
sqlConnectionString; }
101.
set
102.
{
103.
sqlConnectionString = value;
104.
sqlConnection =
new
SqlConnection(sqlConnectionString);
105.
}
106.
}
107.
108.
/// <summary>
109.
/// Gets or sets Sql command.
110.
/// </summary>
111.
public
virtual
string
CommandString
112.
{
113.
get
{
return
sqlCommandString; }
114.
set
115.
{
116.
sqlCommandString = ConvertDateCommand(value);
117.
sqlCommand =
new
SqlCommand(sqlCommandString, sqlConnection);
118.
119.
commandMessage =
"You must execute command."
;
120.
commandSuccess =
false
;
121.
rowsAffected = 0;
122.
123.
if
(transaction)
124.
sqlCommand.Transaction = sqlTransaction;
125.
}
126.
}
127.
128.
/// <summary>
129.
/// Check for Sql command.
130.
/// </summary>
131.
public
virtual
bool
IsSuccess
132.
{
133.
get
{
return
commandSuccess; }
134.
}
135.
136.
/// <summary>
137.
/// Gets message from Sql command.
138.
/// </summary>
139.
public
virtual
string
Message
140.
{
141.
get
{
return
commandMessage; }
142.
}
143.
144.
/// <summary>
145.
/// Gets Number of rows affected.
146.
/// </summary>
147.
public
virtual
int
RowsAffected
148.
{
149.
get
{
return
rowsAffected; }
150.
}
151.
#endregion
152.
153.
#region ========== Method ==========
154.
/// <summary>
155.
/// Add the parameter value to the sql command.
156.
/// </summary>
157.
/// <param name="ParameterName">The name of Parameter.</param>
158.
/// <param name="ParameterValue">The value to be added.</param>
159.
public
virtual
void
AddParameter(
string
ParameterName,
object
ParameterValue)
160.
{
161.
sqlCommand.Parameters.AddWithValue(ParameterName, ParameterValue);
162.
}
163.
164.
/// <summary>
165.
/// Start Sql Transaction.
166.
/// </summary>
167.
public
virtual
void
TransactionStart()
168.
{
169.
transaction =
true
;
170.
errorCommand =
new
List<
string
>();
171.
172.
if
(sqlConnection.State != ConnectionState.Open)
173.
sqlConnection.Open();
174.
175.
sqlTransaction = sqlConnection.BeginTransaction(IsolationLevel.ReadCommitted);
176.
}
177.
178.
/// <summary>
179.
/// Execute Sql Transaction.
180.
/// </summary>
181.
/// <returns>Result of transaction.</returns>
182.
public
virtual
bool
ExecuteTransaction()
183.
{
184.
transaction =
false
;
185.
186.
if
(errorCommand.Count == 0)
187.
{
188.
sqlTransaction.Commit();
189.
190.
commandMessage =
"All command is successfully. <font color=\"darkgreen\">Transaction Commited.</font>"
;
191.
commandSuccess =
true
;
192.
}
193.
else
194.
{
195.
sqlTransaction.Rollback();
196.
197.
string
ErrorText =
"Some command has error. <font color=\"red\">Transaction RollBack.</font><br />Error in: <br />"
;
198.
199.
foreach
(
string
aErrorSqlCommand
in
errorCommand)
200.
{
201.
ErrorText += aErrorSqlCommand +
"<br />"
;
202.
}
203.
204.
commandMessage = ErrorText;
205.
commandSuccess =
false
;
206.
}
207.
208.
errorCommand.Clear();
209.
210.
if
(sqlConnection.State == ConnectionState.Open)
211.
sqlConnection.Close();
212.
213.
sqlTransaction.Dispose();
214.
sqlCommand.Dispose();
215.
sqlConnection.Dispose();
216.
217.
return
commandSuccess;
218.
}
219.
220.
/// <summary>
221.
/// Execute Query Sql command.
222.
/// </summary>
223.
/// <returns>Query data in DataTable.</returns>
224.
public
virtual
DataTable ExecuteQuery()
225.
{
226.
DataTable dataTable =
new
DataTable();
227.
228.
try
229.
{
230.
SqlDataAdapter sqlDataAdapter =
new
SqlDataAdapter(sqlCommand);
231.
sqlDataAdapter.Fill(dataTable);
232.
sqlDataAdapter.Dispose();
233.
234.
if
(!transaction)
235.
{
236.
sqlCommand.Dispose();
237.
sqlConnection.Dispose();
238.
}
239.
240.
commandMessage =
"Command is successfully."
;
241.
commandSuccess =
true
;
242.
}
243.
catch
(Exception ex)
244.
{
245.
commandMessage = ErrorMessage(ex.Message);
246.
commandSuccess =
false
;
247.
}
248.
249.
rowsAffected = dataTable.Rows.Count;
250.
251.
return
dataTable;
252.
}
253.
254.
/// <summary>
255.
/// Execute Scalar Sql command.
256.
/// </summary>
257.
/// <returns>Object of value.</returns>
258.
public
virtual
object
ExecuteScalar()
259.
{
260.
object
Result = 0;
261.
262.
try
263.
{
264.
if
(transaction)
265.
{
266.
Result = sqlCommand.ExecuteScalar();
267.
}
268.
else
269.
{
270.
if
(sqlConnection.State != ConnectionState.Open)
271.
sqlConnection.Open();
272.
273.
Result = sqlCommand.ExecuteScalar();
274.
sqlConnection.Close();
275.
276.
sqlCommand.Dispose();
277.
sqlConnection.Dispose();
278.
}
279.
280.
commandMessage =
"Command is successfully."
;
281.
commandSuccess =
true
;
282.
}
283.
catch
(Exception ex)
284.
{
285.
commandMessage = ErrorMessage(ex.Message);
286.
commandSuccess =
false
;
287.
AddErrorCommand(sqlCommandString, ex.Message);
288.
}
289.
290.
return
Result;
291.
}
292.
293.
/// <summary>
294.
/// Execute Non Query Sql command.
295.
/// </summary>
296.
/// <returns>Result of execute command.</returns>
297.
public
virtual
bool
ExecuteNonQuery()
298.
{
299.
rowsAffected = 0;
300.
301.
try
302.
{
303.
if
(transaction)
304.
{
305.
rowsAffected = sqlCommand.ExecuteNonQuery();
306.
}
307.
else
308.
{
309.
if
(sqlConnection.State != ConnectionState.Open)
310.
sqlConnection.Open();
311.
312.
rowsAffected = sqlCommand.ExecuteNonQuery();
313.
sqlConnection.Close();
314.
315.
sqlCommand.Dispose();
316.
sqlConnection.Dispose();
317.
}
318.
319.
commandMessage =
"Command is successfully."
;
320.
commandSuccess =
true
;
321.
}
322.
catch
(Exception ex)
323.
{
324.
commandMessage = ErrorMessage(ex.Message);
325.
commandSuccess =
false
;
326.
AddErrorCommand(sqlCommandString, ex.Message);
327.
}
328.
329.
return
commandSuccess;
330.
}
331.
332.
/// <summary>
333.
/// Build error message.
334.
/// </summary>
335.
/// <param name="Message">Message string.</param>
336.
/// <returns>Error message string.</returns>
337.
protected
virtual
string
ErrorMessage(
string
MessageString)
338.
{
339.
return
"<font color=\"red\">Command error.</font> "
+ MessageString;
340.
}
341.
342.
/// <summary>
343.
/// Add error sql command to string collections.
344.
/// </summary>
345.
/// <param name="commandString">The sql command.</param>
346.
/// <param name="errorMessage">The error message.</param>
347.
protected
virtual
void
AddErrorCommand(
string
commandString,
string
errorMessage)
348.
{
349.
errorCommand.Add(commandString +
" <font color=\"red\">[Error message: "
+ errorMessage +
"]</font>"
);
350.
}
351.
352.
/// <summary>
353.
/// Convert native command to sql command.
354.
/// </summary>
355.
/// <param name="commandString">The native sql command.</param>
356.
/// <returns>The standard sql command.</returns>
357.
protected
virtual
string
ConvertDateCommand(
string
commandString)
358.
{
359.
string
SmallDateTimePattern =
"[sS][mM][aA][lL][lL][dD][aA][tT][eE][tT][iI][mM][eE]\\([@][0-9a-zA-Z\\s]{1,}\\)"
;
360.
Regex SmallDateTimeRgx =
new
Regex(SmallDateTimePattern);
361.
362.
foreach
(Match SmallDateTimeMatchCase
in
SmallDateTimeRgx.Matches(commandString))
363.
{
364.
string
MatchCasePattern =
"^[sS][mM][aA][lL][lL][dD][aA][tT][eE][tT][iI][mM][eE]"
;
365.
Regex MatchCaseRgx =
new
Regex(MatchCasePattern);
366.
Match RemoveMatch = MatchCaseRgx.Match(SmallDateTimeMatchCase.Value);
367.
string
TempMatchCase = SmallDateTimeMatchCase.Value.Replace(RemoveMatch.Value,
""
);
368.
369.
commandString = commandString.Replace(SmallDateTimeMatchCase.Value, TempMatchCase.Replace(
"("
,
"Convert(SmallDateTime, "
).Replace(
")"
,
", 103)"
));
370.
}
371.
372.
string
DateTimePattern =
"[dD][aA][tT][eE][tT][iI][mM][eE]\\([@][0-9a-zA-Z\\s]{1,}\\)"
;
373.
Regex DateTimeRgx =
new
Regex(DateTimePattern);
374.
375.
foreach
(Match DateTimeMatchCase
in
DateTimeRgx.Matches(commandString))
376.
{
377.
string
MatchCasePattern =
"^[dD][aA][tT][eE][tT][iI][mM][eE]"
;
378.
Regex MatchCaseRgx =
new
Regex(MatchCasePattern);
379.
Match RemoveMatch = MatchCaseRgx.Match(DateTimeMatchCase.Value);
380.
string
TempMatchCase = DateTimeMatchCase.Value.Replace(RemoveMatch.Value,
""
);
381.
382.
commandString = commandString.Replace(DateTimeMatchCase.Value, TempMatchCase.Replace(
"("
,
"Convert(DateTime, "
).Replace(
")"
,
", 103)"
));
383.
}
384.
385.
return
commandString;
386.
}
387.
#endregion
388.
}
389.
#endregion
390.
391.
#region ========== Class SqlConvert ==========
392.
/// <summary>
393.
/// Summary description for SqlConvert
394.
/// </summary>
395.
public
sealed
class
SqlConvert
396.
{
397.
/// <summary>
398.
/// Convert to byte[].
399.
/// </summary>
400.
/// <param name="BinaryStream">File upload binary stream.</param>
401.
/// <param name="StreamLength">Lenght of File upload binary stream.</param>
402.
/// <returns>Byte[] of binary stream.</returns>
403.
public
static
byte
[] ToVarBinary(Stream BinaryStream,
int
StreamLength)
404.
{
405.
BinaryReader BinaryRead =
new
BinaryReader(BinaryStream);
406.
byte
[] binaryData = BinaryRead.ReadBytes(StreamLength);
407.
408.
return
binaryData;
409.
}
410.
411.
/// <summary>
412.
/// Convert to DataTime DataType with d/M/yyyy format.
413.
/// </summary>
414.
/// <param name="DateString">DateTime sring.</param>
415.
/// <returns>Datetime Type.</returns>
416.
public
static
DateTime ToDateTime(
string
DateString)
417.
{
418.
419.
420.
421.
422.
423.
return
DateTime.ParseExact(DateString,
"d/M/yyyy"
, CultureInfo.InvariantCulture);
424.
}
425.
426.
/// <summary>
427.
/// Convert to DataTime DataType with user define format.
428.
/// </summary>
429.
/// <param name="DateString">DateTime sring.</param>
430.
/// <param name="DateFormat">DateTime Format</param>
431.
/// <returns>Datetime Type.</returns>
432.
public
static
DateTime ToDateTime(
string
DateString,
string
DateFormat)
433.
{
434.
435.
436.
437.
438.
439.
return
DateTime.ParseExact(DateString, DateFormat, CultureInfo.InvariantCulture);
440.
}
441.
}
442.
#endregion