Monday, May 26, 2008

C_Sharp edition StringList Class

Delphi有一个常用的类StringList, 它有一个特点是你可以一行一行加String, 如果你所加的每行String都是Name=Value格式的,它会帮你提取出Name列表和Value列表, 这个类我在用Delphi时候, 常使用它. 下面是C#版的StringList类.



namespace LiuHarry.Utils.Foundation
{
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;

public class DelphiStrList
{
private List<string> M_Items = new List<string>();
private List<string> M_Keys = new List<string>();
private string M_KeyValueEqualmark = "=";
private List<string> M_Values = new List<string>();

public virtual void Add(string item)
{
string str;
string str2;
this.M_Items.Add(item);
DivideKeyValue(item, this.M_KeyValueEqualmark, out str2, out str);
this.M_Keys.Add(str2);
this.M_Values.Add(str);
}

public virtual void Clear()
{
this.M_Items.Clear();
this.M_Keys.Clear();
this.M_Values.Clear();
}

protected void DevideKeyValuesByItems()
{
this.M_Keys.Clear();
this.M_Values.Clear();
foreach (string str3 in this.M_Items)
{
string str;
string str2;
DivideKeyValue(str3, this.M_KeyValueEqualmark, out str2, out str);
this.M_Keys.Add(str2);
this.M_Values.Add(str);
}
}

public static void DivideKeyValue(string entireStr, string keyValueEqualmark, out string keyStr, out string valueStr)
{
int index = entireStr.IndexOf(keyValueEqualmark);
if (index > 0)
{
keyStr = entireStr.Substring(0, index);
if (index < (entireStr.Length - 1))
{
valueStr = entireStr.Substring(index + 1);
}
else
{
valueStr = "";
}
}
else
{
keyStr = entireStr;
valueStr = "";
}
}

public virtual int IndexOf(string item)
{
return this.M_Items.IndexOf(item);
}

public virtual void Insert(int index, string item)
{
string str;
string str2;
this.M_Items.Insert(index, item);
DivideKeyValue(item, this.M_KeyValueEqualmark, out str2, out str);
this.M_Keys.Insert(index, str2);
this.M_Values.Insert(index, str);
}

public string MakeItemsToText(string ItemSeperator)
{
return this.MakeStrlistToText(this.M_Items, ItemSeperator);
}

public string MakeKeyItemsToText(string ItemSeperator)
{
return this.MakeStrlistToText(this.M_Keys, ItemSeperator);
}

private string MakeStrlistToText(List<string> items, string ItemSeperator)
{
StringBuilder builder = new StringBuilder();
foreach (string str in items)
{
builder.Append(str);
builder.Append(ItemSeperator);
}
return builder.ToString();
}

public string MakeValueItemsToText(string ItemSeperator)
{
return this.MakeStrlistToText(this.M_Keys, ItemSeperator);
}

public virtual bool Remove(string item)
{
int index = this.IndexOf(item);
if (index >= 0)
{
this.M_Keys.RemoveAt(index);
this.M_Values.RemoveAt(index);
}
return this.M_Items.Remove(item);
}

public virtual void RemoveAt(int index)
{
this.M_Items.RemoveAt(index);
this.M_Keys.RemoveAt(index);
this.M_Values.RemoveAt(index);
}

public virtual void Sort()
{
this.M_Items.Sort();
this.DevideKeyValuesByItems();
}

public int Count
{
get
{
return this.M_Items.Count;
}
}

public List<string> Items
{
get
{
return this.M_Items;
}
}

public List<string> Keys
{
get
{
return this.M_Keys;
}
}

public string KeyValueEqualmark
{
get
{
return this.M_KeyValueEqualmark;
}
set
{
this.M_KeyValueEqualmark = value;
}
}

public List<string> Values
{
get
{
return this.M_Values;
}
}
}
}

How to hide or show TabPage of TabControl

C# 的TabControl功能严重不足, 尤其是你用它来制作Wizard界面时候, 下面代码会有所帮助的.


