Summary of coding tips and tips used in recent development projects

Source: Internet
Author: User

Summary of coding tips and tips used in recent development projects

1. by default, the connection string generated by EF is long and weird. To connect to EF using a common connection string, you can create a branch class and override a constructor, in the constructor, You can dynamically concatenate EntityConnectionString to obtain the connection string required by EF. The Code is as follows:

    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];        }    }

Note that the preceding class is a partial class: partial, and the BuildEntityConnectionString method is a static method. In the BuildEntityConnectionString method, ProviderConnectionString = EncryptUtility. desDecrypt ("XXXXX", connStrSetting. connectionString); it is the key. Here I have encrypted all the connection strings in config, so I need to decrypt it. If this is not required, you can directly: ProviderConnectionString = connStrSetting. connectionString. When instantiating an EF context object, you can use the following connName to construct the meaning: DataEntities (string connName). DataEntities is a specific EF context object. You can use different EF context class names.

2. Support XML serialization of a Common Object (that is, a class contains variable type attribute members, requiring different sequence results and generating different sequence element names). The specific implementation code is as follows:

A class to be serialized into XML: The generated XML Element detail must have a child element, and the child element name and the internal attributes of the child element vary according to the type (I .e: the child element under the detail element is variable)

[XmlRootAttribute ("master")] public class DemoMaster <T> where T: class {[XmlElement ("attr")] public string DemoAttr {get; set ;} [XmlElement ("detail")] public DemoDetail <T> DemoDetail {get; set;} // The key point is here. The attribute element is detail, but its sub-elements vary according to 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 ;}}

Note that in the code above, you need to pay attention to the DemoDetail attribute and DemoDetail <T> class. The DemoDetail attribute is only used to generate the detail element node, the subnode is generated by the DemoDetail <T> class. The DemoDetail <T> implements the IXmlSerializable interface. During XML serialization, the DemoDetail <T> class only serializes the content of the T-type instance corresponding to the body attribute (WriteRaw). During deserialization, the T-type instance corresponding to the body attribute is deserialized first, and then assign the value to the body attribute. This is also clever. The DemoDetail <T> class itself is not actually involved in serialization, so the serialized string cannot see the elements related to the DemoDetail <T> class, the DemoDetail <T> class is only an intermediary generated by the XML serialization format. The serialized XML results are as follows:

Serialization code:

            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 += "\r\n" + XmlHelper.XmlSerialize(demo2, Encoding.UTF8);            textBox1.Text += "\r\n" + XmlHelper.XmlSerialize(demo3, Encoding.UTF8);

Serialized 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: Display and edit specified columns in Password box mode, and bind columns to composite attributes (that is, bind columns to multi-level attributes). The specific implementation code is as follows:

DataGridView1.CellFormatting + = new Preview (maid); maid + = new Preview (maid 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 (maid [e. columnIndex]. dataPropertyName. contains (". ") {e. value = EvaluateValue (maid [e. rowIndex]. dataBoundItem, maid [e. columnInde X]. DataPropertyName);} if (maid [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; }}// example: the bound source data class defines 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 ;}}

Bind to Data source:

            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;

To display and edit a specified column in Password box mode, and bind the column to a composite attribute, you must subscribe to the CellFormatting and EditingControlShowing events of the DataGridView, and write and convert the Value of the current Cell, to bind a column to a composite attribute, the key point is the EvaluateValue method. The logic of this method is very simple, that is, according to the bound attribute level (. to obtain the value of an attribute. If the traversal is complete or empty, the result is the value of the bound attribute. The final effect is shown in:

  

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.