生如夏花

这是一个多美丽又遗憾的世界,我们就这样抱着笑着还流着泪 我从远方赶来赴你一面之约,痴迷流连人间我为她而狂野
posts - 11, comments - 6, trackbacks - 0, articles - 2
  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理

2007年8月17日

最近在项目中因为各种需要必须把出错信息及相关数据记录起来,由于考虑到记录到系统日志,不便于收集,所以综合起来,还是决定用文件记录出错信息,这样,如果客户使用程序过程中出现错误,可以直接将日志文件发送过来以便我们寻找问题的根源

1. 先写个日志记录类,主要代码如下
using System;
using System.Text;
using System.IO;

        /// <summary>
        /// 记录错误日志到文本文件
        /// </summary>
        /// <param name="text">日志内容</param>
        static public void WriteLog(string text)
        {
            string folderPath = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\My Tests\\Log1";//记录到当前登陆用户文件夹下,保证了用户的权限问题

            if (!Directory.Exists(folderPath))
            {
                Directory.CreateDirectory(folderPath);
            }
            string filePath = folderPath + "\\Log.txt";

            LogToFile(text, filePath);
        }

        #region 记录文本到文本文件
        /// <summary>
        /// 记录文本到文本文件
        /// </summary>
        /// <param name="text">记录内容</param>
        /// <param name="filePath">文件路径</param>
        static private void LogToFile(string text, string filePath)
        {
            //-------------------
            StreamWriter sw = null;
            try
            {
                if (!File.Exists(filePath))
                {
                    sw = File.CreateText(filePath);
                }
                else
                {
                    sw = File.AppendText(filePath);
                }
                string msg = string.Format("---------Log Time:{0}--------", System.DateTime.Now.ToString());
                sw.WriteLine(msg);
                sw.WriteLine(text);
            }
            finally
            {
                if (sw != null)
                {
                    sw.Close();
                    sw = null;
                }
            }
        }
        #endregion

        //-------------
    }

/****************
 * 原本MSDN2005代码
// This text is added only once to the file.
// Create a file to write to.
using (StreamWriter sw = File.CreateText(filePath))
{
    string msg = string.Format("---------Log Time:{0}--------", System.DateTime.Now.ToString());
    sw.WriteLine(msg);
    sw.WriteLine(text);
}
****************/


2. 调用代码如下
string[] sList ={
"11111111111",
"22222222222",
"33333333333",
"44444444444",
"55555555555",
"66666666666",
"77777777777",
"88888888888",
"99999999999",
"AAAAAAAAAAA",
"BBBBBBBBBBB",
"CCCCCCCCCCC",
"DDDDDDDDDDD",
"EEEEEEEEEEE"
};
foreach (string s in sList)
{
LogMsg.WriteLog(s);
}
3. 测试,能正确记录内容
现在主要有以下几个疑问,希望大家能一起讨论
1. 假如在设置保存文件的路径时设置如下
            string filePath = System.Windows.Forms.Application.ExecutablePath + ".log";
在本机上使用系统帐户登陆,能正常记录日志内容

如果使用Guest组用户(用户无在此目录修改文件的权限),这时无法记录日志内容

2. 系统使用UTF8(File.CreateText(filePath))编码保存文本内容,不知在其他操作系统下是否会有乱码或是编码不兼容问题

3.
string msg = string.Format("---------Log Time:{0}--------", System.DateTime.Now.ToString());
sw.WriteLine(msg);
sw.WriteLine(text);//执行了两次

string msg = string.Format("---------Log Time:{0}--------", System.DateTime.Now.ToString());
string msgtext=msg+ System.Environment.NewLine+text;
sw.WriteLine(msgtext);//仅执行一次

哪种好点,哪种效率高

4.
//方式1
// 使用using方式,参考微软MSDN2005帮助文档System.IO.File.AppendText()提供的示例
using (StreamWriter sw = File.CreateText(filePath))
{
    string msg = string.Format("---------Log Time:{0}--------", System.DateTime.Now.ToString());
    sw.WriteLine(msg);
    sw.WriteLine(text);
}
//?这里不知是否会关闭sw对象

//方式2
//使用try catch方式
StreamWriter sw = null;
try
{
if (!File.Exists(filePath))
{
    sw = File.CreateText(filePath);
}
else
{
    sw = File.AppendText(filePath);
}
string msg = string.Format("---------Log Time:{0}--------", System.DateTime.Now.ToString());
sw.WriteLine(msg);
sw.WriteLine(text);
}
finally
{
if (sw != null)
{
    sw.Close();
    sw = null;
}
}

哪种好点,哪种效率高,不知有什么不同
项目文件如下

/Files/chenaspx/FileLogDemo.rar

posted @ 2007-08-17 22:16 陈欠扁 阅读(50) | 评论 (0)编辑

2007年7月30日

using System;
using System.Collections.Generic;
using System.Text;