namespace LiuHarry.Utils.Components
{
using System;
using System.Windows.Forms;

public class TabControlHelper
{
private TabControl m_tabControl;

public TabControlHelper(TabControl tabCtrl)
{
this.m_tabControl = tabCtrl;
}

public void HideTabPage(TabPage tp)
{
if (this.m_tabControl.TabPages.Contains(tp))
{
this.m_tabControl.TabPages.Remove(tp);
}
}

private void InsertTabPage(TabPage tabpage, int index)
{
if ((index < 0) || (index > this.m_tabControl.TabCount))
{
throw new ArgumentException("Index out of Range.");
}
this.m_tabControl.TabPages.Add(tabpage);
if (index < (this.m_tabControl.TabCount - 1))
{
do
{
this.SwapTabPages(tabpage, this.m_tabControl.TabPages[this.m_tabControl.TabPages.IndexOf(tabpage) - 1]);
}
while (this.m_tabControl.TabPages.IndexOf(tabpage) != index);
}
this.m_tabControl.SelectedTab = tabpage;
}

public void ShowTabPage(TabPage tp)
{
this.ShowTabPage(tp, this.m_tabControl.TabPages.Count);
}

public void ShowTabPage(TabPage tp, int index)
{
if (!this.m_tabControl.TabPages.Contains(tp))
{
this.InsertTabPage(tp, index);
}
}

private void SwapTabPages(TabPage tp1, TabPage tp2)
{
if (!(this.m_tabControl.TabPages.Contains(tp1) && this.m_tabControl.TabPages.Contains(tp2)))
{
throw new ArgumentException("TabPages must be in the TabControls TabPageCollection.");
}
int index = this.m_tabControl.TabPages.IndexOf(tp1);
int num2 = this.m_tabControl.TabPages.IndexOf(tp2);
this.m_tabControl.TabPages[index] = tp2;
this.m_tabControl.TabPages[num2] = tp1;
this.m_tabControl.SelectedIndex = this.m_tabControl.SelectedIndex;
string text = tp1.Text;
string str2 = tp2.Text;
tp1.Text = str2;
tp2.Text = text;
}
}
}

DataGridViewHelper class

DataGridView这个控件在开发中经常会被用到, C#的组件总觉得不如Delphi组件那么容易使用, 怎样在Grid上选择一个Row, 怎样选择一个Cell, 我就被block了好久. 下面是代码:

namespace LiuHarry.Utils.Components
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;

public class DataGridViewHelper
{
private DataGridView m_DataGridView;
private SortedList<string, string> m_MapListFieldColumn = new SortedList<string, string>();
private DataView m_ShowedDataViewInGrid;

public DataGridViewHelper(DataGridView dataGridView, DataView showedDataViewInGrid)
{
this.m_DataGridView = dataGridView;
this.m_ShowedDataViewInGrid = showedDataViewInGrid;
this.InitFieldColumnMapList();
}

private string _GetGridViewColumnName(string dataFieldName)
{
for (int i = 0; i < this.m_DataGridView.Columns.Count; i++)
{
if (this.m_DataGridView.Columns[i].DataPropertyName == dataFieldName)
{
return this.m_DataGridView.Columns[i].Name;
}
}
return "";
}

private void InitFieldColumnMapList()
{
this.m_MapListFieldColumn.Clear();
for (int i = 0; i < this.m_ShowedDataViewInGrid.Table.Columns.Count; i++)
{
string columnName = this.m_ShowedDataViewInGrid.Table.Columns[i].ColumnName;
string str2 = this._GetGridViewColumnName(columnName);
this.m_MapListFieldColumn.Add(columnName, str2);
}
}

public string QuickFindGridViewColumnName(string dataFieldName)
{
int num = this.m_MapListFieldColumn.IndexOfKey(dataFieldName);
if (num < 0)
{
throw new Exception("There no a column in DataGridView corresponding DataFieldName=" + dataFieldName);
}
return this.m_MapListFieldColumn.Values[num];
}

public void SelectAndScrollToCell(string fieldName, object fieldValue)
{
this.m_DataGridView.ClearSelection();
if ((fieldName != null) && (fieldValue != null))
{
string str = this.QuickFindGridViewColumnName(fieldName);
foreach (DataGridViewRow row in (IEnumerable) this.m_DataGridView.Rows)
{
if (object.Equals(row.Cells[str].Value, fieldValue))
{
this.m_DataGridView.CurrentCell = row.Cells[str];
this.m_DataGridView.CurrentCell.Selected = true;
break;
}
}
}
}

public void SelectRow(object valueOfSortedField)
{
DataView showedDataViewInGrid = this.m_ShowedDataViewInGrid;
this.m_DataGridView.ClearSelection();
if ((showedDataViewInGrid != null) && (valueOfSortedField != null))
{
int num = showedDataViewInGrid.Find(valueOfSortedField);
if (num >= 0)
{
this.m_DataGridView.Rows[num].Selected = true;
}
}
}

public SortedList<string, string> MapListFieldColumn
{
get
{
return this.m_MapListFieldColumn;
}
}
}
}

