近期开发项目中用到的编码小技巧汇总说明

图片 2

1.默许EF生成的连续几天字符串相比较的长和奇特,若想选取普通的总是字符串来连接EF,则能够经过创立分项目,同样重视写二个构造函数,在构造函数中通过动态拼接EntityConnectionString拿到EF所需的三番五次字符串,具代实今世码如下:

    public partial class DataEntities
    {
        private static ConcurrentDictionary<string, string> entityConnStrings = new ConcurrentDictionary<string, string>();

        public DataEntities(string connName)
            : base(BuildEntityConnectionString(connName))
        {

        }

        private static string BuildEntityConnectionString(string connName)
        {

            if (!entityConnStrings.ContainsKey(connName))
            {
                var connStrSetting = System.Configuration.ConfigurationManager.ConnectionStrings[connName];

                EntityConnectionStringBuilder entityConnStrBuilder = new EntityConnectionStringBuilder();
                entityConnStrBuilder.Provider = connStrSetting.ProviderName;
                entityConnStrBuilder.ProviderConnectionString = EncryptUtility.DesDecrypt("XXXXX", connStrSetting.ConnectionString);
                entityConnStrBuilder.Metadata = "res://*/Data.csdl|res://*/Data.ssdl|res://*/Data.msl";
                string entityConnString = entityConnStrBuilder.ToString();
                entityConnStrings.AddOrUpdate(connName, entityConnString, (key, value) => entityConnString);
            }
            return entityConnStrings[connName];
        }
    }

注意上边的类是二个根据地类:partial,同时BuildEntityConnectionString方法是三个静态方法,在BuildEntityConnectionString方法中ProviderConnectionString
= EncryptUtility.DesDecrypt(“XXXXX”,
connStrSetting.ConnectionString);是最主要,作者那边是对config中的连接字符串
也都进行了加密,故此处作者索要解密,若无这些需要能够直接:ProviderConnectionString
=connStrSetting.ConnectionString就能够。后续实例化EF上下文对象时,请使用:DataEntities(string
connName)那几个组织涵数就可以,DataEntities是现实性的EF上下文对象,大家的EF上下文类名均可能差别样。

