New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fully implemented case where Type of SQLCommand is Text #3

Open
wants to merge 2 commits into
base: master
from
Jump to file or symbol
Failed to load files and symbols.
+132 −106
Diff settings

Always

Just for now

Next

Fully implemented case where Type of SQLCommand is Text

apart from the implementation for Text type of SQLCommand, also refactored code for readability
  • Loading branch information...
birbilis committed Sep 19, 2018
commit 527d696dc6055c5bcf858b9700b83dc863f04896
@@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
namespace CommandAsSql
{
@@ -10,16 +11,65 @@ namespace CommandAsSql
/// </summary>
public static class ExtensionMethods
{
#region Boolean Helpers
public static Boolean ToBooleanOrDefault(this string s, bool defaultValue)
{
return ToBooleanOrDefault((object)s, defaultValue);
}
public static Boolean ToBooleanOrDefault(this object o, bool defaultValue)
{
bool result = defaultValue;
if (o != null)
try
{
switch (o.ToString().ToLower())
{
case "yes":
case "true":
case "ok":
case "y":
result = true;
break;
case "no":
case "false":
case "n":
result = false;
break;
default:
result = bool.Parse(o.ToString());
break;
}
}
catch
{
}
return result;
}
#endregion
#region SQL Helpers
/// <summary>
/// Turns a parameter object to string
/// </summary>
/// <param name="sp">SqlParameter</param>
/// <param name="param">SqlParameter</param>
/// <returns></returns>
public static string ParameterValueForSQL(this SqlParameter sp)
public static String ParameterValueForSQL(this SqlParameter param)
{
string retval = string.Empty;
object paramValue = param.Value; //assuming param isn't null
if (paramValue == null)
return "NULL";
switch (sp.SqlDbType)
switch (param.SqlDbType)
{
case SqlDbType.Char:
case SqlDbType.NChar:
@@ -33,21 +83,21 @@ public static string ParameterValueForSQL(this SqlParameter sp)
case SqlDbType.DateTime:
case SqlDbType.DateTime2:
case SqlDbType.DateTimeOffset:
retval = $"'{sp.Value.ToString().Replace("'", "''")}'";
break;
//return "'" + paramValue.ToString().Replace("'", "''") + "'";
return $"'{paramValue.ToString().Replace("'", "''")}'"; //C# 6 syntax
case SqlDbType.Bit:
retval = (sp.Value.ToBooleanOrDefault(false)) ? "1" : "0";
break;
return (paramValue.ToBooleanOrDefault(false)) ? "1" : "0";
case SqlDbType.Structured:
var sb = new System.Text.StringBuilder();
var dt = (DataTable)sp.Value;
var dt = (DataTable)paramValue;
sb.Append("declare ").Append(sp.ParameterName).Append(" ").AppendLine(sp.TypeName);
sb.Append("declare ").Append(param.ParameterName).Append(" ").AppendLine(param.TypeName);
foreach (DataRow dr in dt.Rows)
{
sb.Append("insert ").Append(sp.ParameterName).Append(" values (");
{
sb.Append("insert ").Append(param.ParameterName).Append(" values (");
for (int colIndex = 0; colIndex < dt.Columns.Count; colIndex++)
{
@@ -56,12 +106,15 @@ public static string ParameterValueForSQL(this SqlParameter sp)
case TypeCode.Boolean:
sb.Append(Convert.ToInt32(dr[colIndex]));
break;
case TypeCode.String:
sb.Append("'").Append(dr[colIndex]).Append("'");
break;
case TypeCode.DateTime:
sb.Append("'").Append(Convert.ToDateTime(dr[colIndex]).ToString("yyyy-MM-dd HH:mm")).Append("'");
break;
default:
sb.Append(dr[colIndex]); break;
}
@@ -73,139 +126,112 @@ public static string ParameterValueForSQL(this SqlParameter sp)
sb.AppendLine(")");
}
retval = sb.ToString();
break;
return sb.ToString();
case SqlDbType.Decimal:
case SqlDbType.Float:
retval = ((double)sp.Value).ToString(System.Globalization.CultureInfo.InvariantCulture).Replace("'", "''");
break;
return ((double)paramValue).ToString(System.Globalization.CultureInfo.InvariantCulture).Replace("'", "''");
default:
retval = sp.Value.ToString().Replace("'", "''");
break;
return paramValue.ToString().Replace("'", "''");
}
return retval;
}
private static List<SqlParameter> GetStructured(this SqlParameterCollection c)
private static List<SqlParameter> GetStructured(this SqlParameterCollection paramCollection)
{
var filtered = new List<SqlParameter>();
foreach (SqlParameter p in c)
{
List<SqlParameter> filtered = new List<SqlParameter>();
foreach (SqlParameter p in paramCollection)
if (p.SqlDbType == SqlDbType.Structured)
filtered.Add(p);
}
return filtered;
}
#endregion
/// <summary>
/// This method fills all parameters of the sqlcommand and displays it as a string which can be copy pasted in your DB management tool for debug purposes.
/// </summary>
/// <param name="sc">The SqlCommand you want parsed as a full SQL string</param>
/// <param name="command">The SqlCommand you want parsed as a full SQL string</param>
/// <returns></returns>
public static string CommandAsSql(this SqlCommand sc)
public static string CommandAsSql(this SqlCommand command)
{
var sql = new System.Text.StringBuilder();
bool FirstParam = true;
sql.Append("use ").Append(sc.Connection.Database).AppendLine(";");
sql.Append("use ").Append(command.Connection.Database).AppendLine(";");
foreach (SqlParameter strucParam in sc.Parameters.GetStructured())
sql.AppendLine(ParameterValueForSQL(strucParam));
foreach (SqlParameter strucParam in command.Parameters.GetStructured())
sql.AppendLine(strucParam.ParameterValueForSQL());
switch (sc.CommandType)
switch (command.CommandType)
{
case CommandType.StoredProcedure:
sql.AppendLine("declare @return_value int;");
foreach (SqlParameter sp in sc.Parameters)
{
if ((sp.Direction == ParameterDirection.InputOutput) || (sp.Direction == ParameterDirection.Output))
{
sql.Append("declare ").Append(sp.ParameterName).Append("\t").Append(sp.SqlDbType.ToString()).Append("\t= ");
sql.Append((sp.Direction == ParameterDirection.Output) ? "null" : sp.ParameterValueForSQL()).AppendLine(";");
}
}
sql.Append("exec [").Append(sc.CommandText).AppendLine("]");
foreach (SqlParameter sp in sc.Parameters)
{
if (sp.Direction != ParameterDirection.ReturnValue)
{
sql.Append((FirstParam) ? "\t" : "\t, ");
if (FirstParam) FirstParam = false;
if (sp.Direction == ParameterDirection.Input)
{
if (sp.SqlDbType != SqlDbType.Structured)
sql.Append(sp.ParameterName).Append(" = ").AppendLine(sp.ParameterValueForSQL());
else
sql.Append(sp.ParameterName).Append(" = ").AppendLine(sp.ParameterName);
}
else
{
sql.Append(sp.ParameterName).Append(" = ").Append(sp.ParameterName).AppendLine(" output");
}
}
}
sql.AppendLine(";");
sql.AppendLine("select 'Return Value' = convert(varchar, @return_value);");
foreach (SqlParameter sp in sc.Parameters)
{
if ((sp.Direction == ParameterDirection.InputOutput) || (sp.Direction == ParameterDirection.Output))
{
sql.Append("select '").Append(sp.ParameterName).Append("' = convert(varchar, ").Append(sp.ParameterName).AppendLine(");");
}
}
case CommandType.Text: //checking 1st, since if we use Text SQL Commands we'll probably be logging more of them that if we had them grouped in Stored Procedures
command.CommandAsSql_Text(sql);
break;
case CommandType.Text:
sql.AppendLine(sc.CommandText);
case CommandType.StoredProcedure:
command.CommandAsSql_StoredProcedure(sql);
break;
}
return sql.ToString();
}
public static bool ToBooleanOrDefault(this string s, bool Default)
private static void CommandAsSql_Text(this SqlCommand command, System.Text.StringBuilder sql)
{
return ToBooleanOrDefault((object)s, Default);
string query = command.CommandText;
foreach (SqlParameter p in command.Parameters)
query = Regex.Replace(query, "\\B" + p.ParameterName + "\\b", p.ParameterValueForSQL()); //the first one is \B, the 2nd one is \b, since ParameterName starts with @ which is a non-word character in RegEx (see https://stackoverflow.com/a/2544661)
sql.AppendLine(query);
}
public static bool ToBooleanOrDefault(this object o, bool Default)
private static void CommandAsSql_StoredProcedure(this SqlCommand command, System.Text.StringBuilder sql)
{
bool ReturnVal = Default;
try
sql.AppendLine("declare @return_value int;");
foreach (SqlParameter sp in command.Parameters)
{
if (o != null)
if ((sp.Direction == ParameterDirection.InputOutput) || (sp.Direction == ParameterDirection.Output))
{
switch (o.ToString().ToLower())
{
case "yes":
case "true":
case "ok":
case "y":
ReturnVal = true;
break;
case "no":
case "false":
case "n":
ReturnVal = false;
break;
default:
ReturnVal = bool.Parse(o.ToString());
break;
}
sql.Append("declare ").Append(sp.ParameterName).Append("\t").Append(sp.SqlDbType.ToString()).Append("\t= ");
sql.Append((sp.Direction == ParameterDirection.Output) ? "null" : sp.ParameterValueForSQL()).AppendLine(";");
}
}
catch
sql.Append("exec [").Append(command.CommandText).AppendLine("]");
bool FirstParam = true;
foreach (SqlParameter param in command.Parameters)
{
if (param.Direction != ParameterDirection.ReturnValue)
{
sql.Append((FirstParam) ? "\t" : "\t, ");
if (FirstParam)
FirstParam = false;
if (param.Direction == ParameterDirection.Input)
if (param.SqlDbType != SqlDbType.Structured)
sql.Append(param.ParameterName).Append(" = ").AppendLine(param.ParameterValueForSQL());
else
sql.Append(param.ParameterName).Append(" = ").AppendLine(param.ParameterName);
else
sql.Append(param.ParameterName).Append(" = ").Append(param.ParameterName).AppendLine(" output");
}
}
sql.AppendLine(";");
sql.AppendLine("select 'Return Value' = convert(varchar, @return_value);");
foreach (SqlParameter sp in command.Parameters)
{
if ((sp.Direction == ParameterDirection.InputOutput) || (sp.Direction == ParameterDirection.Output))
sql.Append("select '").Append(sp.ParameterName).Append("' = convert(varchar, ").Append(sp.ParameterName).AppendLine(");");
}
return ReturnVal;
}
}
}
ProTip! Use n and p to navigate between commits in a pull request.