SQL Execute Trace Helper Class

http://focuswindows.blogspot.com/2008/01/sql-executing-monitor-code.html
该版本可能不是最新的, 最新的代码应该是下面:



namespace LiuHarry.Utils.DB
{
using LiuHarry.Utils.Foundation;
using System;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Reflection;

internal class SqlExecuteTracer : IDisposable
{
private bool disposed = false;
private string m_ErrorLogFile;
private readonly string m_ErrorLogFileSuffix = "SqlError.txt";
private bool m_LogSqlExecute = false;
private string m_SqlLogFile;
private readonly string m_SqlLogFileSuffix = "SqlLog.txt";
private TextWriterTraceListener m_SqlLogListener;

public SqlExecuteTracer()
{
string assemblyFileWithoutExt = this.GetAssemblyFileWithoutExt();
this.m_ErrorLogFile = assemblyFileWithoutExt + "_" + this.m_ErrorLogFileSuffix;
this.m_SqlLogFile = assemblyFileWithoutExt + "_" + this.m_SqlLogFileSuffix;
}

public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}

private void Dispose(bool disposing)
{
if (!this.disposed && this.m_LogSqlExecute)
{
this.m_SqlLogListener.Close();
}
this.disposed = true;
}

private string GetAssemblyFileWithoutExt()
{
string location = Assembly.GetExecutingAssembly().Location;
return (Path.GetDirectoryName(location) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(location));
}

private string GetSqlFromCommand(IDbCommand cmd)
{
string commandText = cmd.CommandText;
if (cmd.Parameters.Count <= 0)
{
return commandText;
}
DelphiStrList list = new DelphiStrList();
foreach (IDbDataParameter parameter in cmd.Parameters)
{
if (parameter.Value != null)
{
list.Add(parameter.ParameterName + "=" + parameter.Value.ToString());
}
else
{
list.Add(parameter.ParameterName + "=NULL");
}
}
return (commandText + Environment.NewLine + list.MakeItemsToText(Environment.NewLine));
}

public void TraceErrorSqlToLog(IDbCommand cmd, string ErrorMessage)
{
using (TraceListener listener = new TextWriterTraceListener(this.m_ErrorLogFile))
{
string sqlFromCommand = this.GetSqlFromCommand(cmd);
this.TraceSqlToLogListener(sqlFromCommand, ErrorMessage, listener);
listener.Close();
}
}

public void TraceErrorSqlToLog(string sql, string ErrorMessage)
{
using (TraceListener listener = new TextWriterTraceListener(this.m_ErrorLogFile))
{
this.TraceSqlToLogListener(sql, ErrorMessage, listener);
listener.Close();
}
}

public void TraceSqlToLog(IDbCommand cmd)
{
if (this.m_LogSqlExecute)
{
string sqlFromCommand = this.GetSqlFromCommand(cmd);
this.TraceSqlToLogListener(sqlFromCommand, null, this.m_SqlLogListener);
}
}

public void TraceSqlToLog(string sql)
{
if (this.m_LogSqlExecute)
{
this.TraceSqlToLogListener(sql, null, this.m_SqlLogListener);
}
}

private void TraceSqlToLogListener(string sql, string ErrorInfo, TraceListener listener)
{
listener.WriteLine("===================================");
listener.WriteLine(DateTime.Now.ToString());
if (!string.IsNullOrEmpty(ErrorInfo))
{
listener.WriteLine("Error Info:");
listener.WriteLine(ErrorInfo);
listener.WriteLine("SQL:");
}
listener.WriteLine(sql);
listener.WriteLine("===================================");
listener.WriteLine("");
listener.Flush();
}

public bool LogSqlExecute
{
get
{
return this.m_LogSqlExecute;
}
set
{
this.m_LogSqlExecute = value;
if (this.m_LogSqlExecute && (this.m_SqlLogListener == null))
{
this.m_SqlLogListener = new TextWriterTraceListener(this.m_SqlLogFile);
}
}
}
}
}

