andrew4582

DataSchemaHelper

Oct 7th, 2014
324
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.53 KB | None | 0 0
  1. using System;
  2. using System.Data;
  3. using System.Globalization;
  4. using System.Text;
  5.  
  6. namespace Common.Extensions
  7. {
  8.     public static class DataSchemaHelper
  9.     {
  10.         /// <summary>
  11.         /// Gets the DataReader's schema table fields
  12.         /// </summary>
  13.         public static string WriteSchemaFields(this IDataReader reader)
  14.         {
  15.             var dt = reader.GetSchemaTable();
  16.             return dt.WriteSchemaFields();
  17.         }
  18.  
  19.         /// <summary>
  20.         /// Gets the DataTable's schema table fields from the DataReader.GetSchemaTable() method
  21.         /// </summary>
  22.         public static string WriteSchemaFields(this DataTable dt)
  23.         {
  24.             if (!dt.Columns.Contains("ColumnName") || !dt.Columns.Contains("DataType"))
  25.                 throw new ArgumentOutOfRangeException("The DataTable must contain the 'ColumnName' and 'DataType' columns. Use the DataReader.GetSchemaTable() method");
  26.  
  27.             StringBuilder sb = new StringBuilder();
  28.             for (int i = 0; i < dt.Rows.Count; i++)
  29.                 //sb.AppendFormat("{0}[{1}]({2})", dt.Rows[i]["ColumnName"].ToString(), dt.Rows[i]["DataType"].ToString(), dt.Rows[i]["ColumnSize"].ToString())
  30.                 sb.AppendFormat("{0} {1} {2}",
  31.                                 dt.Rows[i]["DataType"].ToString().Replace("System.", "").ToLower(),
  32.                                 dt.Rows[i]["ColumnName"].ToString().FormatPropertyName(),
  33.                                 dt.Rows[i]["ColumnName"].ToString())
  34.                 .AppendLine();
  35.  
  36.             string output = sb.ToString();
  37.             return output;
  38.         }
  39.  
  40.         static string FormatPropertyName(this string text)
  41.         {
  42.             TextInfo myTI = new CultureInfo("en-US", false).TextInfo;
  43.             return myTI.ToTitleCase(text.ToLower()).Replace("_", "");
  44.         }
  45.     }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment