public PropertyItem(string inName) { property = new CodeMemberProperty(); property.HasGet = false; property.HasSet = false; property.Name = Assist.FirstLetterLower(inName); }
public void SetValue(XmlAttributeCollection inValue) { constructList.Add(new ConstructItem()); // 构造函数 ConstructItem construct = new ConstructItem(new List <string>() { "System.String" }); construct.Struct.Statements.Add(Line("string[] ss", "inArg0.Split(\'^\')")); classer.CustomAttributes.Add(new CodeAttributeDeclaration("ProtoContract")); for (int i = 0; i < inValue.Count; i++) { fieldList.Add(new FieldItem(inValue[i].Name, inValue[i].Value, MemberAttributes.Private)); PropertyItem item = new PropertyItem(inValue[i].Name); item.SetGetName(); item.SetSetName(); item.SetValueType(inValue[i].Value); item.SetModifier(MemberAttributes.Public | MemberAttributes.Final); item.SetField("ProtoMember", (i + 1).ToString()); propertyList.Add(item); Type t = (Type)Assist.stringToType(inValue[i].Value); string right = t == typeof(System.String) ? "ss[" + i + "]" : t == typeof(System.UInt32) ? "uint.Parse(ss[" + i + "])" : t == typeof(System.Single) ? "float.Parse(ss[" + i + "])" : "new " + t.ToString() + "(inValues[" + i + "])"; construct.Struct.Statements.Add(Line("_" + Assist.FirstLetterLower(inValue[i].Name), right)); } constructList.Add(construct); Create(); }
/// <summary> /// 字段 /// </summary> /// <param name="inName">字段名</param> /// <param name="inType">字段类型</param> /// <param name="inAtt">访问修饰符</param> public FieldItem(string inName, string inType, MemberAttributes inAtt) { object objType = Assist.stringToType(inType); if (objType is string) { field = new CodeMemberField((string)objType, "m_" + Assist.FirstLetterLower(inName)); } else { field = new CodeMemberField((Type)objType, "m_" + Assist.FirstLetterLower(inName)); if (Assist.isArray(inType)) { field.Type.BaseType = "List"; } } field.Attributes = inAtt; }
/// <summary> /// Set属性 /// </summary> /// <param name="inName"></param> public void SetSetName(string inName = "") { string s = inName == "" ? property.Name : inName; property.HasSet = true; property.SetStatements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "m_" + Assist.FirstLetterLower(s)), new CodePropertySetValueReferenceExpression())); }
/// <summary> /// Get属性 /// </summary> /// <param name="inName"></param> public void SetGetName(string inName = "", bool bKeyGet = false) { string s = inName == "" ? property.Name : inName; property.HasGet = true; if (bKeyGet == false) { property.GetStatements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "m_" + Assist.FirstLetterLower(s)))); } else { CodeSnippetStatement state = new CodeSnippetStatement(inName); property.GetStatements.Add(state); } }
/// <summary> /// Excel -> 二进制文件 /// </summary> /// <param name="inPath"></param> /// <param name="inFolderName"></param> /// <param name="suffixName"></param> /// <returns></returns> public bool Bin(string inPath, string inFolderName, string suffixName) { Assist.CheckFolderExist(inFolderName); //PBData data = new PBData(); //modify by wukun 2015/10/28 //PBData需要用到的类都是动态生成的 无需每次添加的时候添加进工程重新编译exe //类的cs文件必须放在exe文件根目录的/ExcelfieldStrs/文件夹下 Type PBDataType = AutoCSharp.Do.Creator.TypeMapper.GetTypeByName("PBData", true); object pbData = Activator.CreateInstance(PBDataType); //Test Cost Time System.Diagnostics.Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); DataSet ds; DataTable dt = null; string classname, subCfgName, subField, fieldTypeStr = "", fieldName = "", fieldStr = "", fieldMaxStr = ""; Type classType, subClassType, listType; object classObj, subClassObj, listObj, key; FieldInfo fieldInfo; IDictionary fieldValue; int column = 0, subProIndex, arrSize; PropertyInfo[] arrPro, subArrPro; bool isBaseType; Regex reg = new Regex(@"\{.+?\}"); MatchCollection matches; Type generic = typeof(List <>); string[] arrField; MethodInfo method; long maxVal; Dictionary <string, long> dicMaxValue; Assist.GetObjPaths(suffixName, inPath).ForEach(delegate(string path) { bool bExcel = true; int rowIndex = 4; if (suffixName == ".xlsx") { ds = Assist.ExcelToData(path); dt = ds.Tables[0]; } else if (suffixName == ".txt") { dt = Assist.TxtToData(path); bExcel = false; rowIndex = 5; } classname = Assist.FirstLetterUp(dt.TableName); //TODO Get Cfg Max Value dicMaxValue = new Dictionary <string, long>(); for (column = 0; column < dt.Columns.Count; column++) { if (dt.Rows[2][column].ToString().Contains("+")) { fieldName = Assist.FirstLetterLower(dt.Rows[0][column].ToString().Trim()); fieldMaxStr = dt.Rows[rowIndex][column].ToString(); maxVal = 0; if (!Regex.IsMatch(fieldMaxStr, @"\d.\d+")) { maxVal = long.Parse(fieldMaxStr); } dicMaxValue.Add(fieldName, maxVal); } } //TODO 类型的获取应该动态获取 classType = AutoCSharp.Do.Creator.TypeMapper.GetTypeByName("Cfg" + classname); fieldInfo = pbData.GetType().GetField(classname + "Dic"); fieldValue = fieldInfo.GetValue(pbData) as IDictionary; int row = 5; if (!bExcel) { row = 6; } bool bDeleted = false; try { if (classType != null) { for (; row < dt.Rows.Count; row++) { classObj = Activator.CreateInstance(classType); column = 0; if (dt.Rows[row][column].ToString() == "") { break; } arrPro = classType.GetProperties(); foreach (PropertyInfo pro in arrPro) { fieldName = pro.Name; if (fieldName == "mkey") { continue; } fieldStr = dt.Rows[row][column].ToString(); isBaseType = ParseExcelField2ObjectPro(pro, classObj, fieldStr, dicMaxValue[fieldName]); if (isBaseType) { if (fieldName == "deleted") { bDeleted = (int)pro.GetValue(classObj) == 1; } } else { if (!reg.IsMatch(fieldStr)) { column++; continue; //throw new Exception("自定义结构配置错误"); } if (pro.PropertyType.Name == "List`1") { matches = reg.Matches(fieldStr); subCfgName = pro.PropertyType.GenericTypeArguments[0].Name; subClassType = AutoCSharp.Do.Creator.TypeMapper.GetTypeByName(subCfgName); listType = generic.MakeGenericType(new System.Type[] { subClassType }); listObj = Activator.CreateInstance(listType); foreach (object match in matches) { subField = match.ToString(); subField = subField.Substring(1, subField.Length - 2); subClassObj = Activator.CreateInstance(subClassType); subArrPro = subClassType.GetProperties(); arrField = subField.Split(','); arrSize = arrField.Length; subProIndex = 0; foreach (PropertyInfo subPro in subArrPro) { fieldName = subPro.Name; if (fieldName == "mkey") { continue; } if (subProIndex < arrSize) { ParseExcelField2ObjectPro(subPro, subClassObj, arrField[subProIndex++]); } } method = listType.GetMethod("Add"); method.Invoke(listObj, new object[] { subClassObj }); } pro.SetValue(classObj, listObj); } else { fieldStr = fieldStr.Substring(1, fieldStr.Length - 2); subClassType = AutoCSharp.Do.Creator.TypeMapper.GetTypeByName(pro.PropertyType.Name); subClassObj = Activator.CreateInstance(subClassType); subArrPro = subClassType.GetProperties(); arrField = fieldStr.Split(','); subProIndex = 0; foreach (PropertyInfo subPro in subArrPro) { fieldName = subPro.Name; if (fieldName == "mkey") { continue; } ParseExcelField2ObjectPro(subPro, subClassObj, arrField[subProIndex++]); } pro.SetValue(classObj, subClassObj); } } column++; } if (bDeleted == false) { PropertyInfo proInfo = classType.GetProperty("mkey"); key = proInfo.GetValue(classObj, null); fieldValue.Add(key, classObj); } } fieldInfo.SetValue(pbData, fieldValue); } } catch (Exception ex) { string errorMsg = classname + "表第" + (row + 1) + "行\n" + fieldName + "字段\n" + fieldTypeStr + "\n" + fieldStr + "\n" + ex.Message; throw new Exception(errorMsg); } }); #region //SceneLayout 读取同级目录下的“Excel/SceneLayout/”内的所有 xml 文件,并将其数据写入 PBData //Dictionary<string, XmlDocument> doc = Assist.GetXml(Assist.RootPath + "Excel/SceneLayout/"); //foreach (KeyValuePair<string, XmlDocument> fieldStr in doc) //{ // SceneLayout sl = new SceneLayout(); // XmlNodeList xcc = fieldStr.Value.SelectSingleNode("Config").ChildNodes; // for (int i = 0; i < xcc.Count; i++) // { // SceneLayoutfieldStr sli = new SceneLayoutfieldStr(); // IProtoBufable xmlfieldStrValue = new SceneLayoutfieldStr() as IProtoBufable;// value // List<string> xls = new List<string>(); // for (int x = 0; x < xcc[i].Attributes.Count; x++) // { // xls.Add(xcc[i].Attributes[x].Value); // } // xmlfieldStrValue.Set(xls); // sl.fieldStr.Add(xmlfieldStrValue as SceneLayoutfieldStr); // } // data.SceneLayoutDic.Add(fieldStr.Key, sl); //} #endregion using (var file = System.IO.File.Create("PBData")) { try { ProtoBuf.Serializer.Serialize(file, pbData); stopWatch.Stop(); double msTime = stopWatch.Elapsed.TotalMilliseconds; Console.WriteLine("耗时" + msTime); } catch (Exception e) { MainWindow.Show(e.ToString()); } } return(true); }
public void SetNodeValue(XmlNode n) { for (int i = 0; i < n.Attributes.Count; i++) { string value = n.Attributes[i].Value; //AddField(n.Attributes[i].Name, value, MemberAttributes.Private); fieldList.Add(new FieldItem(n.Attributes[i].Name, value, MemberAttributes.Private)); PropertyItem item = new PropertyItem(n.Attributes[i].Name); item.SetGetName(); item.SetValueType(value); item.SetModifier(MemberAttributes.Public | MemberAttributes.Final); propertyList.Add(item); CodeConditionStatement condition = new CodeConditionStatement(); condition.Condition = new CodeVariableReferenceExpression("inArg0.ContainsKey(\"" + n.Attributes[i].Name + "\")"); string parseLeft = ""; string parseRight = ""; if (Assist.IsNumber(value)) { parseLeft = value.Contains(".") ? "float.Parse(" : "uint.Parse("; parseRight = ")"; } CodeVariableReferenceExpression right = new CodeVariableReferenceExpression(parseLeft + "inArg0[\"" + n.Attributes[i].Name + "\"]" + parseRight); CodePropertyReferenceExpression left = new CodePropertyReferenceExpression(new CodeThisReferenceExpression(), "_" + Assist.FirstLetterLower(n.Attributes[i].Name)); if (Assist.IsNumber(value)) { CodeConditionStatement numCondition = new CodeConditionStatement(); numCondition.Condition = new CodeVariableReferenceExpression("inArg0[\"" + n.Attributes[i].Name + "\"] == \"\""); numCondition.TrueStatements.Add(new CodeAssignStatement(left, new CodeVariableReferenceExpression("0"))); numCondition.FalseStatements.Add(new CodeAssignStatement(left, right)); condition.TrueStatements.Add(numCondition); } else { condition.TrueStatements.Add(new CodeAssignStatement(left, right)); } AddConditionStatement(condition); } Create(); }
/// <summary> /// <para>0: 字段名</para> /// <para>1: a+i+0 指明类型及是否为Key值</para> /// <para>2: 注释</para> /// </summary> /// <param name="inList">0: 字段名</param> public void SetValue(string tableName, List <string[]> inList) { classer.CustomAttributes.Add(new CodeAttributeDeclaration("ProtoContract")); List <KeyValuePair <string, string> > keyList = new List <KeyValuePair <string, string> >();// key 值 string[] ss, arrContruct; string attrName, typeString, linkTable, cfgName, strListType, content, ks = "", bit = ""; MethodItem mis; CodeSnippetStatement state; PropertyItem item, keyPropertyItem; Regex rgx = new Regex(@"[\[\]]{1}"); bool isArray; for (int i = 0; i < inList.Count; i++) { arrContruct = inList[i]; if (!arrContruct[1].Contains("+")) { continue; } ss = arrContruct[1].Split('+'); attrName = Assist.FirstLetterLower(arrContruct[0]); typeString = ss[1]; string strTmp = arrContruct[3].Trim(); if (strTmp == "") { strTmp = "0"; } linkTable = Assist.FirstLetterUp(strTmp); cfgName = "Cfg" + linkTable; //link table 不指定id if (typeString == "t") { mis = new MethodItem("GetList" + cfgName, MemberAttributes.Final | MemberAttributes.Public, new List <string>() { }); SetComment("获取List<" + cfgName + ">", mis.Method); strListType = "List<" + cfgName + ">"; mis.Method.ReturnType = new CodeTypeReference(strListType); content = dicFunctions["GetListCfgNameUnAttach"]; content = content.Replace("{TableName}", linkTable); content = content.Replace("{CfgName}", cfgName); content = content.Replace("{Type}", "long"); m_linkMethodContent = content; m_linkTableName = linkTable; m_linkMethod = mis; //content = content.Replace("{MainKey}", **); //state = new CodeSnippetStatement(content); //mis.Method.Statements.Add(state); //methodList.Add(mis); continue; } //是否数组eg. [i] isArray = false; if (rgx.IsMatch(typeString)) { isArray = true; typeString = rgx.Replace(typeString, ""); } //link table 指定id if (Regex.IsMatch(linkTable, @"[a-zA-Z]+")) { //string msg = className.Substring(3) + "的" + attrName + "第四列要把浮点数改成0"; //System.Windows.MessageBox.Show(msg); if (isArray) { mis = new MethodItem("GetList" + cfgName, MemberAttributes.Final | MemberAttributes.Public, new List <string>() { }); SetComment("获取List<" + cfgName + ">", mis.Method); strListType = "List<" + cfgName + ">"; mis.Method.ReturnType = new CodeTypeReference(strListType); content = dicFunctions["GetListCfgNameInArray"]; content = content.Replace("{TableName}", linkTable); content = content.Replace("{CfgName}", cfgName); content = content.Replace("{Param}", attrName); content = content.Replace("{Type}", "int"); state = new CodeSnippetStatement(content); mis.Method.Statements.Add(state); methodList.Add(mis); } else { mis = new MethodItem("Get" + cfgName, MemberAttributes.Final | MemberAttributes.Public, new List <string>() { }); SetComment("获取" + cfgName, mis.Method); mis.Method.ReturnType = new CodeTypeReference(cfgName); content = dicFunctions["GetCfgName"]; content = content.Replace("{TableName}", linkTable); content = content.Replace("{Param}", attrName); state = new CodeSnippetStatement(content); mis.Method.Statements.Add(state); methodList.Add(mis); } } fieldList.Add(new FieldItem(arrContruct[0], arrContruct[1], MemberAttributes.Private)); item = new PropertyItem(arrContruct[0]); item.SetGetName(); item.SetSetName(); item.SetComment(arrContruct[2]); item.SetValueType(arrContruct[1]); item.SetModifier(MemberAttributes.Public | MemberAttributes.Final); item.SetField("ProtoMember", (i + 1).ToString()); propertyList.Add(item); if (ss[2] == "1")// 如果该属性是类的Key值,则加入列表 { if (m_mainKey == null) { m_mainKey = attrName; } string strType = item.Property.Type.BaseType; if (strType == "System.Int32" || strType == "System.Int64") { string[] arrType = arrContruct[1].Split('+'); string keyBit = ""; if (arrType.Length == 4) { keyBit = arrType[3]; } keyList.Add(new KeyValuePair <string, string>(attrName, keyBit)); } else { throw new Exception(tableName + "的主键" + attrName + "必须是整数类型!"); } } } //Key 属性 int keyCnt = keyList.Count; if (keyCnt > 0) { keyPropertyItem = new PropertyItem("mkey"); if (keyCnt > 1) { this.m_keyType = "long"; List <Type> paramTypes = new List <Type>(); List <string> paramNames = new List <string>(); string strGenKey = "\t\treturn "; for (int i = 0; i < keyCnt - 1; i++) { attrName = keyList[i].Key; bit = keyList[i].Value; //不配置的话默认16位累加 if (bit == "") { bit = "" + 16 * (keyCnt - 1 - i); } ks += "((long)this.m_" + attrName + " << " + bit + ") + "; paramTypes.Add(typeof(System.Int32)); paramNames.Add(attrName); strGenKey += "((long)" + attrName + " << " + bit + ") + "; } attrName = keyList[keyCnt - 1].Key; paramTypes.Add(typeof(System.Int32)); paramNames.Add(attrName); strGenKey += attrName + ";"; //GenKey方法 mis = new MethodItem("GenKey", MemberAttributes.Final | MemberAttributes.Public | MemberAttributes.Static, paramTypes, paramNames); SetComment("GenKey方法", mis.Method); mis.Method.ReturnType = new CodeTypeReference(typeof(System.Int64)); state = new CodeSnippetStatement(strGenKey); mis.Method.Statements.Add(state); methodList.Add(mis); } ks += "this.m_" + keyList[keyCnt - 1].Key; ks = "\t\t\treturn " + ks + ";"; keyPropertyItem.SetGetName(ks, true); if (this.m_keyType == "int") { keyPropertyItem.SetValueType(typeof(System.Int32)); } else if (this.m_keyType == "long") { keyPropertyItem.SetValueType(typeof(System.Int64)); } keyPropertyItem.SetModifier(MemberAttributes.Public | MemberAttributes.Final); keyPropertyItem.SetComment("类的Key值"); propertyList.Add(keyPropertyItem); } }