using System; using System.Data; using System.Data.SqlClient; using System.Text; using System.Xml.Linq; namespace Neo.Afx.ComponentModel { /////////////////////////////////////////////////////////////////////// // DO NOT USE Neo.Afx.Core version as it closes connections!!! /////////////////////////////////////////////////////////////////////// /// /// Groups some SQL Server utility methods. /// public static class SqlUtilities { /// /// The CLR connection string: context connection=true /// public const string ClrConnectionString = "context connection=true"; #region FetchDataTable /// /// Executes the given SqlCommand and returns a /// DataTable for the result set returned by the /// SqlCommand. /// /// The result of the command in a DataTable. public static DataTable FetchDataTable(this SqlCommand command) { using(var reader = command.ExecuteReader((CommandBehavior.SchemaOnly & CommandBehavior.KeyInfo))) { var table = new DataTable(); table.Load(reader, LoadOption.OverwriteChanges); return table; } } #endregion #region Replace /// /// Replaces values in the format string with values from the given source. /// /// The format string to be parsed. /// The type of the formatting to be performed. /// The source to be queried for values - must be positioned before call. /// The string with the relevant values replaced. public static string Replace(this string formatString, EntityFormatType formatType, SqlDataReader source) { return ReplaceInternal(formatString, formatType, source.FieldCount, source.GetName, index => source[index].ToStringSafe()); } /// /// Replaces values in the format string with values from the given source. /// /// The format string to be parsed. /// The type of the formatting to be performed. /// The source to be queried for values - must be positioned before call. /// The string with the relevant values replaced. public static string Replace(this string formatString, EntityFormatType formatType, DataRow source) { return ReplaceInternal(formatString, formatType, source.Table.Columns.Count, index => source.Table.Columns[index].ColumnName, index => source[index].ToStringSafe()); } #endregion #region ReplaceInternal static string ReplaceInternal(string formatString, EntityFormatType formatType, int colCount, Func getName, Func getValue) { var result = new StringBuilder(formatString); for(var colIndex = 0; colIndex < colCount; colIndex++) { var name = getName(colIndex); var value = getValue(colIndex); switch(formatType) { case EntityFormatType.Replacement: result.Replace("[[" + name.ToLower() + "]]", value); break; case EntityFormatType.Xml: result.Append(new XElement(name, value)); break; } } return result.ToString(); } #endregion } }