SQLite Dataset Helper Class



namespace LiuHarry.Utils.DB
{
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.Runtime.InteropServices;
using System.Text;

public class SqliteDataSetHelper : IDisposable
{
private readonly string DELETED_FLAG;
private bool disposed;
private readonly string INSERTED_FLAG;
private string m_ConnectionString;
private bool m_LogSqlExecute;
private bool m_SelfBuildConnection;
private SQLiteConnection m_SqlConn;
private SqlExecuteTracer m_SqlExecuteTracer;
private readonly string MODIFIED_FLAG;
private readonly string PARAMETER_NAME_PREFIX;
private readonly string PARAMETER_PREFIX;

public SqliteDataSetHelper()
{
this.m_LogSqlExecute = false;
this.m_SelfBuildConnection = true;
this.DELETED_FLAG = "DELETED_FLAG";
this.INSERTED_FLAG = "INSERTED_FLAG";
this.MODIFIED_FLAG = "MODIFIED_FLAG";
this.PARAMETER_PREFIX = "@";
this.PARAMETER_NAME_PREFIX = "@";
this.disposed = false;
this.m_SqlExecuteTracer = new SqlExecuteTracer();
}

public SqliteDataSetHelper(SQLiteConnection conn) : this()
{
if (conn != null)
{
this.m_SelfBuildConnection = false;
this.m_SqlConn = conn;
}
}

public SqliteDataSetHelper(string connectionString) : this()
{
this.m_ConnectionString = connectionString;
}

private void ActivateConnection()
{
if (this.m_SqlConn == null)
{
this.m_SqlConn = new SQLiteConnection(this.m_ConnectionString);
this.m_SelfBuildConnection = true;
}
}

public void DeleteRows(List<DataRow> listRows, string tableName, string keyFieldName)
{
foreach (DataRow row in listRows)
{
this.SetToDeleteState(row);
this.InnerDeleteRow(row, tableName, keyFieldName);
}
}

public void DeleteRows(List<long> listRowKeyFieldValue, string tableName, string keyFieldName)
{
foreach (int num in listRowKeyFieldValue)
{
this.InnerDeleteRowByKeyField(num, tableName, keyFieldName, typeof(long));
}
}

public void DeleteRows(List<string> listRowKeyFieldValue, string tableName, string keyFieldName)
{
foreach (string str in listRowKeyFieldValue)
{
this.InnerDeleteRowByKeyField(str, tableName, keyFieldName, typeof(string));
}
}

public void DeleteRows(DataRow row, string tableName, string keyFieldName)
{
this.SetToDeleteState(row);
this.InnerDeleteRow(row, tableName, keyFieldName);
}

public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}

private void Dispose(bool disposing)
{
if (!this.disposed)
{
this.TryCloseConnection();
}
this.disposed = true;
}

public int ExecCommand(SQLiteCommand sqlcom)
{
int num2;
this.ActivateConnection();
sqlcom.Connection = this.m_SqlConn;
try
{
this.TryOpenConnection();
this.m_SqlExecuteTracer.TraceSqlToLog(sqlcom);
num2 = sqlcom.ExecuteNonQuery();
}
catch (Exception exception)
{
this.m_SqlExecuteTracer.TraceErrorSqlToLog(sqlcom, exception.Message);
throw exception;
}
finally
{
this.TryCloseConnection();
}
return num2;
}

public int ExecCommand(string sql)
{
if (sql.EndsWith(","))
{
sql = sql.Substring(0, sql.Length - 1);
}
SQLiteCommand sqlcom = new SQLiteCommand(sql);
return this.ExecCommand(sqlcom);
}

public SQLiteDataReader ExecDataReader(SQLiteCommand sqlcom)
{
SQLiteDataReader reader;
this.ActivateConnection();
sqlcom.Connection = this.m_SqlConn;
try
{
this.TryOpenConnection();
this.m_SqlExecuteTracer.TraceSqlToLog(sqlcom);
reader = sqlcom.ExecuteReader();
}
catch (Exception exception)
{
this.m_SqlExecuteTracer.TraceErrorSqlToLog(sqlcom, exception.Message);
throw exception;
}
finally
{
this.TryCloseConnection();
}
return reader;
}

public SQLiteDataReader ExecDataReader(string sqlSelect)
{
if (sqlSelect.EndsWith(","))
{
sqlSelect = sqlSelect.Substring(0, sqlSelect.Length - 1);
}
SQLiteCommand sqlcom = new SQLiteCommand(sqlSelect);
return this.ExecDataReader(sqlcom);
}

public DataTable ExecDataTable(SQLiteCommand sqlcom)
{
DataTable table2;
DataTable dataTable = new DataTable();
SQLiteDataAdapter adapter = new SQLiteDataAdapter(sqlcom);
this.ActivateConnection();
sqlcom.Connection = this.m_SqlConn;
try
{
this.TryOpenConnection();
this.m_SqlExecuteTracer.TraceSqlToLog(sqlcom);
adapter.Fill(dataTable);
table2 = dataTable;
}
catch (Exception exception)
{
this.m_SqlExecuteTracer.TraceErrorSqlToLog(sqlcom, exception.Message);
throw exception;
}
finally
{
this.TryCloseConnection();
}
return table2;
}

public DataTable ExecDataTable(string sqlSelect)
{
if (sqlSelect.EndsWith(","))
{
sqlSelect = sqlSelect.Substring(0, sqlSelect.Length - 1);
}
SQLiteCommand sqlcom = new SQLiteCommand(sqlSelect);
return this.ExecDataTable(sqlcom);
}

public object ExecScalar(SQLiteCommand sqlcom)
{
object obj2;
this.ActivateConnection();
sqlcom.Connection = this.m_SqlConn;
try
{
this.TryOpenConnection();
this.m_SqlExecuteTracer.TraceSqlToLog(sqlcom);
obj2 = sqlcom.ExecuteScalar();
}
catch (Exception exception)
{
this.m_SqlExecuteTracer.TraceErrorSqlToLog(sqlcom, exception.Message);
throw exception;
}
finally
{
this.TryCloseConnection();
}
return obj2;
}

public object ExecScalar(string sqlSelect)
{
if (sqlSelect.EndsWith(","))
{
sqlSelect = sqlSelect.Substring(0, sqlSelect.Length - 1);
}
SQLiteCommand sqlcom = new SQLiteCommand(sqlSelect);
return this.ExecScalar(sqlcom);
}

~SqliteDataSetHelper()
{
this.Dispose(false);
}

public DateTime GetDbTime()
{
string commandText = "select datetime('NOW') ";
SQLiteCommand sqlcom = new SQLiteCommand(commandText);
return (DateTime) this.ExecScalar(sqlcom);
}

private DbType GetDbType(Type type)
{
DbType guid = DbType.String;
if (type.Equals(typeof(int)) || type.IsEnum)
{
return DbType.Int32;
}
if (type.Equals(typeof(long)))
{
return DbType.Int32;
}
if (type.Equals(typeof(double)) || type.Equals(typeof(double)))
{
return DbType.Decimal;
}
if (type.Equals(typeof(DateTime)))
{
return DbType.DateTime;
}
if (type.Equals(typeof(bool)))
{
return DbType.Boolean;
}
if (type.Equals(typeof(string)))
{
return DbType.String;
}
if (type.Equals(typeof(decimal)))
{
return DbType.Decimal;
}
if (type.Equals(typeof(byte[])))
{
return DbType.Binary;
}
if (type.Equals(typeof(Guid)))
{
guid = DbType.Guid;
}
return guid;
}

public long GetMaxID(string primaryKeyField, string tableName)
{
SQLiteCommand sqlcom = new SQLiteCommand("Select Max(" + primaryKeyField + ") from " + tableName);
return (long) this.ExecScalar(sqlcom);
}

private void InnerDeleteRow(DataRow dr, string TableName, string keyFieldName)
{
string format = "Delete from {0} where {1} =" + this.PARAMETER_PREFIX + "{1}";
DataTable table = dr.Table;
SQLiteCommand sqlcom = new SQLiteCommand(string.Format(format, TableName, keyFieldName));
IDataParameter parameter = new SQLiteParameter();
parameter.ParameterName = this.PARAMETER_NAME_PREFIX + keyFieldName;
parameter.DbType = this.GetDbType(table.Columns[keyFieldName].DataType);
parameter.Value = dr[keyFieldName];
sqlcom.Parameters.Add(parameter);
this.ExecCommand(sqlcom);
}

private void InnerDeleteRowByKeyField(object RowKeyFieldValue, string tableName, string keyFieldName, Type keyFieldType)
{
SQLiteCommand sqlcom = new SQLiteCommand(string.Format("Delete from {0} where {1} =" + this.PARAMETER_PREFIX + "{1}", tableName, keyFieldName));
IDataParameter parameter = new SQLiteParameter();
parameter.ParameterName = this.PARAMETER_NAME_PREFIX + keyFieldName;
parameter.DbType = this.GetDbType(keyFieldType);
parameter.Value = RowKeyFieldValue;
sqlcom.Parameters.Add(parameter);
this.ExecCommand(sqlcom);
}

private void InnerInsertRow(DataRow dr, string TableName, string primaryKeyField, bool primaryKeyValueIsAutoGenerated, out long primaryKeyValue)
{
string format = "Insert into {0}({1}) values ({2})";
SQLiteCommand sqlcom = new SQLiteCommand();
DataTable table = dr.Table;
StringBuilder builder = new StringBuilder();
StringBuilder builder2 = new StringBuilder();
for (int i = 0; i < dr.Table.Columns.Count; i++)
{
if (!primaryKeyValueIsAutoGenerated || !(table.Columns[i].ColumnName == primaryKeyField))
{
IDataParameter parameter = new SQLiteParameter();
parameter.ParameterName = this.PARAMETER_NAME_PREFIX + table.Columns[i].ColumnName;
parameter.DbType = this.GetDbType(table.Columns[i].DataType);
parameter.Value = dr[i];
sqlcom.Parameters.Add(parameter);
builder2.Append(table.Columns[i].ColumnName);
builder.Append(this.PARAMETER_PREFIX + table.Columns[i].ColumnName);
builder2.Append(",");
builder.Append(",");
}
}
string str2 = builder2.ToString();
str2 = str2.Substring(0, str2.Length - 1);
string str3 = builder.ToString();
str3 = str3.Substring(0, str3.Length - 1);
string str4 = string.Format(format, TableName, str2, str3);
sqlcom.CommandText = str4;
this.ExecCommand(sqlcom);
if (!primaryKeyValueIsAutoGenerated)
{
primaryKeyValue = 0L;
}
else
{
SQLiteCommand command2 = new SQLiteCommand("Select Max(" + primaryKeyField + ") from " + TableName);
object obj2 = this.ExecScalar(command2);
primaryKeyValue = (long) obj2;
}
}

private void InnerModifyRow(DataRow dr, string TableName, string keyFieldName)
{
string format = "Update {0} set {1} {2}";
string str2 = "{0}= " + this.PARAMETER_PREFIX + "{0}";
string str3 = " Where {0}=" + this.PARAMETER_PREFIX + "{0}";
StringBuilder builder = new StringBuilder();
SQLiteCommand sqlcom = new SQLiteCommand();
DataTable table = dr.Table;
for (int i = 0; i < dr.Table.Columns.Count; i++)
{
IDataParameter parameter = new SQLiteParameter();
parameter.ParameterName = this.PARAMETER_NAME_PREFIX + table.Columns[i].ColumnName;
parameter.DbType = this.GetDbType(table.Columns[i].DataType);
parameter.Value = dr[i];
sqlcom.Parameters.Add(parameter);
if (table.Columns[i].ColumnName == keyFieldName)
{
str3 = string.Format(str3, keyFieldName);
}
else
{
builder.Append(string.Format(str2, table.Columns[i].ColumnName));
builder.Append(",");
}
}
string str4 = builder.ToString();
str4 = str4.Substring(0, str4.Length - 1);
string str5 = string.Format(format, TableName, str4, str3);
sqlcom.CommandText = str5;
this.ExecCommand(sqlcom);
}

public void InsertRows(List<DataRow> listRows, string tableName)
{
foreach (DataRow row in listRows)
{
this.InsertRows(row, tableName);
}
}

public void InsertRows(DataRow row, string tableName)
{
long num;
this.SetToInsertState(row);
string primaryKeyField = "";
bool primaryKeyValueIsAutoGenerated = false;
this.InnerInsertRow(row, tableName, primaryKeyField, primaryKeyValueIsAutoGenerated, out num);
}

public void InsertRows(List<DataRow> listRows, string tableName, string primaryKeyField, bool primaryKeyValueIsAutoGenerated, out List<long> listPrimaryKeyValue)
{
listPrimaryKeyValue = new List<long>();
foreach (DataRow row in listRows)
{
long num;
this.SetToInsertState(row);
this.InnerInsertRow(row, tableName, primaryKeyField, primaryKeyValueIsAutoGenerated, out num);
listPrimaryKeyValue.Add(num);
}
}

public void InsertRows(DataRow row, string tableName, string primaryKeyField, bool primaryKeyValueIsAutoGenerated, out long primaryKeyValue)
{
this.SetToInsertState(row);
this.InnerInsertRow(row, tableName, primaryKeyField, primaryKeyValueIsAutoGenerated, out primaryKeyValue);
}

public void ModifyRows(List<DataRow> listRows, string tableName, string keyFieldName)
{
foreach (DataRow row in listRows)
{
this.SetToModifyState(row);
this.InnerModifyRow(row, tableName, keyFieldName);
}
}

public void ModifyRows(DataRow row, string tableName, string keyFieldName)
{
this.SetToModifyState(row);
this.InnerModifyRow(row, tableName, keyFieldName);
}

public void SetToDeleteState(DataRow row)
{
row.RowError = this.DELETED_FLAG;
}

public void SetToInsertState(DataRow row)
{
row.RowError = this.INSERTED_FLAG;
}

public void SetToModifyState(DataRow row)
{
row.RowError = this.MODIFIED_FLAG;
}

private void TryCloseConnection()
{
if (this.m_SelfBuildConnection && (this.m_SqlConn != null))
{
this.m_SqlConn.Close();
}
}

private void TryOpenConnection()
{
if (this.m_SelfBuildConnection)
{
this.m_SqlConn.Open();
}
}

public string ConnectionString
{
get
{
return this.m_ConnectionString;
}
set
{
this.m_ConnectionString = value;
}
}

public bool LogSqlExecute
{
get
{
return this.m_LogSqlExecute;
}
set
{
this.m_LogSqlExecute = value;
this.m_SqlExecuteTracer.LogSqlExecute = this.m_LogSqlExecute;
}
}
}
}

