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
abstract
class
SqlDatabaseManager
018.
{
019.
#region ========== Field ==========
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.
protected
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.
protected
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.
protected
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.
protected
virtual
bool
IsSuccess
132.
{
133.
get
{
return
commandSuccess; }
134.
}
135.
136.
/// <summary>
137.
/// Gets message from Sql command.
138.
/// </summary>
139.
protected
virtual
string
Message
140.
{
141.
get
{
return
commandMessage; }
142.
}
143.
144.
/// <summary>
145.
/// Gets Number of rows affected.
146.
/// </summary>
147.
protected
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.
protected
virtual
void
AddParameter(
string
ParameterName,
object
ParameterValue)
160.
{
161.
sqlCommand.Parameters.AddWithValue(ParameterName, ParameterValue);
162.
}
163.
164.
/// <summary>
165.
/// Add the parameter value to the sql command.
166.
/// </summary>
167.
///<param name="ParameterName">The name of the parameter.</param>
168.
///<param name="SqlDataType">One of the SqlDbType values.</param>
169.
///<param name="Size">The column length.</param>
170.
///<param name="ColumnName">The name of the source column.</param>
171.
protected
virtual
void
AddParameter(
string
ParameterName, SqlDbType SqlDataType,
int
Size,
string
ColumnName)
172.
{
173.
sqlCommand.Parameters.Add(ParameterName, SqlDataType, Size, ColumnName);
174.
}
175.
176.
/// <summary>
177.
/// Start Sql Transaction.
178.
/// </summary>
179.
protected
virtual
void
TransactionStart()
180.
{
181.
transaction =
true
;
182.
errorCommand =
new
List<
string
>();
183.
184.
if
(sqlConnection.State != ConnectionState.Open)
185.
sqlConnection.Open();
186.
187.
sqlTransaction = sqlConnection.BeginTransaction(IsolationLevel.ReadCommitted);
188.
}
189.
190.
/// <summary>
191.
/// Insert the DataTable to database.
192.
/// </summary>
193.
/// <param name="DataSource">The name of the DataTable. </param>
194.
/// <returns>Result of command.</returns>
195.
protected
virtual
bool
Insert(DataTable DataSource)
196.
{
197.
bool
result =
false
;
198.
199.
try
200.
{
201.
SqlDataAdapter sqlAdapter =
new
SqlDataAdapter();
202.
sqlAdapter.InsertCommand = sqlCommand;
203.
rowsAffected = sqlAdapter.Update(DataSource);
204.
205.
commandMessage =
"Command is successfully."
;
206.
commandSuccess =
true
;
207.
result =
true
;
208.
}
209.
catch
(Exception ex)
210.
{
211.
commandMessage = ErrorMessage(ex.Message);
212.
commandSuccess =
false
;
213.
}
214.
215.
return
result;
216.
}
217.
218.
/// <summary>
219.
/// Update the database by DataTeble.
220.
/// </summary>
221.
/// <param name="DataSource">The name of the DataTable. </param>
222.
/// <returns>Result of command.</returns>
223.
protected
virtual
bool
Update(DataTable DataSource)
224.
{
225.
bool
result =
false
;
226.
227.
try
228.
{
229.
SqlDataAdapter sqlAdapter =
new
SqlDataAdapter();
230.
sqlAdapter.UpdateCommand = sqlCommand;
231.
rowsAffected = sqlAdapter.Update(DataSource);
232.
233.
commandMessage =
"Command is successfully."
;
234.
commandSuccess =
true
;
235.
result =
true
;
236.
}
237.
catch
(Exception ex)
238.
{
239.
commandMessage = ErrorMessage(ex.Message);
240.
commandSuccess =
false
;
241.
}
242.
243.
return
result;
244.
}
245.
246.
/// <summary>
247.
/// Delete the database by DataTeble.
248.
/// </summary>
249.
/// <param name="DataSource">The name of the DataTable. </param>
250.
/// <returns>Result of command.</returns>
251.
protected
virtual
bool
Delete(DataTable DataSource)
252.
{
253.
bool
result =
false
;
254.
255.
try
256.
{
257.
SqlDataAdapter sqlAdapter =
new
SqlDataAdapter();
258.
sqlAdapter.DeleteCommand = sqlCommand;
259.
rowsAffected = sqlAdapter.Update(DataSource);
260.
261.
commandMessage =
"Command is successfully."
;
262.
commandSuccess =
true
;
263.
result =
true
;
264.
}
265.
catch
(Exception ex)
266.
{
267.
commandMessage = ErrorMessage(ex.Message);
268.
commandSuccess =
false
;
269.
}
270.
271.
return
result;
272.
}
273.
274.
/// <summary>
275.
/// Execute Sql Transaction.
276.
/// </summary>
277.
/// <returns>Result of transaction.</returns>
278.
protected
virtual
bool
ExecuteTransaction()
279.
{
280.
transaction =
false
;
281.
282.
if
(errorCommand.Count == 0)
283.
{
284.
sqlTransaction.Commit();
285.
286.
commandMessage =
"All command is successfully. <font color=\"darkgreen\">Transaction Commited.</font>"
;
287.
commandSuccess =
true
;
288.
}
289.
else
290.
{
291.
sqlTransaction.Rollback();
292.
293.
string
ErrorText =
"Some command has error. <font color=\"red\">Transaction Rollback.</font><br />Error in: <br />"
;
294.
295.
foreach
(
string
aErrorSqlCommand
in
errorCommand)
296.
{
297.
ErrorText += aErrorSqlCommand +
"<br />"
;
298.
}
299.
300.
commandMessage = ErrorText;
301.
commandSuccess =
false
;
302.
}
303.
304.
errorCommand.Clear();
305.
306.
if
(sqlConnection.State == ConnectionState.Open)
307.
sqlConnection.Close();
308.
309.
return
commandSuccess;
310.
}
311.
312.
/// <summary>
313.
/// Execute Query Sql command.
314.
/// </summary>
315.
/// <returns>Query data in DataTable.</returns>
316.
protected
virtual
DataTable ExecuteQuery()
317.
{
318.
DataTable dataTable =
new
DataTable();
319.
320.
try
321.
{
322.
SqlDataAdapter sqlDataAdapter =
new
SqlDataAdapter(sqlCommand);
323.
sqlDataAdapter.Fill(dataTable);
324.
sqlDataAdapter.Dispose();
325.
326.
commandMessage =
"Command is successfully."
;
327.
commandSuccess =
true
;
328.
}
329.
catch
(Exception ex)
330.
{
331.
commandMessage = ErrorMessage(ex.Message);
332.
commandSuccess =
false
;
333.
}
334.
335.
rowsAffected = dataTable.Rows.Count;
336.
337.
return
dataTable;
338.
}
339.
340.
/// <summary>
341.
/// Execute Scalar Sql command.
342.
/// </summary>
343.
/// <returns>Object of value.</returns>
344.
protected
virtual
object
ExecuteScalar()
345.
{
346.
object
Result = 0;
347.
348.
try
349.
{
350.
if
(transaction)
351.
{
352.
Result = sqlCommand.ExecuteScalar();
353.
}
354.
else
355.
{
356.
if
(sqlConnection.State != ConnectionState.Open)
357.
sqlConnection.Open();
358.
359.
Result = sqlCommand.ExecuteScalar();
360.
sqlConnection.Close();
361.
}
362.
363.
commandMessage =
"Command is successfully."
;
364.
commandSuccess =
true
;
365.
}
366.
catch
(Exception ex)
367.
{
368.
commandMessage = ErrorMessage(ex.Message);
369.
commandSuccess =
false
;
370.
if
(transaction) AddErrorCommand(sqlCommandString, ex.Message);
371.
}
372.
373.
return
Result;
374.
}
375.
376.
/// <summary>
377.
/// Execute Non Query Sql command.
378.
/// </summary>
379.
/// <returns>Result of execute command.</returns>
380.
protected
virtual
bool
ExecuteNonQuery()
381.
{
382.
rowsAffected = 0;
383.
384.
try
385.
{
386.
if
(transaction)
387.
{
388.
rowsAffected = sqlCommand.ExecuteNonQuery();
389.
}
390.
else
391.
{
392.
if
(sqlConnection.State != ConnectionState.Open)
393.
sqlConnection.Open();
394.
395.
rowsAffected = sqlCommand.ExecuteNonQuery();
396.
sqlConnection.Close();
397.
}
398.
399.
commandMessage =
"Command is successfully."
;
400.
commandSuccess =
true
;
401.
}
402.
catch
(Exception ex)
403.
{
404.
commandMessage = ErrorMessage(ex.Message);
405.
commandSuccess =
false
;
406.
if
(transaction) AddErrorCommand(sqlCommandString, ex.Message);
407.
}
408.
409.
return
commandSuccess;
410.
}
411.
412.
/// <summary>
413.
/// Build error message.
414.
/// </summary>
415.
/// <param name="Message">Message string.</param>
416.
/// <returns>Error message string.</returns>
417.
protected
virtual
string
ErrorMessage(
string
MessageString)
418.
{
419.
return
"<font color=\"red\">Command error.</font> "
+ MessageString;
420.
}
421.
422.
/// <summary>
423.
/// Add error sql command to string collections.
424.
/// </summary>
425.
/// <param name="commandString">The sql command.</param>
426.
/// <param name="errorMessage">The error message.</param>
427.
protected
virtual
void
AddErrorCommand(
string
commandString,
string
errorMessage)
428.
{
429.
errorCommand.Add(commandString +
" <font color=\"red\">[Error message: "
+ errorMessage +
"]</font>"
);
430.
}
431.
432.
/// <summary>
433.
/// Convert native command to sql command.
434.
/// </summary>
435.
/// <param name="commandString">The native sql command.</param>
436.
/// <returns>The standard sql command.</returns>
437.
protected
virtual
string
ConvertDateCommand(
string
commandString)
438.
{
439.
string
SmallDateTimePattern =
"[sS][mM][aA][lL][lL][dD][aA][tT][eE][tT][iI][mM][eE]\\([@][0-9a-zA-Z\\s]{1,}\\)"
;
440.
Regex SmallDateTimeRgx =
new
Regex(SmallDateTimePattern);
441.
442.
foreach
(Match SmallDateTimeMatchCase
in
SmallDateTimeRgx.Matches(commandString))
443.
{
444.
string
MatchCasePattern =
"^[sS][mM][aA][lL][lL][dD][aA][tT][eE][tT][iI][mM][eE]"
;
445.
Regex MatchCaseRgx =
new
Regex(MatchCasePattern);
446.
Match RemoveMatch = MatchCaseRgx.Match(SmallDateTimeMatchCase.Value);
447.
string
TempMatchCase = SmallDateTimeMatchCase.Value.Replace(RemoveMatch.Value,
""
);
448.
449.
commandString = commandString.Replace(SmallDateTimeMatchCase.Value, TempMatchCase.Replace(
"("
,
"Convert(SmallDateTime, "
).Replace(
")"
,
", 103)"
));
450.
}
451.
452.
string
DateTimePattern =
"[dD][aA][tT][eE][tT][iI][mM][eE]\\([@][0-9a-zA-Z\\s]{1,}\\)"
;
453.
Regex DateTimeRgx =
new
Regex(DateTimePattern);
454.
455.
foreach
(Match DateTimeMatchCase
in
DateTimeRgx.Matches(commandString))
456.
{
457.
string
MatchCasePattern =
"^[dD][aA][tT][eE][tT][iI][mM][eE]"
;
458.
Regex MatchCaseRgx =
new
Regex(MatchCasePattern);
459.
Match RemoveMatch = MatchCaseRgx.Match(DateTimeMatchCase.Value);
460.
string
TempMatchCase = DateTimeMatchCase.Value.Replace(RemoveMatch.Value,
""
);
461.
462.
commandString = commandString.Replace(DateTimeMatchCase.Value, TempMatchCase.Replace(
"("
,
"Convert(DateTime, "
).Replace(
")"
,
", 103)"
));
463.
}
464.
465.
return
commandString;
466.
}
467.
#endregion
468.
}
469.
#endregion
470.
471.
#region ========== Class SqlConvert ==========
472.
/// <summary>
473.
/// Summary description for SqlConvert
474.
/// </summary>
475.
public
sealed
class
SqlConvert
476.
{
477.
/// <summary>
478.
/// Convert to byte[].
479.
/// </summary>
480.
/// <param name="BinaryStream">File upload binary stream.</param>
481.
/// <param name="StreamLength">Lenght of File upload binary stream.</param>
482.
/// <returns>Byte[] of binary stream.</returns>
483.
public
static
byte
[] ToVarBinary(Stream BinaryStream,
int
StreamLength)
484.
{
485.
BinaryReader BinaryRead =
new
BinaryReader(BinaryStream);
486.
byte
[] binaryData = BinaryRead.ReadBytes(StreamLength);
487.
488.
return
binaryData;
489.
}
490.
491.
/// <summary>
492.
/// Convert to DataTime DataType with d/M/yyyy format.
493.
/// </summary>
494.
/// <param name="DateString">DateTime sring.</param>
495.
/// <returns>Datetime Type.</returns>
496.
public
static
DateTime ToDateTime(
string
DateString)
497.
{
498.
499.
500.
501.
502.
503.
return
DateTime.ParseExact(DateString,
"d/M/yyyy"
, CultureInfo.InvariantCulture);
504.
}
505.
506.
/// <summary>
507.
/// Convert to DataTime DataType with user define format.
508.
/// </summary>
509.
/// <param name="DateString">DateTime sring.</param>
510.
/// <param name="DateFormat">DateTime Format</param>
511.
/// <returns>Datetime Type.</returns>
512.
public
static
DateTime ToDateTime(
string
DateString,
string
DateFormat)
513.
{
514.
515.
516.
517.
518.
519.
return
DateTime.ParseExact(DateString, DateFormat, CultureInfo.InvariantCulture);
520.
}
521.
}
522.
#endregion