namespace HardwareDistributor.Business
{
    public class Customer
    {
        private int _customerId;
        private string _customerName;
        private string _streetAddress;
        private string _city;
        private string _stateProvince;
        private string _postalCode;
        private string _contactName;
        private string _contactPhone;
        private int _routeId;

        public Customer() { }

        public Customer(int customerId, string customerName, string streetAddress,
                        string city, string stateProvince, string postalCode,
                        string contactName, string contactPhone, int routeId)
        {
            this._customerId = customerId;
            this._customerName = customerName;
            this._streetAddress = streetAddress;
            this._city = city;
            this._stateProvince = stateProvince;
            this._postalCode = postalCode;
            this._contactName = contactName;
            this._contactPhone = contactPhone;
            this._routeId = routeId;
        }


        /// <summary>
        /// Customer's phone number
        /// </summary>
        public string ContactPhone
        {
            get
            {
                return _contactPhone;
            }
            set
            {
                _contactPhone = value;
            }
        }


        /// <summary>
        /// Point of contact at Customer's company
        /// </summary>
        public string ContactName
        {
            get
            {
                return _contactName;
            }
            set
            {
                _contactName = value;
            }
        }


        /// <summary>
        /// Customer's postal/zip code
        /// </summary>
        public string PostalCode
        {
            get
            {
                return _postalCode;
            }
            set
            {
                _postalCode = value;
            }
        }


        /// <summary>
        /// State or Province where customer resides
        /// </summary>
        public string StateProvince
        {
            get
            {
                return _stateProvince;
            }
            set
            {
                _stateProvince = value;
            }
        }


        /// <summary>
        /// City where customer resides
        /// </summary>
        public string City
        {
            get
            {
                return _city;
            }
            set
            {
                _city = value;
            }
        }


        /// <summary>
        /// Address of Customer's place of business
        /// </summary>
        public string StreetAddress
        {
            get
            {
                return _streetAddress;
            }
            set
            {
                _streetAddress = value;
            }
        }


        /// <summary>
        /// Id of the route this customer belongs to
        /// </summary>
        public int RouteId
        {
            get
            {
                return _routeId;
            }
            set
            {
                _routeId = value;
            }
        }


        /// <summary>
        /// Customer's unique Id
        /// </summary>
        public int CustomerId
        {
            get
            {
                return _customerId;
            }
            set
            {
                _customerId = value;
            }
        }

       
        /// <summary>
        /// Customer's company name
        /// </summary>
        public string CustomerName
        {
            get
            {
                return _customerName;
            }
            set
            {
                _customerName = value;
            }
        }


    }
}


using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;


namespace HardwareDistributor.Business
{
    public class CustomerCollection : CollectionBase
    {

        /// <summary>
        /// Collection indexer
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        public Customer this[int index]
        {
            get
            {
                return (Customer)List[index];
            }
            set
            {
                List[index] = value;
            }
        }


        /// <summary>
        /// Adds an object to the collection
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public int Add(Customer value)
        {
            return (List.Add(value));
        }


        /// <summary>
        /// Returns the index of the passed-in object
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public int IndexOf(Customer value)
        {
            return (List.IndexOf(value));
        }


        /// <summary>
        /// Inserts an object into a specfic index of the collection
        /// </summary>
        /// <param name="index"></param>
        /// <param name="value"></param>
        public void Insert(int index, Customer value)
        {
            List.Insert(index, value);
        }


        /// <summary>
        /// Removes an object from the collection
        /// </summary>
        /// <param name="value"></param>
        public void Remove(Customer value)
        {
            List.Remove(value);
        }


        /// <summary>
        /// Tells you if this collection
        /// contains the passed-in object
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public bool Contains(Customer value)
        {
            return (List.Contains(value));
        }

    }
}


/Files/chenaspx/daabcf.zip

posted @ 2007-07-30 22:44 陈欠扁 阅读(22) | 评论 (0)编辑

2007年7月21日

     摘要:   阅读全文

posted @ 2007-07-21 22:26 陈欠扁 阅读(454) | 评论 (0)编辑

2006年12月27日

using System;
using System.Data;
using System.Text;
using System.Data.SqlClient;
using System.Collections;
using System.Configuration;

/// <summary>
/// Summary description for SqlHelper
/// </summary>
public class SqlHelper
{
    //public static string CONN_STR = @"Server=HUDENGWEN\SQLEXPRESS;Database=MQSDB;Trusted_Connection=True";
    public static string CONN_STR = System.Configuration.ConfigurationSettings.AppSettings["CONN_STRING"];

    #region ExecuteNonQuery(SQL语句)
    /// <summary>
    /// 执行Update,delete,insert语句
    /// </summary>
    /// <param name="strSql"></param>
    /// <returns></returns>

