Tagged: c#

WinCE 同步时间

最近项目中PDA的时间总是与业务数据时间不符,因此需要一个这样的功能。

首先确定使用WebService的Response信息作为时间的获取源头。

代码如下

#region 修改系统日期
[DllImport("coredll.dll")]
private static extern bool SetLocalTime(ref SystemTime lpSystemTime);

public struct SystemTime
{
    public short wYear;
    public short wMonth;
    public short wDayOfWeek;
    public short wDay;
    public short wHour;
    public short wMinute;
    public short wSecond;
    public short wMilliseconds;
}

/// <summary>
/// 设置系统当前日期
/// </summary>
public static void SetTime()
{

    WebRequest request = null;
    WebResponse response = null;
    WebHeaderCollection headerCollection = null;

    string webserviceUrl = string.Format("http://{0}/axis/servlet/AxisServlet", DB.GetServerAddr());
    string datetime = string.Empty;
    CultureInfo cultureInfo = CultureInfo.CreateSpecificCulture("en-US");
    // Tue, 11 Sep 2018 09:46:58 GMT
    string format = "r";

    try
    {
        request = WebRequest.Create(webserviceUrl);
        request.Timeout = -1;
        request.Credentials = CredentialCache.DefaultCredentials;
        response = request.GetResponse();
        headerCollection = response.Headers;
        foreach (var item in headerCollection.AllKeys)
        {
            if (item.Equals("Date",StringComparison.CurrentCultureIgnoreCase))
            {
                datetime = headerCollection[item];
            }
        }

        SystemTime newTime = new SystemTime();
        DateTime dt = DateTime.ParseExact(datetime, format, cultureInfo).AddHours(8.00);

        newTime.wYear = Convert.ToInt16(dt.Year);
        newTime.wMonth = Convert.ToInt16(dt.Month);
        newTime.wDay = Convert.ToInt16(dt.Day);
        newTime.wDayOfWeek = Convert.ToInt16(dt.DayOfWeek);
        newTime.wHour = Convert.ToInt16(dt.Hour);
        newTime.wMinute = Convert.ToInt16(dt.Minute);
        newTime.wSecond = Convert.ToInt16(dt.Second);

        SetLocalTime(ref newTime);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    finally
    {
        if (request != null)
        {
            request.Abort();
        }
        if (response != null)
        {
            response.Close();
        }
        if (headerCollection != null)
        {
            headerCollection.Clear();
        }
    }
}
#endregion

C# 自动导入数据至数据库

最后在写一个项目,数据源自NC接口,需要将NC接口返回的数据处理后导入Sqlite数据库。

在实际操作中需要直接写入Datatable的对象进数据库,或直接将一行数据库写入数据,但每次构建SQL这些太麻烦。因此才有了这样一个处理类。

构建SQL

/// <summary>
/// 根据DataTable构建插入语句
/// </summary>
/// <param name="dataTable"></param>
/// <returns></returns>
public static string builderSql(DataTable dataTable)
{
    StringBuilder sb = new StringBuilder("insert into "+ dataTable.TableName + "(");
    StringBuilder head = new StringBuilder();
    StringBuilder values = new StringBuilder();
    foreach (DataColumn col in dataTable.Columns)
    {
        head.Append(col.ColumnName + ",");
        values.Append("@" + col.ColumnName + ",");
    }
    head.Remove(head.Length - 1, 1);
    values.Remove(values.Length - 1, 1);
    sb.Append(head).Append(") VALUES (").Append(values).Append(");");
    sb.Append("select last_insert_rowid();");
    return sb.ToString();
}

插入行

/// <summary>
/// 插入行
/// </summary>
/// <param name="row"></param>
/// <returns>数据库ID</returns>
public static int InsertDataRow(DataRow row) 
{
    using (SQLiteConnection connection = new SQLiteConnection(connectionString))
    {
        using (SQLiteCommand cmd = new SQLiteCommand())
        {
            try
            {
                string SQLString = builderSql(row.Table);

                List<SQLiteParameter> sqlitePars = new List<SQLiteParameter>();
                foreach (DataColumn col in row.Table.Columns)
                {
                    SQLiteParameter pars = new SQLiteParameter();
                    pars.ParameterName = string.Format("@{0}", col.ColumnName);
                    pars.Value = row[col.ColumnName];
                    pars.DbType = GetDbType(col.DataType);
                    sqlitePars.Add(pars);
                }

                PrepareCommand(cmd, connection, null, SQLString, sqlitePars.ToArray());

                int rows = Convert.ToInt32(cmd.ExecuteScalar());

                cmd.Parameters.Clear();
                return rows;
            }
            catch (System.Data.SQLite.SQLiteException sqlex)
            {
                throw sqlex;
            }
        }
    }
}

批量写入

/// <summary>
/// 批量插入
/// </summary>
/// <param name="dataTable">需插入数据库的表</param>
/// <param name="DataBaseName">数据库名称</param>
/// <returns></returns>
public static void InsertDataTable(DataTable dataTable)
{
    using (SQLiteConnection conn = new SQLiteConnection(connectionString))
    {
        conn.Open();
        using (SQLiteTransaction trans = conn.BeginTransaction())
        {
            SQLiteCommand cmd = new SQLiteCommand();
            try
            {
                // 构建插入语句
                string cmdText = builderSql(dataTable);

                //循环
                foreach (DataRow row in dataTable.Rows)
                {
                    string BaseName = dataTable.TableName;

                    // 构建插入值
                    List<SQLiteParameter> sqlitePars = new List<SQLiteParameter>();
                    foreach (DataColumn col in dataTable.Columns)
                    {
                        SQLiteParameter pars = new SQLiteParameter();
                        pars.ParameterName = string.Format("@{0}", col.ColumnName);
                        pars.Value = row[col.ColumnName];
                        pars.DbType = GetDbType(col.DataType);
                        sqlitePars.Add(pars);
                    }
                    PrepareCommand(cmd, conn, trans, cmdText, sqlitePars.ToArray());
                    int val = cmd.ExecuteNonQuery();
                    cmd.Parameters.Clear();
                }
                trans.Commit();
            }
            catch
            {
                trans.Rollback();
                throw;
            }
        }
    }
}

自动获取对象数据类型

private static Dictionary typeMap;

#region 类型对应
static SQLite()
{
    typeMap = new Dictionary();

    typeMap[typeof(string)] = DbType.String;
    typeMap[typeof(byte)] = DbType.Byte;
    typeMap[typeof(int)] = DbType.Int32;
    typeMap[typeof(Int16)] = DbType.Int16;
    typeMap[typeof(Int32)] = DbType.Int32;
    typeMap[typeof(Int64)] = DbType.Int64;
    typeMap[typeof(DateTime)] = DbType.DateTime;
    typeMap[typeof(decimal)] = DbType.Decimal;
    typeMap[typeof(float)] = DbType.Double;
    typeMap[typeof(double)] = DbType.Double;
}

public static DbType GetDbType(Type giveType)
{
    giveType = Nullable.GetUnderlyingType(giveType) ?? giveType;

    if (typeMap.ContainsKey(giveType))
    {
        return typeMap[giveType];
    }

    throw new ArgumentException(string.Format("{0} is not a supported .NET class", giveType.FullName));
}

public static DbType GetDbType()
{
    return GetDbType(typeof(T));
}

#endregion

DataTable 差集Except、交集Intersect、并集Union

使用方法

//获取第一个数据源DataTable
DataTable _dtSource = DBHelper.GetDataTable("select top 10  ksdid,user_id,user_pwd from ksd_user_info");

IEnumerable<DataRow> query = _dtSource.AsEnumerable().Where(t => t.Field<string>("user_id").StartsWith("66")).ToList();
//获取第二个数据源DataTable
DataTable _dt2 = query.CopyToDataTable();

//比较两个数据源的交集
IEnumerable<DataRow> query2 = _dtSource.AsEnumerable().Intersect(dt2.AsEnumerable(), DataRowComparer.Default);
//两个数据源的交集集合      
DataTable dt3 = query2.CopyToDataTable();


//获取两个数据源的并集
IEnumerable<DataRow> query2 = _dtSource.AsEnumerable().Union(dt2.AsEnumerable(), DataRowComparer.Default);
//两个数据源的并集集合
DataTable dt3 = query2.CopyToDataTable();


//获取两个数据源的差集
IEnumerable<DataRow> query2 = _dtSource.AsEnumerable().Except(dt2.AsEnumerable(), DataRowComparer.Default);
//两个数据源的差集集合
DataTable dt3 = query2.CopyToDataTable();

自定义比较器

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Kelun.Comparer
{
    /// <summary>
    /// 计量单位比较器
    /// </summary>
    class JldwComparer : IEqualityComparer<DataRow>
    {
        public bool Equals(DataRow x, DataRow y)
        {
            return (x.Field<string>("F_DWBH") == y.Field<string>("F_DWBH") &&
            x.Field<string>("F_DWMC") == y.Field<string>("F_DWMC") &&
            x.Field<string>("F_DWLX") == y.Field<string>("F_DWLX"));
        }

        public int GetHashCode(DataRow obj)
        {
            return obj.ToString().GetHashCode();
        }
    }
}

根据自定义条件获取差集

// 获取2个数据源的差集
//IEnumerable<DataRow> query = _dt.AsEnumerable().Except(_sdt.AsEnumerable(), DataRowComparer.Default);
IEnumerable<DataRow> query = _dt.AsEnumerable().Except(_sdt.AsEnumerable(), new JldwComparer());

int querynum = query.Count();

if (querynum > 0)
{
	var _saveDt = query.CopyToDataTable();
	SqlDbHelper.Insert(_saveDt, "HNKL_JLDW_ERP");
	var msg = string.Format("计量单位写入成功,共计{0}条", _saveDt.Rows.Count);
	Logger.Info(msg, null, "System");
}

Quartz.NET 3.x 例子

最近写项目需要用到定时任务,所以就找到了Quartz.NET,但网上的例子都是到处抄袭的,完全没有适合Quartz.NET 3.x 的有用信息,这里就将自己的使用例子帖一下。

  • IDE:VS2017
  • .Net : 4.5.2

写在前面

Quartz.NET 在3.x已经将插件分离了,所以如果要从xml直接加载文件,需要引入插件包

引入包

配置

app.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>

  <configSections>
    <section name="quartz" type="System.Configuration.NameValueSectionHandler, System, Version=1.0.5000.0,Culture=neutral, PublicKeyToken=b77a5c561934e089" />
  </configSections>

  <quartz>
    <add key="quartz.scheduler.instanceName" value="QuartzScheduler"/>
    <add key="quartz.threadPool.type" value="Quartz.Simpl.SimpleThreadPool, Quartz"/>
    <add key="quartz.threadPool.threadCount" value="10"/>
    <!--******************************Plugin配置*********************************************-->
    <add key="quartz.plugin.jobInitializer.type" value="Quartz.Plugin.Xml.XMLSchedulingDataProcessorPlugin, Quartz.Plugins"/>
    <add key="quartz.plugin.jobInitializer.fileNames" value="quartz_jobs.xml"/>
  </quartz>

  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2"/>
  </startup>

</configuration>

quartz_jobs.xml

<?xml version="1.0" encoding="UTF-8"?>

<!-- This file contains job definitions in schema version 2.0 format -->

<job-scheduling-data xmlns="http://quartznet.sourceforge.net/JobSchedulingData" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0">

  <processing-directives>
    <overwrite-existing-data>true</overwrite-existing-data>
  </processing-directives>


  <schedule>

    <!--开始执行一个调度-->
    <job>
      <name>jldwjob</name>
      <group>kelun</group>
      <description>计量单位</description>
      <job-type>Kelun.JldwJob, Kelun</job-type><!--格式:实现了IJob接口的包含完整命名空间的类名,程序集名称-->
      <durable>true</durable>
      <recover>false</recover>
    </job>
    
    <trigger>
      <cron>
        <name>jlwd</name>
        <group>kelun</group>
        <job-name>jldwjob</job-name>
        <job-group>kelun</job-group>
        <!--<start-time>2018-01-22T00:00:00+08:00</start-time>-->
        <cron-expression>0/1 * * * * ?</cron-expression><!--每3秒执行一次-->
      </cron>
    </trigger>

  </schedule>
</job-scheduling-data>

接口实现

using Kelun.Log4Net;
using Quartz;
using System.Reflection;
using System.Threading.Tasks;

namespace Kelun
{
    class JldwJob : IJob
    {

        private static readonly IMyLog Logger = MyLogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        public Task Execute(IJobExecutionContext context)
        {
            return Task.Run(() => 
            {
                Logger.Info("定时任务执行");
            });
        }
    }
}

启动Quartz

public MainForm()
{
    InitializeComponent();
    RunProgramAsync().GetAwaiter().GetResult();
}

private static async Task RunProgramAsync()
{
    try
    {
        StdSchedulerFactory factory = new StdSchedulerFactory();

        IScheduler scheduler = await factory.GetScheduler();

        //开启调度器
        await scheduler.Start();

        //创建一个作业
        //IJobDetail job = JobBuilder.Create<JldwJob>().WithIdentity("myJob", "group1").Build();

        //ITrigger trigger = TriggerBuilder.Create()
        //    .WithIdentity("myTrigger", "group1")
        //    .StartNow()     //现在开始
        //    .WithSimpleSchedule(x => x
        //        .WithIntervalInSeconds(1)   //触发时间,1秒一次
        //        .RepeatForever())
        //    .Build();

        //把作业,触发器加入调度器。
       //await scheduler.ScheduleJob(job, trigger);  

        //await scheduler.Shutdown();

    }
    catch (SchedulerException se)
    {
        Logger.Error("执行错误", se);
    }
}

禁用Quartz.NET日志输出

<logger name="Quartz">
	<level value="OFF" />
</logger>

Log4Net 写入数据库[扩展字段]

最近在写一个项目,需要将日志写入数据库,Log4Net的功能仅仅只能满足写入消息部分,若需要写入自定义信息就不行了,所以这里扩展了Log4Net的部分功能。

扩展字段

建立扩展字段的Entity类

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

namespace Kelun.Log4Net
{
    /// <summary>
    /// 扩展Log4Net字段
    /// </summary>
    class LogMessage
    {
        /// <summary>
        /// 订单号
        /// </summary>
        public string OrderNum { get; set; }

        /// <summary>
        /// 用户
        /// </summary>
        public string UserName { get; set; }

        public LogMessage(string orderNum, string userName)
        {
            OrderNum = orderNum;
            UserName = userName;
        }
    }
}

转换类

using log4net.Core;
using log4net.Layout.Pattern;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace Kelun.Log4Net
{
    /// <summary>
    /// Log4Net 扩展字段
    /// 转换自定义字段
    /// </summary>
    class ParemterContent
    {
        internal sealed class OrderNumParam : PatternLayoutConverter
        {
            protected override void Convert(TextWriter writer, LoggingEvent loggingEvent)
            {
                if (loggingEvent.MessageObject is LogMessage content)
                {
                    writer.Write(content.OrderNum);
                }
            }
        }

        internal sealed class UserNameParam : PatternLayoutConverter
        {
            protected override void Convert(TextWriter writer, LoggingEvent loggingEvent)
            {
                if (loggingEvent.MessageObject is LogMessage content)
                {
                    writer.Write(content.UserName);
                }
            }
        }
    }
}

Layout 扩展

using log4net.Layout;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Kelun.Log4Net
{
    class MyLoggerLayout : PatternLayout
    {
        public MyLoggerLayout()
        {
            this.AddConverter("OrderNum", typeof(ParemterContent.OrderNumParam));
            this.AddConverter("UserName", typeof(ParemterContent.UserNameParam));
        }
    }
}

扩展方法

接口

using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Kelun.Log4Net
{
    interface IMyLog : ILog
    {
        void Debug(object message, string OrderNum, string UserName);
        void Debug(object message, string OrderNum, string UserName,Exception t);

        void Info(object message, string OrderNum, string UserName);
        void Info(object message, string OrderNum, string UserName, Exception t);

        void Warn(object message, string OrderNum, string UserName);
        void Warn(object message, string OrderNum, string UserName, Exception t);

        void Error(object message, string OrderNum, string UserName);
        void Error(object message, string OrderNum, string UserName, Exception t);

    }
}

接口实现

using Kelun.Log4Net;
using log4net.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Kelun.Log4Net
{
    class MyLogImpl : LogImpl, IMyLog
    {

        public static readonly Type ThisDeclaringType = typeof(MyLogImpl);

        public MyLogImpl(ILogger logger) : base(logger)
        {
            
        }

        #region 实现重写

        public void Debug(object message, string OrderNum, string UserName)
        {
            Debug(message, OrderNum, UserName, null);
        }

        public void Debug(object message, string OrderNum, string UserName, Exception t)
        {
            if (this.IsDebugEnabled)
            {
                LoggingEvent loggingEvent = new LoggingEvent(ThisDeclaringType, Logger.Repository, Logger.Name, Level.Debug, message, t);
                loggingEvent.Properties["UserName"] = UserName;
                loggingEvent.Properties["OrderNum"] = OrderNum;
                Logger.Log(loggingEvent);
            }
        }

        public void Error(object message, string OrderNum, string UserName)
        {
            Error(message, OrderNum, UserName, null);
        }

        public void Error(object message, string OrderNum, string UserName, Exception t)
        {
            if (this.IsErrorEnabled)
            {
                LoggingEvent loggingEvent = new LoggingEvent(ThisDeclaringType, Logger.Repository, Logger.Name, Level.Error, message, t);
                loggingEvent.Properties["UserName"] = UserName;
                loggingEvent.Properties["OrderNum"] = OrderNum;
                Logger.Log(loggingEvent);
            }
        }

        public void Info(object message, string OrderNum, string UserName)
        {
            Info(message, OrderNum, UserName, null);
        }

        public void Info(object message, string OrderNum, string UserName, Exception t)
        {
            if (this.IsInfoEnabled)
            {
                LoggingEvent loggingEvent = new LoggingEvent(ThisDeclaringType, Logger.Repository, Logger.Name, Level.Info, message, t);
                loggingEvent.Properties["UserName"] = UserName;
                loggingEvent.Properties["OrderNum"] = OrderNum;
                Logger.Log(loggingEvent);
            }
        }

        public void Warn(object message, string OrderNum, string UserName)
        {
            Warn(message, OrderNum, UserName, null);
        }

        public void Warn(object message, string OrderNum, string UserName, Exception t)
        {
            LoggingEvent loggingEvent = new LoggingEvent(ThisDeclaringType, Logger.Repository, Logger.Name, Level.Warn, message, t);
            loggingEvent.Properties["UserName"] = UserName;
            loggingEvent.Properties["OrderNum"] = OrderNum;
            Logger.Log(loggingEvent);
        }

        #endregion
    }
}

扩展Manager

using log4net.Core;
using System.Reflection;
using System;

namespace Kelun.Log4Net
{
    class MyLogManager
    {
        #region Static Member Variables
        /// <summary>
        /// The wrapper map to use to hold the <see cref="MyLogImpl"/> objects
        /// </summary>
        private static readonly WrapperMap s_wrapperMap = new WrapperMap(new WrapperCreationHandler(WrapperCreationHandler));
        #endregion

        #region Constructor
        private MyLogManager() { }
        #endregion


        #region Type Specific Manager Methods

        /// <summary>
        /// Returns the named logger if it exists
        /// </summary>
        /// <remarks>
        /// <para>If the named logger exists (in the default hierarchy) then it
        /// returns a reference to the logger, otherwise it returns
        /// <c>null</c>.</para>
        /// </remarks>
        /// <param name="name">The fully qualified logger name to look for</param>
        /// <returns>The logger found, or null</returns>
        public static IMyLog Exists(string name)
        {
            return Exists(Assembly.GetCallingAssembly(), name);
        }

        /// <summary>
        /// Returns the named logger if it exists
        /// </summary>
        /// <remarks>
        /// <para>If the named logger exists (in the specified domain) then it
        /// returns a reference to the logger, otherwise it returns
        /// <c>null</c>.</para>
        /// </remarks>
        /// <param name="domain">the domain to lookup in</param>
        /// <param name="name">The fully qualified logger name to look for</param>
        /// <returns>The logger found, or null</returns>
        public static IMyLog Exists(string domain, string name)
        {
            return WrapLogger(LoggerManager.Exists(domain, name));
        }

        /// <summary>
        /// Returns the named logger if it exists
        /// </summary>
        /// <remarks>
        /// <para>If the named logger exists (in the specified assembly's domain) then it
        /// returns a reference to the logger, otherwise it returns
        /// <c>null</c>.</para>
        /// </remarks>
        /// <param name="assembly">the assembly to use to lookup the domain</param>
        /// <param name="name">The fully qualified logger name to look for</param>
        /// <returns>The logger found, or null</returns>
        public static IMyLog Exists(Assembly assembly, string name)
        {
            return WrapLogger(LoggerManager.Exists(assembly, name));
        }

        /// <summary>
        /// Returns all the currently defined loggers in the default domain.
        /// </summary>
        /// <remarks>
        /// <para>The root logger is <b>not</b> included in the returned array.</para>
        /// </remarks>
        /// <returns>All the defined loggers</returns>
        public static IMyLog[] GetCurrentLoggers()
        {
            return GetCurrentLoggers(Assembly.GetCallingAssembly());
        }

        /// <summary>
        /// Returns all the currently defined loggers in the specified domain.
        /// </summary>
        /// <param name="domain">the domain to lookup in</param>
        /// <remarks>
        /// The root logger is <b>not</b> included in the returned array.
        /// </remarks>
        /// <returns>All the defined loggers</returns>
        public static IMyLog[] GetCurrentLoggers(string domain)
        {
            return WrapLoggers(LoggerManager.GetCurrentLoggers(domain));
        }

        /// <summary>
        /// Returns all the currently defined loggers in the specified assembly's domain.
        /// </summary>
        /// <param name="assembly">the assembly to use to lookup the domain</param>
        /// <remarks>
        /// The root logger is <b>not</b> included in the returned array.
        /// </remarks>
        /// <returns>All the defined loggers</returns>
        public static IMyLog[] GetCurrentLoggers(Assembly assembly)
        {
            return WrapLoggers(LoggerManager.GetCurrentLoggers(assembly));
        }

        /// <summary>
        /// Retrieve or create a named logger.
        /// </summary>
        /// <remarks>
        /// <para>Retrieve a logger named as the <paramref name="name"/>
        /// parameter. If the named logger already exists, then the
        /// existing instance will be returned. Otherwise, a new instance is
        /// created.</para>
        /// 
        /// <para>By default, loggers do not have a set level but inherit
        /// it from the hierarchy. This is one of the central features of
        /// log4net.</para>
        /// </remarks>
        /// <param name="name">The name of the logger to retrieve.</param>
        /// <returns>the logger with the name specified</returns>
        public static IMyLog GetLogger(string name)
        {
            return GetLogger(Assembly.GetCallingAssembly(), name);
        }

        /// <summary>
        /// Retrieve or create a named logger.
        /// </summary>
        /// <remarks>
        /// <para>Retrieve a logger named as the <paramref name="name"/>
        /// parameter. If the named logger already exists, then the
        /// existing instance will be returned. Otherwise, a new instance is
        /// created.</para>
        /// 
        /// <para>By default, loggers do not have a set level but inherit
        /// it from the hierarchy. This is one of the central features of
        /// log4net.</para>
        /// </remarks>
        /// <param name="domain">the domain to lookup in</param>
        /// <param name="name">The name of the logger to retrieve.</param>
        /// <returns>the logger with the name specified</returns>
        public static IMyLog GetLogger(string domain, string name)
        {
            return WrapLogger(LoggerManager.GetLogger(domain, name));
        }

        /// <summary>
        /// Retrieve or create a named logger.
        /// </summary>
        /// <remarks>
        /// <para>Retrieve a logger named as the <paramref name="name"/>
        /// parameter. If the named logger already exists, then the
        /// existing instance will be returned. Otherwise, a new instance is
        /// created.</para>
        /// 
        /// <para>By default, loggers do not have a set level but inherit
        /// it from the hierarchy. This is one of the central features of
        /// log4net.</para>
        /// </remarks>
        /// <param name="assembly">the assembly to use to lookup the domain</param>
        /// <param name="name">The name of the logger to retrieve.</param>
        /// <returns>the logger with the name specified</returns>
        public static IMyLog GetLogger(Assembly assembly, string name)
        {
            return WrapLogger(LoggerManager.GetLogger(assembly, name));
        }

        /// <summary>
        /// Shorthand for <see cref="LogManager.GetLogger(string)"/>.
        /// </summary>
        /// <remarks>
        /// Get the logger for the fully qualified name of the type specified.
        /// </remarks>
        /// <param name="type">The full name of <paramref name="type"/> will 
        /// be used as the name of the logger to retrieve.</param>
        /// <returns>the logger with the name specified</returns>
        public static IMyLog GetLogger(Type type)
        {
            return GetLogger(Assembly.GetCallingAssembly(), type.FullName);
        }

        /// <summary>
        /// Shorthand for <see cref="LogManager.GetLogger(string)"/>.
        /// </summary>
        /// <remarks>
        /// Get the logger for the fully qualified name of the type specified.
        /// </remarks>
        /// <param name="domain">the domain to lookup in</param>
        /// <param name="type">The full name of <paramref name="type"/> will 
        /// be used as the name of the logger to retrieve.</param>
        /// <returns>the logger with the name specified</returns>
        public static IMyLog GetLogger(string domain, Type type)
        {
            return WrapLogger(LoggerManager.GetLogger(domain, type));
        }

        /// <summary>
        /// Shorthand for <see cref="LogManager.GetLogger(string)"/>.
        /// </summary>
        /// <remarks>
        /// Get the logger for the fully qualified name of the type specified.
        /// </remarks>
        /// <param name="assembly">the assembly to use to lookup the domain</param>
        /// <param name="type">The full name of <paramref name="type"/> will 
        /// be used as the name of the logger to retrieve.</param>
        /// <returns>the logger with the name specified</returns>
        public static IMyLog GetLogger(Assembly assembly, Type type)
        {
            return WrapLogger(LoggerManager.GetLogger(assembly, type));
        }

        #endregion

        #region Extension Handlers

        /// <summary>
        /// Lookup the wrapper object for the logger specified
        /// </summary>
        /// <param name="logger">the logger to get the wrapper for</param>
        /// <returns>the wrapper for the logger specified</returns>
        private static IMyLog WrapLogger(ILogger logger)
        {
            return (IMyLog)s_wrapperMap.GetWrapper(logger);
        }

        /// <summary>
        /// Lookup the wrapper objects for the loggers specified
        /// </summary>
        /// <param name="loggers">the loggers to get the wrappers for</param>
        /// <returns>Lookup the wrapper objects for the loggers specified</returns>
        private static IMyLog[] WrapLoggers(ILogger[] loggers)
        {
            IMyLog[] results = new IMyLog[loggers.Length];
            for (int i = 0; i < loggers.Length; i++)
            {
                results[i] = WrapLogger(loggers[i]);
            }
            return results;
        }

        /// <summary>
        /// Method to create the <see cref="ILoggerWrapper"/> objects used by
        /// this manager.
        /// </summary>
        /// <param name="logger">The logger to wrap</param>
        /// <returns>The wrapper for the logger specified</returns>
        private static ILoggerWrapper WrapperCreationHandler(ILogger logger)
        {
            return new MyLogImpl(logger);
        }

        #endregion
    }
}

配置文件及数据库建表语句

配置文件

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>

  <log4net debug="true">

    <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender" >
      <file value="testlog.txt" />
      <appendToFile value="true" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="100" />
      <rollingStyle value="Date" />
      <datePattern value="yyyy-MM-dd"/>
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%-5level %date %logger - [%message] - %property{OrderNum} - %property{UserName %newline" />
      </layout>
    </appender>


    <!-- 写入SqlServer数据库 -->
    <appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
      <!--缓存多少数据后写入数据库-->
      <bufferSize value="1" />

      <!--数据源连接类型-->
      <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />

      <!-- SQL连接字符串-->
      <!--<connectionString value="Data Source=JALENAPC;Initial Catalog=erp;integrated security=false;Persist Security Info=True;User ID=sa;Password=privacy" />-->
      <ConnectionStringName value="Kelun.Properties.Settings.ConnectionString"/>

      <!--SQL写入语句-->
      <commandText value="INSERT INTO [Loging] (logDate, logLevel, logLogger, logOrder, logMessage, logUser, logException) VALUES (@logDate, @logLevel, @logLogger, @logOrder, @logMessage ,@logUser, @logException)" />


      <!-- 写入参数 -->
      <parameter>
        <parameterName value="@logDate" />
        <dbType value="DateTime" />
        <layout type="log4net.Layout.RawTimeStampLayout" />
      </parameter>

      <parameter>
        <parameterName value="@logLevel" />
        <dbType value="String" />
        <size value="50" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%level" />
        </layout>
      </parameter>

      <parameter>
        <parameterName value="@logLogger" />
        <dbType value="String" />
        <size value="500" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%logger" />
        </layout>
      </parameter>

      <parameter>
        <parameterName value="@logOrder" />
        <dbType value="String" />
        <size value="20" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%property{OrderNum}" />
        </layout>
      </parameter>

      <parameter>
        <parameterName value="@logMessage" />
        <dbType value="String" />
        <size value="4000" />
        <!--<layout type="log4net.Layout.PatternLayout">-->
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%message" />
        </layout>
      </parameter>

      <parameter>
        <parameterName value="@logUser" />
        <dbType value="String" />
        <size value="50" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%property{UserName}" />
        </layout>
      </parameter>

      <parameter>
        <parameterName value="@logException" />
        <dbType value="String" />
        <size value="2000" />
        <layout type="log4net.Layout.ExceptionLayout" />
      </parameter>

    </appender>

    <root>
      <level value="ALL"/>
      <appender-ref ref="AdoNetAppender" />
      <appender-ref ref="RollingFileAppender" />
    </root>

    <!--<logger name="MyLogger">
      <level value="ALL"/>
      <appender-ref ref="AdoNetAppender" />
    </logger>-->

  </log4net>
</configuration>

建表语句

create table Loging (
   id                   int                  identity,
   logDate              datetime             null,
   logLevel             varchar(50)          null,
   logLogger            varchar(500)         null,
   logOrder             varchar(20)          null,
   logMessage           text                 null,
   logUser              varchar(50)          null,
   logException         text                 null,
   constraint PK_LOGING primary key (id)
)

使用

AssemblyInfo.cs 增加如下内容

// 自动配置Log4Net
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config",Watch =true)]
private static readonly IMyLog logger = MyLogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

logger.Debug("只有消息的输出");
logger.Debug("日志内容", "OrderNum", "Jalena");
logger.Warn("Warn.......","OrderNum","Jalena");
logger.Error("Error...", "order..", "王麻子", new Exception("异常信息"));

最后来个数据库最终数据

C# SqlBulkCopy 批量写入数据

最近在写 一个项目,数据来自WebService,然后插入数据库。但在写入库的时候总是报错,所以记录下!

XMl转DataTable

/// <summary>
/// XMLNode转DataTable
/// </summary>
/// <param name="Data">XMLNode节点</param>
/// <param name="xpath">Xpath</param>
/// <returns></returns>
public static DataTable GetDataTable(XmlNode Data, string xpath)
{
	XmlNodeList xmlRows = Data.SelectNodes(xpath);
	if ((xmlRows == null) || (xmlRows.Count == 0)) return null;

	DataTable dt = new DataTable();
	foreach (XmlNode xmlColumn in xmlRows[0].ChildNodes)
	{
		if (xmlColumn.Name.ToLower() != "locators")
		{
			dt.Columns.Add(xmlColumn.Name);
		}
		else
		{
			foreach (XmlNode loc in xmlColumn.SelectSingleNode("locator").ChildNodes)
			{
				dt.Columns.Add(loc.Name);
			}
		}
	}

	foreach (XmlNode xmlRow in xmlRows)
	{
		DataRow dr = dt.NewRow();
		foreach (XmlNode xmlColumn in xmlRow.ChildNodes)
		{
			if (xmlColumn.Name.ToLower() != "locators")
			{
				dr[xmlColumn.Name] = xmlRow[xmlColumn.Name].InnerText;
			}
			else
			{
				foreach (XmlNode loc in xmlColumn.SelectSingleNode("locator").ChildNodes)
				{
					dr[loc.Name] = xmlRow.SelectSingleNode(@"locators/locator/" + loc.Name).InnerText;
				}
			}
		}
		dt.Rows.Add(dr);
	}
	dt.AcceptChanges();

	return dt;
}

获取XML所有的单据行封装成DataTable

/// <summary>
/// XMLNodeList 转 DataTable
/// </summary>
/// <param name="xmlNodeList">xmlNodeList</param>
/// <param name="xpath">xpath</param>
/// <returns></returns>
public static DataTable GetDataTable(XmlNodeList xmlNodeList,string xpath)
{
	if (xmlNodeList.Count == 0 || string.IsNullOrEmpty(xpath))
		return null;

	DataTable dataTable = new DataTable();
	foreach (XmlElement item in xmlNodeList[0].ChildNodes)
	{
		dataTable.Columns.Add(item.Name.ToLower());
	}

	foreach (XmlNode item in xmlNodeList)
	{
		DataRow dataRow = dataTable.NewRow();
		foreach (XmlElement xmlelement in item.ChildNodes)
		{
			dataRow[xmlelement.Name] = xmlelement.InnerText;
		}
		dataTable.Rows.Add(dataRow);
	}
	dataTable.AcceptChanges();
	return dataTable;
}

批量插入数据

使用SqlBulkCopy的时候,它不是按照DataColumn的名称来对照数据库列名称的,它是按照DataTable的顺序来对应数据库列。所以一定要注意。若DataTable的列与数据库列不对应,可以使用ColumnMappings来建立对应关系。

public static void Insert(DataTable dataTable,string TableName)
{
	try
	{
		using (SqlConnection Connection = new SqlConnection(connectionString))
		{
			if (Connection.State != ConnectionState.Open)
				Connection.Open();

			using(SqlTransaction transaction = Connection.BeginTransaction())
			{
				using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(Connection, SqlBulkCopyOptions.Default, transaction))
				{
					sqlBulkCopy.BatchSize = dataTable.Rows.Count;
					sqlBulkCopy.DestinationTableName = TableName;

					// 映射表关系
					foreach (DataColumn column in dataTable.Columns)
					{
						sqlBulkCopy.ColumnMappings.Add(new SqlBulkCopyColumnMapping(column.ColumnName, column.ColumnName));
					}

					try
					{
						sqlBulkCopy.WriteToServer(dataTable);
						transaction.Commit();
					}
					catch (Exception)
					{
						transaction.Rollback();
						throw;
					}
					finally
					{
						Connection.Close();
					}
				}
			}
		}
	}
	catch (Exception)
	{
		throw;
	}
}