I've posted a few code snippets and some people noticed that there are references to unresolved methods.
I am using a few Helper Classes .. This post describes my DataHelper class.
namespace FSHelperLib
{
using Microsoft.ApplicationBlocks.Data;
using Microsoft.VisualBasic;
using Microsoft.VisualBasic.CompilerServices;////VB .Net Runtime
using System;
using System.Collections;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Text;
using System.Windows.Forms;
public class DataHelper
{
// Methods
public DataHelper()
{
}
#region "DbNull,Nothing and Empty"
// 'TODO there are too many similar function 'review and re-factor them
//'Generic method to set not NULL values, similar to SQL Coalesce, the same as Coalesce
public static object Nz(object oItemValue, object oDefault)
{
return DataHelper.Coalesce(RuntimeHelpers.GetObjectValue(oItemValue), RuntimeHelpers.GetObjectValue(oDefault));
}
// 'Generic method to set not NULL values, similar to SQL Coalesce,the same as Nz
public static object Coalesce(object oItemValue, object oDefault)
{
if (oItemValue == null)
{
return RuntimeHelpers.GetObjectValue(oDefault);
}
if (Information.IsDBNull(RuntimeHelpers.GetObjectValue(oItemValue)))
{
return RuntimeHelpers.GetObjectValue(oDefault);
}
//'TODO add DateTime = Nothing as in IsDBNullOrEmpty
return RuntimeHelpers.GetObjectValue(oItemValue);
}
// 'Method similar to Nz, but empty strings also replaced with Default
public static object DefaultIfDBNullOrEmpty(object oItemValue, object oDefault)
{
if (DataHelper.IsDBNullOrEmpty(RuntimeHelpers.GetObjectValue(oItemValue)))
{
return RuntimeHelpers.GetObjectValue(oDefault);
}
return RuntimeHelpers.GetObjectValue(oItemValue);
}
// ' returns true if DBNull Or Empty String or nothing
public static bool IsDBNullOrEmpty(object oItemValue)
{
bool bRet = false;
if (oItemValue == null)
{
return true;
}
if (Information.IsDBNull(RuntimeHelpers.GetObjectValue(oItemValue)))
{
return true;
}
if (oItemValue.GetType() == Type.GetType("System.DateTime"))
{
if (ObjectType.ObjTst(oItemValue, null, false) == 0)
{
bRet = true;
}
return bRet;
}
if (StringType.StrCmp(oItemValue.ToString(), "", false) == 0)
{
bRet = true;
}
return bRet;
}
// 'simple function for string 10/8/2004
public static bool IsNullOrEmpty(string oItemValue)
{
bool bRet = ((oItemValue == null)||(oItemValue.Length==0));
return bRet;
}
public static bool IsEmpty(DateTime dt)
{
return (dt==DateTime.MinValue );
}
// 'THe folowing 2 functions were not tested
// 'Public Shared Function SetIfTrue(ByRef LValue As Object, ByVal condition As Boolean, ByVal Value As Object) As Boolean
// ' Dim bRet As Boolean = False
// ' If condition Then
// ' LValue = Value
// ' ' Debug.WriteLine(" SetIfNotEmpty:" & LValue.ToString())
// ' bRet = True
// ' End If
// ' Return bRet
// 'End Function
// ''LValue must be ReferenceType to be return back
// 'Public Shared Function SetIfValueChanged(ByRef LValue As Object, ByVal NewValue As Object) As Boolean
// ' Debug.Assert(LValue.GetType.IsClass())
// ' Dim bRet As Boolean = False
// ' If LValue <> NewValue Then
// ' LValue = NewValue
// ' ' Debug.WriteLine(" SetIfNotEmpty:" & LValue.ToString())
// ' bRet = True
// ' End If
// ' Return bRet
// 'End Function
public static bool SetDBNullIfEmpty(ref object LValue)
{
bool bRet = false;
if (DataHelper.IsDBNullOrEmpty(RuntimeHelpers.GetObjectValue(LValue)))
{
LValue = DBNull.Value;
bRet = true;
}
return bRet;
}
public static string ToString_EmptyIfNull(object Value)
{
if (DataHelper.IsDBNullOrEmpty(RuntimeHelpers.GetObjectValue(Value)))
{
return "";
}
return Value.ToString();
}
public static object DBNullIfEmpty(object Value)
{
//bool bRet = false;
if (DataHelper.IsDBNullOrEmpty(RuntimeHelpers.GetObjectValue(Value)))
{
Value = DBNull.Value;
}
return Value;
}
public static object NothingIfEmpty(object Value)
{
//bool bRet = false;
if (DataHelper.IsDBNullOrEmpty(RuntimeHelpers.GetObjectValue(Value)))
{
Value = null;
}
return Value;
}
public static bool SetIfNotEmpty(ref object LValue, object Value)
{
DebugHelper.TracedLine("not sure that it returns valid ref");
bool bRet = false;
if (!DataHelper.IsDBNullOrEmpty(RuntimeHelpers.GetObjectValue(Value)))
{
LValue = RuntimeHelpers.GetObjectValue(Value);
bRet = true;
}
return bRet;
}
//(Guid)TypeDescriptor.GetConverter(typeof(Guid)).ConvertFromString(sClassId) doesn't convert empty string
public static Guid GetGUIDOrNullIfEmpty(string Value)
{ Guid oRet=new Guid();// default guid struct
if (!DataHelper.IsDBNullOrEmpty(Value))
{
// if (Value is Guid)
// return Value;
// else
{
oRet=new Guid(Value);
}
}
return oRet;
}
public static string StringFromObject(object Value)
{
string sRet=null;
if (Value!=null)
{
//special case for Guid because is is not supported by Microsoft.VisualBasic.CompilerServices.StringType.FromObject
if (Value.GetType()==typeof(Guid))
sRet= Value.ToString();
else
sRet=StringType.FromObject(Value);
}
return sRet;
}
#endregion "DbNull,Nothing and Empty"
#region " SQL String Manipulations "
public static string Quoted(char arg)
{
return DataHelper.Quoted(StringType.FromChar(arg));
}
// 'To use in SQL queries
public static string Quoted(string arg)
{
return ("'" + Strings.Replace(arg, "'", "''", 1, -1, CompareMethod.Binary) + "'");
}
// 'Used in some cases when Quoted is not appropriate
public static string EscapeSQL(string arg)
{
return Strings.Replace(arg, "'", "''", 1, -1, CompareMethod.Binary);
}
// 'Should be called inside Quoted, eg " LIKE " & Quoted(SafeLikeLiteral(sInput) & "%")
public static string SafeLikeLiteral(string inputSQL)
{
// ' Make the following replacements:
// ' [ becomes [[]
// ' % becomes [%]
// ' _ becomes [_]
// ' s = inputSQL.Replace("'", "''")' ' ' becomes ''
string text1 = inputSQL;
text1 = text1.Replace("[", "[[]");
text1 = text1.Replace("%", "[%]");
return text1.Replace("_", "[_]");
}
// 'Sample code
// ' sWhere = sSQLAppendWhereOrAnd(sWhere)
// ' sWhere &= " IdentityKey <> " & ExcludeIdentityKey
public static string sSQLAppendWhereOrAnd(string strWhere)
{
if (Strings.Len(strWhere) == 0)
{
strWhere = " Where ";
return strWhere;
}
strWhere = strWhere + " and ";
return strWhere;
}
// 'Not very relyable, because it can be 'where' in the data, not as keyword
public static string PrefixWhereIfRequired(string strWhere)
{
if ((Strings.Len(strWhere.Trim()) > 0) && (Strings.InStr(strWhere, "Where", CompareMethod.Text) <= 0))
{
strWhere = " Where " + strWhere;
}
return strWhere;
}
public static string SQLAppendAndIfNotEmpty(string strWhere)
{
if (Strings.Len(strWhere) > 0)
strWhere = strWhere + " and ";
return strWhere;
}
///
///
///
///
existing Where string
///
additional "and" condition
///
public static string SQLAppendCondition(string strWhere,string Condition)
{
if (Strings.Len(strWhere) > 0)
{
strWhere = strWhere + " and ";
}
strWhere+=Condition;
return strWhere;
}
// 'corresponds to MS Access AcFindMatch constants acAnywhere ,acEntire and acStart
public enum FindMatchEnum
{
// Fields
Anywhere = 0,//'Any part of Field -like '%x%'
Entire = 1,
Start = 2, //'Start of Field
CommaSeparatedList = 3
}
public static string SQLLikeCriteria(FindMatchEnum matcher, string sFind)
{
return " LIKE " + SQLQuotedLikeValue(matcher,sFind);
}
public static string SQLQuotedLikeValue(FindMatchEnum matcher, string sFind)
{
string sRet="";
// 'Select case for matcher to create something similar to Like '%" & Titlefinder & "%'))
switch (matcher)
{
case FindMatchEnum.Anywhere:
sRet= DataHelper.Quoted("%" + sFind + "%");
break;
case FindMatchEnum.Entire:
sRet= DataHelper.Quoted(sFind);
break;
case FindMatchEnum.Start:
sRet= DataHelper.Quoted(sFind + "%");
break;
}
return sRet;
}
#endregion " SQL String Manipulations "
#region "DataSet and DataTable Manipulation"
// 'TODO See also and probably move to DatasetHelper.cs
//
// 'function replace existing table if exist
// 'Changed ds returns both as function return and as a parameter
public static DataSet DatasetAddTable(DataSet ds, DataTable tblSrc, string sTableName, bool bReplaceIfExist)
{
// 'http://support.microsoft.com/default.aspx?scid=kb%3Ben-us%3B305346. HOW TO: Copy DataRows Between DataTables
// ' Copy the entire DataTable.
DataTable table1 = tblSrc.Copy();
table1.TableName = sTableName;
if (bReplaceIfExist)
{
DataHelper.DatasetRemoveTable(ds, sTableName);
}
ds.Tables.Add(table1);
return ds;
}
//'Remove if exists
public static bool DatasetRemoveTable(DataSet ds, string sTableName)
{
DataTable table1 = ds.Tables[sTableName];
if (!Information.IsNothing(table1))
{
ds.Tables.Remove(table1);
return true;
}
return false;
}
public static DataColumn[] SetTablePrimaryKey(DataTable tbl, string sColumnName)
{
if (Information.IsNothing(tbl))
{
return null;
}
DataColumn[] columnArray1 = new DataColumn[2];
columnArray1[0] = tbl.Columns[sColumnName];
tbl.PrimaryKey = columnArray1;
return columnArray1;
}
//safe rows count
public static int RowsCount(DataTable tbl)
{ int nRet=0;
if (tbl!=null) { nRet=tbl.Rows.Count;}
return nRet;
}
public static bool IsNullOrEmpty(DataTable tbl)
{
return (RowsCount( tbl)==0);
}
#endregion //"DataSet and DataTable Manipulation"
#region "Column Manipulation"
public static string TableColumnToString(DataTable tbl, string sColumnName, string delimeter)
{
StringBuilder builder1 = new StringBuilder();
foreach (DataRow row1 in tbl.Rows )
{
builder1.Append(RuntimeHelpers.GetObjectValue(row1[sColumnName]));
builder1.Append(delimeter);
}
return StringHelper.LeftBeforeLast(builder1.ToString(), delimeter);
}
//Attempt to use CType(DataHelper.TableColumnToArray(ds.Tables(0), "IndexTable"), String()) causes
// InvalidCastException:Specified cast is not valid
//to workaround see TableColumnToStringArray
public static Object[] TableColumnToArray(DataTable tbl, string sColumnName)
{
ArrayList arr= new ArrayList(tbl.Rows.Count);
foreach (DataRow row1 in tbl.Rows )
{
arr.Add(row1[sColumnName]);
}
return arr.ToArray();
}
public static string[] TableColumnToStringArray(DataTable tbl, string sColumnName)
{
ArrayList arr= new ArrayList(tbl.Rows.Count);
foreach (DataRow row1 in tbl.Rows )
{
arr.Add(row1[sColumnName]);
}
return (string [])arr.ToArray(typeof(System.String));
}
// 'After concatenating it closes DataReader
public static string TableColumnToString(IDataReader rdr, string sColumnName, string delimeter)
{
StringBuilder builder1 = new StringBuilder();
try
{
while (rdr.Read())
{
builder1.Append(RuntimeHelpers.GetObjectValue(rdr[sColumnName]));
builder1.Append(delimeter);
}
}
finally
{
if(rdr!=null) rdr.Close();
}
return StringHelper.LeftBeforeLast(builder1.ToString(), delimeter);
}
public static bool TableColumnAddIfNotExists(DataTable tbl, string sColumnName)
{
bool bRet=false;
if (tbl.Columns[sColumnName] == null)
{
tbl.Columns.Add(sColumnName);
bRet=true;
}
return bRet;
}
public static void Table_TrimColumnNames(DataTable tbl)
{
// string text1;
foreach(DataColumn clmn in tbl.Columns)
{
clmn.ColumnName=clmn.ColumnName.Trim();
}
//return text1;
}
public static bool TableColumnAllNulls(DataTable tbl, string sColumnName)
{
bool bRet = true;
foreach (DataRow row1 in tbl.Rows)
{
if (!Information.IsDBNull(RuntimeHelpers.GetObjectValue(row1[sColumnName])))
{
return false;
}
}
return bRet;
}
public static bool TableColumnAtLeastOneNull(DataTable tbl, string sColumnName)
{
foreach(DataRow row in tbl.Rows)
{
if (Information.IsDBNull(row[sColumnName]))
{
return true;
}
}
return false;
}
public static bool TableColumnAllZeroes(DataTable tbl, string sColumnName)
{
bool bRet = true;
foreach (DataRow row1 in tbl.Rows )
{
if (ObjectType.ObjTst(DataHelper.Nz(RuntimeHelpers.GetObjectValue(row1[sColumnName]), 0), 0, false) != 0)
{
return false;
}
}
return bRet;
}
// 'finds the first not empty column and closes the reader
public static string NotEmptyColumnValue(SqlDataReader reader, string sColumnName)
{
string text2 = "";
while (reader.Read())
{
if (Information.IsDBNull(RuntimeHelpers.GetObjectValue(reader[sColumnName])) || (Strings.Len(RuntimeHelpers.GetObjectValue(reader[sColumnName])) <= 0))
{
continue;
}
text2 = StringType.FromObject(reader[sColumnName]);
break;
}
reader.Close();
return text2;
}
// 'Changes value of field, if it is not the same
public static bool SetValueIfChanged(DataRow row, string ColumnName, object NewValue)
{
bool bRet = false;
if (ObjectType.ObjTst(row[ColumnName], NewValue, false) != 0)
{
row[ColumnName] = RuntimeHelpers.GetObjectValue(NewValue);
bRet = true;
}
return bRet;
}
//2/8/2005
public static object DataRowNz(DataRow row, string ColumnName, object defaultValue)
{
return DataRowNz( row, ColumnName, defaultValue, false);
}
//18/8/2005
public static object DataRowNz(DataRow row, string ColumnName, object defaultValue, bool bColumnCanBeMissing)
{
object oRet = defaultValue;
if (!(null==row))
{
if(bColumnCanBeMissing==true)
{
if(row.Table.Columns.Contains(ColumnName)==false)
{
return oRet;
}
}
oRet = Nz(row[ColumnName], defaultValue);
}
return oRet;
}
// NOTE: The following function seems will never work(may be wait for generics or create overloads for all types)
// Caller should use conversion to pass LValue, and it will return value to a boxing object and it will not assign back to actual LValue
// alternative solution that is working (and type-safe)
// m_Page = CType(IIf(DataHelper.Contains(dr, "Id"), dr("ID"), m_Page), String)
// or
// If (DataHelper.Contains(dr, "Id") = True) Then m_Page = CType(dr.Item("ID"), String)
// 'Changes value of field, if it is not the same
// see also SetIfNotEmpty(ref object LValue, object Value)
public static bool AssignValueIfColumnExists(ref object LValue,IDataRecord row, string ColumnName)
{
Debug.Assert(false,"doesn't return back correct data");
bool bRet = false;
if (Contains(row,ColumnName))
{
LValue=row[ColumnName];
bRet =true;
}
return bRet;
}
// //overload -not tested, not working
// public static bool AssignValueIfColumnExists(ref object LValue,DataRow row, string ColumnName)
// {
// Debug.Assert(False,"doesn't return back correct data");
// bool bRet = false;
// if (row.Table.Columns.Contains(ColumnName))
// {
// LValue=row[ColumnName];
// bRet =true;
// }
// return bRet;
// }
// 'not likely to be re-used ,but
public static void CleanStringFields(DataRow row)
{
foreach (DataColumn column1 in row.Table.Columns)
{
if (!Information.IsDBNull(RuntimeHelpers.GetObjectValue(row[column1])) && (column1.DataType == Type.GetType("System.String")))
{
row[column1] = "";
}
}
}
//21/10/2005
public static bool AreAllFieldEmpty(DataRow row)
{
//bool bRet=false;
foreach (DataColumn column1 in row.Table.Columns)
{
if (!IsDBNullOrEmpty(RuntimeHelpers.GetObjectValue(row[column1])))
{
return false;
}
}
return true;
}
public static DataRow GetLastOrNewRow(DataTable tbl, bool bForceNew)
{
if (bForceNew | (tbl.Rows.Count == 0))
{
DataRow row2 = tbl.NewRow();
tbl.Rows.Add(row2); //'will cause errors if Primary key is defined
return row2;
}
return tbl.Rows[tbl.Rows.Count - 1];
}
///
/// The function similar to ColumnsCollection
///
///
///
///
public static bool Contains(IDataRecord row, string FieldName)
{
bool bRet=true;
try
{
row.GetOrdinal(FieldName);
}
catch //(Exception exc)
{
bRet=false;
}
return bRet;
}
//can be used if rows are from different tables, but column name to copy is the same in both tables
public static void CopyField(DataRow SourceRow, DataRow DestRow, string ColumnName)
{
Debug.Assert( SourceRow.Table.Columns.Contains( ColumnName));
Debug.Assert( DestRow.Table.Columns.Contains( ColumnName));
DestRow[ColumnName] = SourceRow[ColumnName];
}
#endregion //"Column Manipulation"
#region "DateTime SQL Formats"
public static DateTime DateAndTime(DateTime dateValue, DateTime timeValue)
{
DateTime time2;
time2 = new DateTime(dateValue.Year, dateValue.Month, dateValue.Day, timeValue.Hour, timeValue.Minute, timeValue.Second);
return time2;
}
public static DateTime DateEndOfDay(DateTime dateValue)
{
return DataHelper.DateAndTime(dateValue, DateType.FromString("23:59"));
}
public static DateTime DateStartOfDay(DateTime dateValue)
{
return DataHelper.DateAndTime(dateValue, DateType.FromString("00:00"));
}
// 'Not used
// 'Public Shared Function TimeAsAccessDate(ByVal Value As Date) As Date
// ' Const DateOrigAccess As Date = #1/1/1900#
// ' If Value < DateOrigAccess Then
// ' Value = DateOrigAccess + " " + Value
// ' End If
// ' Return (Value)
// 'End Function
public static string FormatDateTimeSQL(DateTime Value)
{
return DataHelper.Quoted(Strings.Format(Value, "yyyy-MM-dd HH:mm:ss"));
}
public static string FormatDateTimeSQL(DateTime dateValue, DateTime timeValue)
{
return DataHelper.Quoted(Strings.Format(dateValue, "yyyy-MM-dd ") + Strings.Format(timeValue, "HH:mm:ss"));
}
public static string TimeConvertSQL(DateTime Value)
{
return (" CONVERT(VARCHAR, " + DataHelper.Quoted(Strings.Format(Value, "HH:mm:ss")) + ",108)");
}
public static string DateConvertSQL(DateTime Value)
{
// 'Using Convert is not good because indexes are not used see http://www.databasejournal.com/features/mssql/print.php/10894_2209321_3.
return (" CONVERT(DATETIME, " + DataHelper.DateFormatSQL(Value) + " , 102) ");
}
public static string DateFormatSQL(DateTime Value)
{
return DataHelper.Quoted(Strings.Format(Value, "yyyy-MM-dd"));
}
public static string SQLBetweenDates(string Field ,DateTime FromDate ,DateTime ToDate )
{
string str = "[" + Field + "] " + SQLBetweenDates(FromDate , ToDate);
return str;
}
public static string SQLBetweenDates(DateTime FromDate ,DateTime ToDate )
{
string str = "BETWEEN " + DateConvertSQL(FromDate) + " AND " + FormatDateTimeSQL( DateEndOfDay(ToDate));
return str;
}
public static DateTime YYYYMMDDToDate(long day)
{
DateTime time3;
object obj1 = day.ToString();
time3 = new DateTime(IntegerType.FromString(Strings.Left(StringType.FromObject(obj1), 4)), IntegerType.FromString(Strings.Mid(StringType.FromObject(obj1), 5, 2)), IntegerType.FromString(Strings.Mid(StringType.FromObject(obj1), 7, 2)));
return time3;
}
public static DateTime HHMMSSToTime(long time)
{
DateTime time3;
object obj1 = time.ToString();
time3 = new DateTime(0x6d9, 1, 1, IntegerType.FromString(Strings.Left(StringType.FromObject(obj1), 2)), IntegerType.FromString(Strings.Mid(StringType.FromObject(obj1), 3, 2)), IntegerType.FromString(Strings.Mid(StringType.FromObject(obj1), 5, 2)));
return time3;
}
#endregion //"DateTime SQL Formats"
#region "//"Conversion""
//invalid string will throw FormatException -see Boolean.Parse method
public static bool BoolFromSQLReturn(object oValue)
{
//TODO try BooleanType.FromObject, but unlikely 0 or 1 will be considered
//return "select 1 from.."
//expected to check result "1" or "0" or "true" or "false"
bool bRet=false;
// if ((oValue is int) &&( (int)oValue==1)) bRet=true;
if (Microsoft.VisualBasic.Information.IsNumeric(oValue))
{ double dValue=Convert.ToDouble( oValue);
if (dValue==1) bRet=true;
}
else if (oValue is string)
{
if(DataHelper.IsNullOrEmpty((string)oValue)) bRet=false;
else bRet=Boolean.Parse((string)oValue) ;
}
else if (oValue is bool)
{ bRet=(bool)oValue;
}
return bRet;
}
#endregion //"Conversion"
#region "DataSet schema and defaults"
//' trim the field to fit into schema
public static object TrimFieldToFitIntoColumn(DataTable tableWithSchema, string sFieldName, object oValue)
{
if(tableWithSchema.Columns[sFieldName]==null){ throw new ArgumentNullException("tableWithSchema.Columns[sFieldName]");}
if ((tableWithSchema.Columns[sFieldName].DataType == Type.GetType("System.String")) & (tableWithSchema.Columns[sFieldName].MaxLength < Strings.Len(RuntimeHelpers.GetObjectValue(oValue))))
{
oValue = Strings.Mid(StringType.FromObject(oValue), 1, tableWithSchema.Columns[sFieldName].MaxLength);
}
return oValue;
}
public static object TrimFieldToFitIntoColumn(string connString, string sTableName, string sFieldName, object oValue)
{// 'TODO cache schema may be into XMLSchemaCollection
SqlConnection connection1 = new SqlConnection(connString);
DataSet set1 = new DataSet();
DataHelper.FillSchema(ref set1, sTableName, connection1);
oValue = RuntimeHelpers.GetObjectValue(DataHelper.TrimFieldToFitIntoColumn(set1.Tables[sTableName], sFieldName, RuntimeHelpers.GetObjectValue(oValue)));
return oValue;
}
// 'Default values from SQL Server http://www.dotnet247.com/247reference/msgs/4/24204.aspx
// ' not Retrieved by MS in general case , because default can be function eg GetDate()
// 'but it will work for simple constant case.
// ' tblSchema DataTable should correspond to the dababase table sTableName
public static void LoadTableDefaults(ref DataTable tblSchema, ref string sTableName, SqlConnection conn)
{
IEnumerator enumerator1=null;
SqlParameter[] parameterArray1 = new SqlParameter[1] { new SqlParameter("@table_name", sTableName) } ;
DataSet set1 = SqlHelper.ExecuteDataset(conn, CommandType.StoredProcedure, "sp_columns", parameterArray1);
try
{
enumerator1 = set1.Tables[0].Rows.GetEnumerator();
while (enumerator1.MoveNext())
{
DataRow row1 = (DataRow) enumerator1.Current;
object obj1 = RuntimeHelpers.GetObjectValue(row1["Column_DEF"]);
if (!Information.IsDBNull(RuntimeHelpers.GetObjectValue(obj1)))
{
obj1 = StringHelper.StripBrackets(StringType.FromObject(obj1), "(", ")");
object[] objArray1 = new object[1] { RuntimeHelpers.GetObjectValue(row1["COLUMN_NAME"]) } ;
DataColumn column1 = (DataColumn) LateBinding.LateGet(tblSchema.Columns, null, "Item", objArray1, null, null);
if (column1.DataType == Type.GetType("System.Boolean"))
{
obj1 = BooleanType.FromObject(obj1);
}
else if ((column1.DataType == Type.GetType("System.DateTime")) && !Information.IsDate(RuntimeHelpers.GetObjectValue(obj1)))
{
Trace.WriteLine(ObjectType.StrCatObj(((("LoadTableDefaults Table " + sTableName) + " Column ") + column1.ColumnName) + "Unable to set Default ", obj1));
obj1 = DBNull.Value;
}
column1.DefaultValue = RuntimeHelpers.GetObjectValue(obj1);
}
}
}
finally
{
if (enumerator1 is IDisposable)
{
((IDisposable) enumerator1).Dispose();
}
}
}
public static void FillSchema(ref DataSet ds, string sTableName, SqlConnection conn)
{
string text1 = "Select * from " + sTableName;
SqlCommand command1 = new SqlCommand();
SqlDataAdapter adapter1 = new SqlDataAdapter(text1, conn);
adapter1.FillSchema(ds, SchemaType.Source, sTableName);
}
public static void FillSchemaAndDefaults(ref DataSet ds, string sTableName, SqlConnection conn)
{
DataHelper.FillSchema(ref ds, sTableName, conn);
DataTable table1 = ds.Tables[0];
DataHelper.LoadTableDefaults(ref table1, ref sTableName, conn);
}
#endregion //"DataSet schema and defaults"
#region "Connection string "
public static string ConcatenateConnString(string ServerName, string sConnUser, string sConnPassword, string DatabaseName, string ApplicationName)
{
// strConn = "Server=MICHAELFPC;uid=???;pwd=???;database=FILMSDSQL;connection lifetime=1;Application Name=vLearning;Enlist=false"
string[] textArray1 = new string[10] { "Server=", ServerName, ";uid=", sConnUser, ";pwd=", sConnPassword, ";database=", DatabaseName, ";connection lifetime=1;Application Name=", ApplicationName } ;
return string.Concat(textArray1);
}
public static string DatabaseNameFromConnString(string connString)
{
SqlConnection connection1 = new SqlConnection(connString);
string text2 = connection1.Database;
connection1.Dispose();
return text2;
}
public static string ServerNameFromConnString(string connString)
{
SqlConnection connection1 = new SqlConnection(connString);
string text2 = connection1.DataSource;
connection1.Dispose();
return text2;
}
#endregion //"Connection string "
#region "CurrencyManager WinForms"
//'cm should be passed in format Me.BindingContext(myTable)
public static DataRowView CurrentDataRowView(CurrencyManager cm)
{
BindingManagerBase base1 = cm;// ' Specify the CurrencyManager for the DataTable.
if (base1.Current.GetType() != typeof(DataRowView))
{
return null;
}
return (DataRowView) base1.Current;
}
#endregion //"CurrencyManager WinForms"
}// public class DataHelper
}//namespace FSHelperLib
public static DateTime TimeToDateTime(object time)
{
DateTime dt;// = new DateTime();
if (time is TimeSpan)
{
TimeSpan ts =(TimeSpan) time ;
dt = new DateTime();
dt = dt.Add(ts);
}
else
dt = DateType.FromObject(time);
return dt;
}
public static DateTime TimeOfDay(DateTime dateValue)
{
TimeSpan ts = dateValue.TimeOfDay;
return TimeToDateTime(ts);
}
posted @ Monday, January 09, 2006 6:17 AM