    public static int ExcectueNonQuery(string strSql)
    {

        using (SqlConnection con = new SqlConnection(CONN_STR))
        {
            con.Open();
            SqlCommand command = new SqlCommand(strSql, con);
            try
            {
                return command.ExecuteNonQuery();
            }
            catch (SqlException ex)
            {
                throw new Exception(ex.Message);
            }
        }
    }
    #endregion

    #region  ExecuteDataset:返回DataSet(查询SQL语句)
    /// <summary>
    /// 执行查询传入Select语句 返回DataSet
    /// </summary>
    /// <param name="strSql"></param>
    /// <returns></returns>
    public static DataSet ExecuteDataset(string strSql)
    {
        try
        {
            using (SqlConnection conn = new SqlConnection(CONN_STR))
            {
                conn.Open();
                // System.Data.SqlServerCe.SqlCeCommand com = new SqlCeCommand(strSql, DAL.CreateConn.GetConn());
                SqlDataAdapter da = new SqlDataAdapter(strSql, conn);
                System.Data.DataSet ds = new DataSet();
                da.Fill(ds);
                return ds;
            }
        }
        catch (SqlException ex)
        {
            throw new Exception(ex.Message);
        }
    }
    #endregion

    #region  ExecuteObj:传入Sql语句返回首行首列的对象(SQL语句)
    /// <summary>
    /// 传入Sql语句返回首行首列的对象
    /// </summary>
    /// <param name="strSql"></param>
    /// <returns></returns>
    public static object ExecuteObj(string strSql)
    {
        try
        {
            using (SqlConnection conn = new SqlConnection(CONN_STR))
            {
                conn.Open();
                SqlCommand command = new SqlCommand(strSql, conn);
                object obj = command.ExecuteScalar();
                if (object.Equals(obj, null))
                {
                    return null;
                }
                else
                {
                    return obj;
                }
            }

        }
        catch (SqlException ex)
        {
            throw new Exception(ex.Message);
        }
    }
    #endregion
}

posted @ 2006-12-27 08:57 陈欠扁 阅读(76) | 评论 (0)编辑

2006年12月15日

NBear演示项目Starter Kit - NBear Offical Site v1.0.2(Lukiya编写)笔记

1.委托和事件的用法
以namespace NBear.ServiceComs下的ArticlesCom为例
先声明委托
  public delegate void ArticlesChangedHanlder();
定义一个事件
    public event ArticlesChangedHanlder ArticlesChanged;
注册此事件的方法
    public ArticlesCom()
    {
      ArticlesChanged += new ArticlesChangedHanlder(Caches.DropNews);
    }
    public static void DropNews()
    {
      News = null;
    }

在需要的地方调用此事件
    public void Save(nb_Articles entity)
    {
      try
      {
        Check(entity);

        Gateways.MainDb.Save<nb_Articles>(entity);

        ArticlesChanged();
      }
      catch
      {
        throw;
      }
    }

    public void Delete(object id)
    {
      try
      {
        Gateways.MainDb.Delete<nb_Articles>(id);

        ArticlesChanged();
      }
      catch
      {
        throw;
      }
    }

2.

posted @ 2006-12-15 10:12 陈欠扁 阅读(47) | 评论 (0)编辑

2006年12月8日

Access数据库查询练习专用数据库 -手机号码归属地Access数据库_MobileDB(10万条记录)

posted @ 2006-12-08 20:54 陈欠扁 阅读(165) | 评论 (2)编辑


今天下午帮公司完善移动报价系统的程序,添加了日志记录功能,顺便整理了一下经常要用到代码

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

posted @ 2006-12-08 16:26 陈欠扁 阅读(172) | 评论 (0)编辑

下午无事,在CNBLOGS闲逛时发现一BLOG系统吕的部落格源码下载

posted @ 2006-12-08 16:10 陈欠扁 阅读(29) | 评论 (0)编辑

从发现微软维生素C.net的文章这真的是微软的作品吗?中知道了这个东东,下载了个试试,试用之后再写点感想

posted @ 2006-12-08 11:15 陈欠扁 阅读(417) | 评论 (3)编辑

2006年9月28日

人=吃饭+睡觉+上班+玩,
猪=吃饭+睡觉,
代入:人=猪+上班+玩,
即:人-玩=猪+上班.
结论:不懂玩的人=会上班的猪! 

男人=吃饭+睡觉+挣钱
猪=吃饭+睡觉
男人=猪+挣钱
猪=男人-挣钱
所以男人不挣钱等于猪。

女人=吃饭+睡觉+花钱。
猪  =吃饭+睡觉。代入上式得:
女人=猪+花钱。移项得:
女人-花钱=猪。
结论:女人不花钱的都是猪。

综上:
男人为了让女人不变成猪而挣钱!
女人为了让男人不变成猪而花钱!
     
男人+女人=两头猪 

posted @ 2006-09-28 07:58 陈欠扁 阅读(24) | 评论 (0)编辑