今天下午帮公司完善移动报价系统的程序,添加了日志记录功能,顺便整理了一下经常要用到代码
1.日志记录(可以记录SQLCE的错误信息到日志文件)
using System.Reflection;
public static void LogError(Exception ex)
{
StreamWriter writer1 = null;
try
{
writer1 = new StreamWriter(Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase) + @"\ErrorLog.txt", true, Encoding.ASCII);
writer1.WriteLine("* " + DateTime.Now.ToString() + " | " + ex.Message + " | " + ex.StackTrace);
}
finally
{
if (writer1 != null)
{
writer1.Close();
writer1 = null;
}
}
}
///如果不存在指定文件,则在当前程序目录下新建文件,并把错误信息记录到文件中(从文件结尾添加内容)
2.
#region 从将二进制数组转化为图片(二进制数组)
/// <summary>
/// 从数据库中获取Byte数组对象得到图片
/// </summary>
/// <param name="byteData"></param>
/// <returns>图片对象</returns>
public static System.Drawing.Image GetImage(byte[] byteData)
{
try
{
using (System.IO.Stream fs = new MemoryStream(byteData.Length))
{
//System.IO.MemoryStream mf = new MemoryStream(byteData,0,byteData.LongLength);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write((byte[])byteData);
bw.Flush();
System.Drawing.Bitmap bitMap = new System.Drawing.Bitmap(fs);
bw.Close();
fs.Close();
System.Drawing.Image image = System.Drawing.Image.FromHbitmap(bitMap.GetHbitmap());
return image;
}
}
catch (System.IO.IOException ee)
{
throw new Exception(ee.Message + "Read image data error!");
}
//return null;
}
#endregion
3.
using System.Net;
using Microsoft.WindowsMobile.Status;
public static bool GetConnectionStatus()
{
if (SystemState.ConnectionsCount > 0)
{
return true;
}
return false;
}
获取当前连接状态
4.
#region ExecuteTransAction
/// <summary>
/// 执行事务、传入SQL语句字符串数组
/// </summary>
/// <param name="strTrans"></param>
/// <returns></returns>
public static int ExecuteTransAction(string[] strTrans)
{
using (System.Data.SqlServerCe.SqlCeConnection conn = new System.Data.SqlServerCe.SqlCeConnection(Common.SqlDB.SqlCeDbConnectionString))
{
if (conn.State.Equals(ConnectionState.Closed))
{
conn.Open();
}
System.Data.SqlServerCe.SqlCeCommand cmd = new SqlCeCommand();
// System.Data.OleDb.OleDbTransaction trans =conn.BeginTransaction;
int i = strTrans.Length;
try
{
cmd.Connection = conn;
cmd.Transaction = conn.BeginTransaction();
foreach (string str in strTrans)
{
cmd.CommandText = str;
cmd.ExecuteNonQuery();
}
cmd.Transaction.Commit();
return 1;
}
catch (System.Data.SqlServerCe.SqlCeException ee)
{
cmd.Transaction.Rollback();
throw new Exception(ee.Message);
}
}
}
#endregion
浙公网安备 33010602011771号