2.协助叁个通用对象的XML系列化(即:多个类中有可变类型属性成员,供给分歧的种类结果及变化分裂的行列成分名称卡塔 尔(阿拉伯语:قطر‎,具体贯彻代码如下:

叁个急需被体系化成XML的类:当中要求调换的XML成分detail必须有子成分,且子成分名称及子成分内部属性依照项指标两样而分裂(即:detail成分下的子成分是可变的卡塔尔国

    [XmlRootAttribute("master")]
    public class DemoMaster<T> where T : class
    {
        [XmlElement("attr")]
        public string DemoAttr { get; set; }

        [XmlElement("detail")]
        public DemoDetail<T> DemoDetail { get; set; } //关键点在这里,该属性元素为:detail,但其子元素根据T不同而不同

    }
    public class DemoDetail<T> : IXmlSerializable where T : class
    {
        public T body { get; set; }

        public System.Xml.Schema.XmlSchema GetSchema()
        {
            return null;
        }

        public void ReadXml(System.Xml.XmlReader reader)
        {
            string bodyStr = reader.ReadInnerXml();
            this.body = XmlHelper.XmlDeserialize<T>(bodyStr, Encoding.UTF8);
        }

        public void WriteXml(System.Xml.XmlWriter writer)
        {
            writer.WriteRaw(XmlHelper.XmlSerialize(this.body, Encoding.UTF8, true));
        }
    }

    [XmlTypeAttribute("list-a", AnonymousType = false)]
    public class DemoDetailA
    {
        public string Apro1 { get; set; }

        public string Apro2 { get; set; }

        public string Apro3 { get; set; }
    }

    [XmlTypeAttribute("list-b", AnonymousType = false)]
    public class DemoDetailB
    {
        public string Bpro1 { get; set; }

        public string Bpro2 { get; set; }

        public string Bpro3 { get; set; }
    }

    [XmlTypeAttribute("list-c", AnonymousType = false)]
    public class DemoDetailC
    {
        public string Cpro1 { get; set; }

        public string Cpro2 { get; set; }

        public string Cpro3 { get; set; }
    }

留意上边代码中,要求关怀:德姆oDetail属性及德姆oDetail<T>类,德姆oDetail属性仅是为着生成detail元九秋点,而子节点则由德姆oDetail<T>类来开展调换,德姆oDetail<T>是贯彻了IXmlSerializable接口,在XML连串化时,德姆oDetail<T>类仅将body属性对应的T类型实例内容展开序列化(WriteRaw卡塔尔国,而反系列化时,则先反连串化body属性对应的T类型实例,然后赋值给body属性,那也是高强之处,德姆oDetail<T>类本人并从未真的加入到连串化中,故类别化的字符串也看不到德姆oDetail<T>类相关的要素,DemoDetail<T>类仅仅是八个XML连串化格式生成的中介。连串化的XML结果如下:

类别化代码:

            var demo1 = new DemoMaster<DemoDetailA>()
            {
                DemoAttr = "demo1",
                DemoDetail = new DemoDetail<DemoDetailA>() { body = new DemoDetailA() { Apro1 = "demoA1", Apro2 = "demoA2", Apro3 = "demoA3" } }
            };

            var demo2 = new DemoMaster<DemoDetailB>()
            {
                DemoAttr = "demo2",
                DemoDetail = new DemoDetail<DemoDetailB>() { body = new DemoDetailB() { Bpro1 = "demoB1", Bpro2 = "demoB2", Bpro3 = "demoB3" } }
            };

            var demo3 = new DemoMaster<DemoDetailC>()
            {
                DemoAttr = "demo3",
                DemoDetail = new DemoDetail<DemoDetailC>() { body = new DemoDetailC() { Cpro1 = "demoC1", Cpro2 = "demoC2", Cpro3 = "demoC3" } }
            };

            textBox1.Text = XmlHelper.XmlSerialize(demo1, Encoding.UTF8);

            textBox1.Text += "rn" + XmlHelper.XmlSerialize(demo2, Encoding.UTF8);

            textBox1.Text += "rn" + XmlHelper.XmlSerialize(demo3, Encoding.UTF8);

种类化的XML:

<?xml version="1.0" encoding="utf-8"?>
<master>
    <attr>demo1</attr>
    <detail><list-a>
    <Apro1>demoA1</Apro1>
    <Apro2>demoA2</Apro2>
    <Apro3>demoA3</Apro3>
</list-a></detail>
</master>

<?xml version="1.0" encoding="utf-8"?>
<master>
    <attr>demo2</attr>
    <detail><list-b>
    <Bpro1>demoB1</Bpro1>
    <Bpro2>demoB2</Bpro2>
    <Bpro3>demoB3</Bpro3>
</list-b></detail>
</master>

<?xml version="1.0" encoding="utf-8"?>
<master>
    <attr>demo3</attr>
    <detail><list-c>
    <Cpro1>demoC1</Cpro1>
    <Cpro2>demoC2</Cpro2>
    <Cpro3>demoC3</Cpro3>
</list-c></detail>
</master>

3.winform DataGridView
完成钦定列采用密码框格局显示与编写制定,以致列绑定到复合属性(即:绑定到多档期的顺序属性卡塔 尔(英语:State of Qatar)
,具体得以达成代码如下:

            dataGridView1.CellFormatting += new DataGridViewCellFormattingEventHandler(dataGridView1_CellFormatting);
            dataGridView1.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(dataGridView1_EditingControlShowing);


        public string EvaluateValue(object obj, string property)
        {
            string retValue = string.Empty;
            string[] names = property.Split('.');

            for (int i = 0; i < names.Count(); i++)
            {
                try
                {
                    var prop = obj.GetType().GetProperty(names[i]);
                    var result = prop.GetValue(obj, null);
                    if (result != null)
                    {
                        obj = result;
                        retValue = result.ToString();
                    }
                    else
                    {
                        break;
                    }
                }
                catch (Exception)
                {
                    throw;
                }
            }

            return retValue;
        }


        private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {

            if (dataGridView1.Columns[e.ColumnIndex].DataPropertyName.Contains("."))
            {
                e.Value = EvaluateValue(dataGridView1.Rows[e.RowIndex].DataBoundItem, dataGridView1.Columns[e.ColumnIndex].DataPropertyName);
            }


            if (dataGridView1.Columns[e.ColumnIndex].Name == "KeyCode")
            {
                if (e.Value != null && e.Value.ToString().Length > 0)
                {
                    e.Value = new string('*', e.Value.ToString().Length);
                }
            }
        }

        private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            int i = this.dataGridView1.CurrentCell.ColumnIndex;
            bool usePassword = false;
            if (dataGridView1.Columns[i].Name == "KeyCode")
            {
                usePassword = true;
            }
            TextBox txt = e.Control as TextBox;
            if (txt != null)
            {
                txt.UseSystemPasswordChar = usePassword;
            }
        }

//示例:绑定的源数据类定义
    public class DemoBindClass
    {
        public string Attr { get; set; }

        public string KeyCode { get; set; }

        public DemoDetailA Detail { get; set; }
    }


    public class DemoDetailA
    {
        public string Apro1 { get; set; }

        public string Apro2 { get; set; }

        public string Apro3 { get; set; }

        public DemoDetailB DetailChild { get; set; }
    }


    public class DemoDetailB
    {
        public string Bpro1 { get; set; }

        public string Bpro2 { get; set; }

        public string Bpro3 { get; set; }
    }

绑定到数据源:

            var demo = new[] {
                new DemoBindClass()
                    {
                        Attr = "demo",
                        KeyCode="a123456789b",
                        Detail = new DemoDetailA()
                        {
                            Apro1 = "demoA1",
                            Apro2 = "demoA2",
                            Apro3 = "demoA3",
                            DetailChild = new DemoDetailB()
                            {
                                Bpro1 = "demoB1",
                                Bpro2 = "demoB2",
                                Bpro3 = "demoB3"
                            }
                        }
                    }
            };


            dataGridView1.AutoGenerateColumns = false;
            dataGridView1.DataSource = demo;

完成钦命列选择密码框情势呈现与编写制定,以至列绑定到复合属性均要求订阅DataGridView的CellFormatting及EditingControlShowing事件,并在其间写调换当前Cell的Value,达成列绑定到复合属性,关键点在:EvaluateValue方法,该办法逻辑很简短,就是基于绑定的习性层级(.分隔卡塔 尔(阿拉伯语:قطر‎层层遍历获取属性的值,直到遍历完或为空时结束,最后获得的结果便是绑定的质量的值。最后兑现的效果如下图示:

图片 1

4.选择BCP(sqlbulkcopy卡塔 尔(阿拉伯语:قطر‎来完结多个例外数据库之间张开数据差距传输(即:数据同步卡塔尔国

TransferBulkCopy成效:达成七个例外数据库之间张开数据差距传输,BuildInsertOrUpdateToDestTableSql功用:依据指标表及有的时候表生成更新与插入记录的SQL语句,以此达成:若同步的数额已存在,则更新,不设有,则插入。

        /// <summary>
        /// 通用数据传输方法(采用SqlBulkCopy快速批量插入,然后再进行处理)
        /// </summary>
        /// <param name="sourceSelectSql"></param>
        /// <param name="sourceConn"></param>
        /// <param name="destTableName"></param>
        /// <param name="destConn"></param>
        /// <param name="colMapFunc"></param>
        /// <param name="lastSaveAction"></param>
        public void TransferBulkCopy(string sourceSelectSql, SqlConnection sourceConn, string destTableName, SqlConnection destConn, Func<DataTable, Dictionary<string, string>> colMapFunc,
                                    Func<string, DataTable, SqlConnection, SqlConnection, bool> lastSaveAction, bool closeConnection = true)
        {
            DataTable srcTable = new DataTable();
            SqlDataAdapter srcAdapter = new SqlDataAdapter(sourceSelectSql, sourceConn);
            srcAdapter.AcceptChangesDuringUpdate = false;
            SqlCommandBuilder srcCmdBuilder = new SqlCommandBuilder(srcAdapter);
            srcAdapter.Fill(srcTable);

            if (srcTable != null && srcTable.Rows.Count > 0)
            {
                string tempDestTableName = "#temp_" + destTableName;
                ClsDatabase.gExecCommand(destConn, string.Format("select top 0 * into {0}  from  {1}", tempDestTableName, destTableName), false);
                List<string> mapDestColNameList = new List<string>();
                using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(destConn))
                {
                    sqlBulkCopy.DestinationTableName = tempDestTableName;
                    foreach (var map in colMapFunc(srcTable))
                    {
                        sqlBulkCopy.ColumnMappings.Add(map.Key, map.Value);
                        mapDestColNameList.Add(map.Value);
                    }
                    sqlBulkCopy.WriteToServer(srcTable);
                }
                srcTable.ExtendedProperties.Add(MapDestColNames_String, mapDestColNameList);
                bool needUpdate = lastSaveAction(tempDestTableName, srcTable, destConn, sourceConn);

                if (needUpdate)
                {
                    if (srcTable.Columns.Contains("TranFlag"))
                    {
                        foreach (DataRow row in srcTable.Rows)
                        {
                            row["TranFlag"] = true;
                        }
                    }
                    srcAdapter.Update(srcTable);
                }

            }

            if (closeConnection)
            {
                DisposeConnections(sourceConn, destConn);
            }
        }

 

        /// <summary>
        /// 生成同步插入及更新目的表SQL语句
        /// </summary>
        /// <param name="destTableName"></param>
        /// <param name="tempdestTableName"></param>
        /// <param name="pkWhereColNames"></param>
        /// <param name="mapDestColNames"></param>
        /// <param name="sqlType">0=生成INSERT与UPDATE;1=生成UPDATE语句;2=生成INSERT语句</param>
        /// <returns></returns>
        public string BuildInsertOrUpdateToDestTableSql(string destTableName, string tempdestTableName, string[] pkWhereColNames, object mapDestColNames, int sqlType = 0)
        {
            var mapDestColNameList = mapDestColNames as List<string>;
            string updateColNames = null;
            foreach (string col in mapDestColNameList)
            {
                if (!pkWhereColNames.Contains(col, StringComparer.OrdinalIgnoreCase))
                {
                    updateColNames += string.Format(",{0}=tnew.{0}", col);
                }
            }
            updateColNames = updateColNames.Substring(1);
            string insertColNames = string.Join(",", mapDestColNameList);

            string pkWhereSql = null;
            foreach (string col in pkWhereColNames)
            {
                pkWhereSql += string.Format(" and told.{0}=tnew.{0} ", col);
            }
            pkWhereSql = pkWhereSql.Trim().Substring(3);

            StringBuilder sqlBuilder = new StringBuilder();

            if (sqlType == 0 || sqlType == 1)
            {
                sqlBuilder.AppendFormat("UPDATE {0}  SET {1} FROM {0} told INNER JOIN {2} tnew ON {3}  " + Environment.NewLine,
                                        destTableName, updateColNames, tempdestTableName, pkWhereSql);
            }

            if (sqlType == 0 || sqlType == 2)
            {
                sqlBuilder.AppendFormat("INSERT INTO {0}({1}) SELECT {1} FROM {2} tnew WHERE NOT EXISTS(SELECT 1 FROM {0} told WHERE {3}) " + Environment.NewLine,
                                        destTableName, insertColNames, tempdestTableName, pkWhereSql);

            }

            return sqlBuilder.ToString();

        }

  

 

行使示举例下:

        public void SendData_CustomerAuthorization()
        {
            try
            {
                SqlConnection obConnLMS1 = new SqlConnection(master.connLMSStr);
                SqlConnection obConnWEB1 = new SqlConnection(master.connWEBStr);

                string selectSql = @"SELECT TOP {0} Id,Phone,Mac,IsSet,LastLoginTime,PCName,TranFlag FROM TWEB_CustomerAuthorization WHERE TranFlag=0 ORDER BY Id ";

                selectSql = string.Format(selectSql, master.batchSize);

                master.TransferBulkCopy(selectSql, obConnWEB1,
                                "TB_CustomerAuthorization", obConnLMS1,
                                 (stable) =>
                                 {
                                     var colMaps = new Dictionary<string, string>();
                                     foreach (DataColumn col in stable.Columns)
                                     {
                                         if (!col.ColumnName.Equals("TranFlag", StringComparison.OrdinalIgnoreCase))
                                         {
                                             colMaps.Add(col.ColumnName, col.ColumnName);
                                         }
                                     }
                                     return colMaps;
                                 },
                                 (tempTableName, stable, destConn, srcConn) =>
                                 {
                                     StringBuilder saveSqlBuilder = new StringBuilder("begin tran" + Environment.NewLine);

                                     string IUSql = master.BuildInsertOrUpdateToDestTableSql("TB_CustomerAuthorization", tempTableName, new[] { "Id" }, stable.ExtendedProperties[master.MapDestColNames_String]);
                                     saveSqlBuilder.Append(IUSql);

                                     saveSqlBuilder.AppendLine("commit");

                                     ClsDatabase.gExecCommand(destConn, saveSqlBuilder.ToString());

                                     master.WriteMsg(master.lstSended, string.Format("上传时间:{0:yyyy-MM-dd HH:mm}t SendData_CustomerAuthorization t Succeed:{1}", DateTime.Now, stable.Rows.Count));

                                     return true;

                                 });
            }
            catch (Exception ex)
            {
                master.WriteMsg(master.lstErrorInfo, DateTime.Now.ToString("yyyy-MM-dd HH:mm") + "t" + "SendData_CustomerAuthorization" + "t" + ex.Message.ToString());
            }
        }

贰只原理如下:

4.1.定义好查询源服务器的急需一块的表(日常表中大家定义贰个用以是否同步的标志字段,如:TranFlag
Bit类型,0象征新数据,未协同,1代表已联手卡塔尔;

4.2.查询源服务器的内需一块的表的笔录(经常是TranFlag=0的记录卡塔 尔(英语:State of Qatar),利用SqlDataAdapter+SqlCommandBuilder
装载Dataset,指标是持续能够行使SqlDataAdapter直接生成更新命令并进行;

4.3.行使insert
into从指标服务器的将被一道的表复制结构发生一个有的时候表,表名日常是:#temp_目的服务器的将被同步表名
,那样不时表与实体表的布局完全生龙活虎致;

4.4.实例化叁个SqlBulkCopy,并确立源服务器的急需一块的表字段与指标不常表字段的映射,然后推行跨过服务器务器传输;

4.5.接受 BuildInsertOrUpdateToDestTableSql 方法 ,生成
 指标服务器的将被生机勃勃并的表 与
不常表的插入与更新SQL语句(今后在同一个库了,想怎么用SQL语句均可卡塔 尔(英语:State of Qatar)  

4.6.为保险大器晚成致性,故外层还需包裹事务SQL语句,若还需参预其余管理SQL,能够加在begin
tran  …
commit代码块中即可,最终实践SQL语句:gExecCommand(ClsDatabase.gExecCommand是三个SQLDB
HELPECR-V 类的推行SQL命令的主意卡塔尔

 

5.达成同多少个WINDOWS SE君越VICE程序
COPY多份,然后通过转移自定义的服务ID(ServiceID)配置项来促成:同一个服务程序安装成五个不一致的WINDOWS服务进程:

5.1.开立多少个WINDOWS服务项目,在ProjectInstaller设计器分界面通过右键弹出美食指南选用安装程序(serviceProcessInstaller1、serviceInstaller1卡塔 尔(英语:State of Qatar)、并设置好ServiceName、DisplayName、Description、Account等,如下图示:

图片 2

5.2.在ProjectInstaller构造函数中追加从CONFIG文件中读取自定义的服务ID(ServiceID)配置项的值,然后将ServiceID拼加到预设的瑟维斯Name前边,以便实际依据ServiceID能够设置成差别ServiceID后缀的劳动进度,关键点在于退换ServiceName,另多个关键点是从CONFIG文件中得到ServiceID,由于设置时,古板的点子无法寻常读取到CONFIG,只好通过Assembly.GetExecutingAssembly().Location
来获取当前实施的主次集的不二等秘书籍再拼成CONFIG文件路线,最终读出ServiceID的值,示例代码如下:

    public partial class ProjectInstaller : System.Configuration.Install.Installer
    {
        public ProjectInstaller()
        {
            InitializeComponent();

            string assyLocation = System.Reflection.Assembly.GetExecutingAssembly().Location;
            string assyCfgPath = assyLocation + ".config";
            string installServiceLogPath = Path.Combine(Path.GetDirectoryName(assyLocation), "InstallServiceLog.log");

            string serviceID = ConfigUtil.GetAppSettingValueForConfigPath("ServiceID", assyCfgPath);

            System.IO.File.AppendAllText(installServiceLogPath, string.Format("[{0:yyyy-MM-dd HH:mm:ss}] ServiceAssembly ConfigPath:{1};rn", DateTime.Now, assyCfgPath));

            if (!string.IsNullOrWhiteSpace(serviceID))
            {
                this.serviceInstaller1.DisplayName = "TestService_" + serviceID;
                this.serviceInstaller1.ServiceName = "TestService_" + serviceID;
            }

            System.IO.File.AppendAllText(installServiceLogPath, string.Format("[{0:yyyy-MM-dd HH:mm:ss}] ProjectInstaller.ProjectInstaller() ->ServiceID:{1},ServiceName:{2}; rn", DateTime.Now, serviceID, this.serviceInstaller1.ServiceName));
        }
    }

5.3.在服务类的构造函数中后生可畏致扩大从CONFIG中读取自定义的劳务ID(ServiceID)配置项的值,然后将ServiceID拼加到预设的ServiceName后边(注意应与上述ProjectInstaller中钦定的ServiceName雷同卡塔 尔(阿拉伯语:قطر‎,示例代码如下:  

public partial class TestService: ServiceBase
{
     public TestService()
    {
          serviceID = ConfigUtil.GetAppSettingValue("ServiceID");
            if (!string.IsNullOrWhiteSpace(serviceID))
            {
                this.ServiceName = "TestService_" + serviceID;
            }
    }

}

 上述三步就成功了同叁个服务程序安装成八个例外的WINDOWS服务进度,那几个依旧比较实用的啊!上述ConfigUtil是包裹的二个安插文件读写帮助类,早前小说有介绍,后边也会公布贰个更完整的ConfigUtil类。

发表评论

电子邮件地址不会被公开。 必填项已用*标注