Managed ExecuteShell API



namespace LiuHarry.Utils.Foundation
{
using System;
using System.Diagnostics;

public class CommandShell
{
public static string RunCmd(string command)
{
Process process = new Process();
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.Arguments = "/c " + command;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.CreateNoWindow = true;
process.Start();
return process.StandardOutput.ReadToEnd();
}

public static void CallWindowsApp()
{
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.EnableRaisingEvents=false;
//call calculator
proc.StartInfo.FileName="calc";
proc.Start();
}

public static void GotoWebSite()
{
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.EnableRaisingEvents=false;
proc.StartInfo.FileName="iexplore";
proc.StartInfo.Arguments=http://www.microsoft.com;
proc.Start();
proc.WaitForExit();
MessageBox.Show("You have just visited www.microsoft.com");
}

public static void OpenWordDocument()
{
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.EnableRaisingEvents=false;
proc.StartInfo.FileName="winword";
proc.StartInfo.Arguments="C:\\Dotnetstuff\\TestWordDoc.doc";
proc.Start();
}

public static void ExecuteBatchFile()
{
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.EnableRaisingEvents=false;
proc.StartInfo.FileName="c:\\dotnetstuff\\netdrv.bat";
proc.Start();
MessageBox.Show("Map Drive Created");
}

}


}

How to create a new XmlElement

XmlNode是一个Context相关的对象, 你不能直接调用XmlNode的构造子来创建一个XmlNode. 要创建一个XmlNode有两个方法. 假设要在xmlParentNode下创建一个newNode.
方法1: 通过XmlDocument的CreateElement方法创建一个XmlNode
  public XmlElement CreateElement(prefix,localName,namespaceURI),如果元素带有namespace,必须加上namespaceURI, 比如:
步骤1:XmlElement newNode= docNode.CreateElement("w", "br", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
步骤2:xmlParentNode.InsertAfter(br, rNode.FirstChild);

方法2: 不是直接创建XmlElement,而是通过修改xmlParentNode的InnerXml文本, 来增加一个节点.记住:如果新加的内容包含前缀,一定要加上namespace URI.否则会报错的.  

xmlParentNode.InnerXml= @"<w:r xmlns:w=""http://schemas.openxmlformats.org/wordprocessingml/2006/main""><w:rPr>
</w:rPr>
<w:br/>
<w:t>Some string </w:t></w:r>"
;