Пример #1
0
        /// <summary>
        /// 将 .proto 文件转成 .cs 文件
        /// <para>用于项目非ProtoBuf-net类型协议,以后用PB协议的话这里就没有用了</para>
        /// </summary>
        /// <param name="inPath"></param>
        /// <param name="inFolderName"></param>
        /// <returns></returns>
        public bool Proto2CSharp(string inPath, string inFolderName)
        {
            Assist.CheckFolderExist(inFolderName);
            Assist.DeleteFilesInFolder("ProtoItem");

            Assist.GetObjPaths(".proto", inPath).ForEach(delegate(string path)
            {
                FileInfo targetFileInfo = new FileInfo(path);
                bool bCommonClass       = path.EndsWith("_comm.proto");

                // 类名 -> 成员列表<成员名, 成员类型>
                Dictionary <string, Dictionary <string, string> > nClasses = null;
                if (targetFileInfo != null)
                {
                    Queue <string> sq = new Queue <string>();
                    StreamReader sr   = new StreamReader(path, System.Text.Encoding.Default);
                    string line;
                    while (!sr.EndOfStream)
                    {
                        line = sr.ReadLine().Trim();
                        line = Regex.Replace(line, @"/{2}.+", "");// 去掉“//”行
                        line = Regex.Replace(line, @"{\s*", "");
                        sq.Enqueue(line);
                    }
                    sr.Close();
                    sr.Dispose();

                    string curNameSpace = sq.Dequeue().Remove(0, 8).Replace(";", "");

                    nClasses = HanldQueue(sq);

                    foreach (KeyValuePair <string, Dictionary <string, string> > fieldStr in nClasses)
                    {
                        if (fieldStr.Key != "")
                        {
                            ProtoToCSharp ptcs = new ProtoToCSharp(curNameSpace, fieldStr.Key, "ProtoItem");
                            try
                            {
                                ptcs.Create(fieldStr.Value, bCommonClass);
                            }
                            catch (Exception exp)
                            {
                                throw new Exception(exp.ToString() + ", Class" + fieldStr);
                            }
                        }
                    }
                }
                if (bCommonClass)
                {
                    AutoCSharp.Do.Creator.TypeMapper.InitProtoAssembly();
                }
            });
            return(true);
        }
Пример #2
0
        /// <summary>
        /// ------------------- TODO -------------------
        /// </summary>
        /// <returns></returns>
        public bool ExcelToXml(string inPath, string inFolderName)
        {
            Assist.CheckFolderExist(inFolderName);
            Assist.GetObjPaths(".xls", inPath).ForEach(delegate(string path)
            {
                DataSet ds   = Assist.ExcelToData(path);
                DataTable dt = ds.Tables[0];

                //ExcelToXml e = new ExcelToXml();
            });
            return(true);
        }
Пример #3
0
        public bool Json2Bin()
        {
            string path = Assist.RootPath + "Json/";

            Assist.CheckFolderExist("Json");
            MemoryStream  ms      = new MemoryStream();
            List <string> allJson = Assist.GetObjPaths(".json", path);

            byte[] countBytes = BitConverter.GetBytes(allJson.Count);
            ms.Write(countBytes, 0, countBytes.Length);

            for (int i = 0; i < allJson.Count; i++)
            {
                FileInfo targetFileInfo = new FileInfo(allJson[i]);
                string   fileName       = targetFileInfo.Name;
                fileName = fileName.Replace(".json", "");
                string txt = File.ReadAllText(allJson[i], Encoding.UTF8);

                byte[] nameBytes       = Encoding.UTF8.GetBytes(fileName);
                byte[] nameLengthBytes = BitConverter.GetBytes(nameBytes.Length);
                ms.Write(nameLengthBytes, 0, nameLengthBytes.Length);
                ms.Write(nameBytes, 0, nameBytes.Length);

                byte[] textBytes       = Encoding.UTF8.GetBytes(txt);
                byte[] textLengthBytes = BitConverter.GetBytes(textBytes.Length);
                ms.Write(textLengthBytes, 0, textLengthBytes.Length);
                ms.Write(textBytes, 0, textBytes.Length);
            }

            byte[] total = ms.ToArray();

            string filePath = Assist.RootPath + "JsonBin";

            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }

            FileStream fs = new FileStream(filePath, FileMode.Create);

            fs.Write(total, 0, total.Length);
            fs.Flush();
            fs.Close();

            return(true);
        }
Пример #4
0
        /// <summary>
        /// 将 .proto 文件转成 .cs 文件
        /// <para>用于项目非ProtoBuf-net类型协议,以后用PB协议的话这里就没有用了</para>
        /// </summary>
        /// <param name="inPath"></param>
        /// <param name="inFolderName"></param>
        /// <returns></returns>
        public bool Proto2CSharp(string inPath, string inFolderName)
        {
            Assist.CheckFolderExist(inFolderName);
            Assist.GetObjPaths(".proto", inPath).ForEach(delegate(string path)
            {
                FileInfo targetFileInfo = new FileInfo(path);
                if (targetFileInfo != null)
                {
                    Queue <string> sq = new Queue <string>();
                    StreamReader sr   = new StreamReader(path, System.Text.Encoding.Default);
                    String line;
                    while (!sr.EndOfStream)
                    {
                        line = sr.ReadLine().Trim();
                        line = Regex.Replace(line, @"/{2}.+", "");
                        line = Regex.Replace(line, @"{\s*", "");
                        if (line != "")
                        {
                            sq.Enqueue(line);
                        }
                    }
                    sr.Close();
                    sr.Dispose();

                    string curNameSpace = sq.Dequeue().Remove(0, 8).Replace(";", "");

                    // 类名 -> 成员列表<成员名, 成员类型>
                    Dictionary <string, Dictionary <string, string> > nClasses = HanldQueue(sq);

                    foreach (KeyValuePair <string, Dictionary <string, string> > item in nClasses)
                    {
                        if (item.Key != "")
                        {
                            ProtoToCSharp ptcs = new ProtoToCSharp(curNameSpace, item.Key, "ProtoItem");
                            ptcs.Create(item.Value);
                        }
                    }
                }
            });
            return(true);
        }
Пример #5
0
 /// <summary>
 /// Sub Excel -> .cs
 /// </summary>
 /// <param name="inPath"></param>
 /// <param name="inFolderName"></param>
 /// <param name="inNameSpace"></param>
 /// <param name="inHeritNames"></param>
 /// <returns></returns>
 public bool SubExcel(string inPath, string inFolderName, string inNameSpace, string inHeritNames)
 {
     Assist.CheckFolderExist(inFolderName);
     Assist.GetObjPaths(".xls", inPath).ForEach(delegate(string path)
     {
         DataSet ds      = Assist.ExcelToData(path);
         DataTable dt    = ds.Tables[0];
         ExcelToCSharp e = new ExcelToCSharp(inHeritNames, dt.TableName, inFolderName);
         e.SetInherit(inHeritNames);
         List <string[]> values = new List <string[]>();
         for (int x = 0; x < dt.Columns.Count; x++)
         {
             string[] v = new string[3];
             v[0]       = dt.Rows[0][x].ToString();
             v[1]       = dt.Rows[2][x].ToString();
             v[2]       = dt.Rows[1][x].ToString();
             values.Add(v);
         }
         e.SetValue(values);
     });
     return(true);
 }
Пример #6
0
        /// <summary>
        /// Excel -> 二进制文件
        /// </summary>
        /// <param name="inPath"></param>
        /// <param name="inFolderName"></param>
        /// <returns></returns>
        public bool Bin(string inPath, string inFolderName)
        {
            Assist.CheckFolderExist(inFolderName);

            PBData data = new PBData();

            Assist.GetObjPaths(".xls", inPath).ForEach(delegate(string path)
            {
                DataSet ds   = Assist.ExcelToData(path);
                DataTable dt = ds.Tables[0];

                string classname = Stringer.FirstLetterUp(dt.TableName);

                Type classType = Type.GetType(classname);

                FieldInfo fieldInfo = typeof(PBData).GetField(classname + "Dic");

                IDictionary fieldValue = fieldInfo.GetValue(data) as IDictionary;

                if (classType != null)
                {
                    for (int i = 4; i < dt.Rows.Count; i++)
                    {
                        string key = ""; // key

                        List <string> ls = new List <string>();
                        for (int x = 0; x < dt.Columns.Count; x++)
                        {
                            ls.Add(dt.Rows[i][x].ToString());

                            if (dt.Rows[2][x].ToString().Split('+')[2] == "1")// 当前值为Key值的一部分
                            {
                                key += dt.Rows[i][x].ToString() + "_";
                            }
                        }
                        key = key.Remove(key.Length - 1, 1);
                        IProtoBufable value = Activator.CreateInstance(classType) as IProtoBufable;// value
                        value.Set(ls);
                        fieldValue.Add(key, value);
                    }

                    fieldInfo.SetValue(data, fieldValue);
                }
            });

            #region SceneLayout 读取同级目录下的“Excel/SceneLayout/”内的所有 xml 文件,并将其数据写入 PBData

            Dictionary <string, XmlDocument> doc = Assist.GetXml(Assist.RootPath + "Excel/SceneLayout/");
            foreach (KeyValuePair <string, XmlDocument> item in doc)
            {
                SceneLayout sl  = new SceneLayout();
                XmlNodeList xcc = item.Value.SelectSingleNode("Config").ChildNodes;
                for (int i = 0; i < xcc.Count; i++)
                {
                    SceneLayoutItem sli = new SceneLayoutItem();

                    IProtoBufable xmlItemValue = new SceneLayoutItem() 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);
                    }
                    xmlItemValue.Set(xls);

                    sl.item.Add(xmlItemValue as SceneLayoutItem);
                }
                data.SceneLayoutDic.Add(item.Key, sl);
            }

            #endregion

            using (var file = System.IO.File.Create("PBData"))
            {
                try
                {
                    ProtoBuf.Serializer.Serialize(file, data);
                }
                catch (Exception e)
                {
                    MainWindow.Show(e.ToString());
                }
            }

            return(true);
        }
Пример #7
0
        /// <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);
        }
Пример #8
0
        /// <summary>
        /// Excel -> .cs
        /// </summary>
        /// <param name="inFolderPath">输出文件夹名</param>
        /// <param name="suffixName">文件后缀名</param>
        /// <param name="inNameSpace">命名空间</param>
        /// <param name="inHeritNames">继承</param>
        /// <returns></returns>
        public bool Excel(string inPath, string inFolderName, string suffixName, string inNameSpace = "", string inHeritNames = "")
        {
            Assist.CheckFolderExist(inFolderName);
            Assist.DeleteFilesInFolder(inFolderName);

            Dictionary <string, string[]> finalclassname = new Dictionary <string, string[]>();

            //Load Cfg XML
            string cfgPath = Assist.RootPath + "Cfg";;
            Dictionary <string, XmlDocument> dicXML = Assist.GetXml(cfgPath);
            string      xmlName;
            XmlNodeList nodeList;
            Dictionary <string, string> dicFunctions = new Dictionary <string, string>();

            foreach (XmlDocument xml in dicXML.Values)
            {
                xmlName = xml.DocumentElement.Name;
                if (xmlName == "Functions")
                {
                    //保证先Load Functions.xml
                    nodeList = xml.GetElementsByTagName("function");
                    foreach (XmlNode node in nodeList)
                    {
                        foreach (XmlAttribute attr in node.Attributes)
                        {
                            if (attr.Name == "name")
                            {
                                dicFunctions[attr.Value] = node.InnerText;
                                break;
                            }
                        }
                    }
                    break;
                }
            }

            Dictionary <string, ExcelToCSharp> dicEc = new Dictionary <string, ExcelToCSharp>();
            string tableName = "";
            string tableDes  = "";

            string          cfgName = "", desName = "", fieldName;
            ExcelToCSharp   e;
            List <string[]> values;

            foreach (XmlDocument xml in dicXML.Values)
            {
                xmlName = xml.DocumentElement.Name;
                if (xmlName == "CfgItems")
                {
                    nodeList = xml.GetElementsByTagName("cfg");
                    foreach (XmlNode node in nodeList)
                    {
                        foreach (XmlAttribute attr in node.Attributes)
                        {
                            if (attr.Name == "name")
                            {
                                cfgName = attr.Value;
                            }
                            else if (attr.Name == "des")
                            {
                                desName = attr.Value;
                            }
                        }
                        //finalclassname.Add(cfgName, desName);
                        e = new ExcelToCSharp(inHeritNames, "Cfg" + Assist.FirstLetterUp(cfgName), inFolderName, dicFunctions);
                        e.SetInherit(inHeritNames);
                        values = new List <string[]>();
                        foreach (XmlNode paramNode in node.ChildNodes)
                        {
                            string[] v = new string[4];
                            foreach (XmlAttribute attr in paramNode.Attributes)
                            {
                                fieldName = attr.Name;
                                if (fieldName == "name")
                                {
                                    v[0] = attr.Value;
                                }
                                else if (fieldName == "type")
                                {
                                    v[1] = attr.Value;
                                }
                                else if (fieldName == "des")
                                {
                                    v[2] = attr.Value;
                                }
                                else if (fieldName == "link")
                                {
                                    v[3] = attr.Value;
                                }
                            }
                            values.Add(v);
                        }
                        e.SetValue(cfgName, values);
                        dicEc.Add(cfgName, e);
                    }
                }
            }

            try
            {
                Assist.GetObjPaths(suffixName, inPath).ForEach(delegate(string path)
                {
                    DataTable dt = null;
                    bool bExcel  = true;
                    if (suffixName == ".xlsx")
                    {
                        DataSet ds = Assist.ExcelToData(path);
                        dt         = ds.Tables[0];
                    }
                    else if (suffixName == ".txt")
                    {
                        tableDes = path;
                        dt       = Assist.TxtToData(path);
                        bExcel   = false;
                    }

                    if (dt != null)
                    {
                        // ===================== 类名注释 ========================

                        string acn  = path.Contains("(") ? path.Split('(')[1] : path.Split('(')[1];
                        string acnn = acn.Contains(")") ? acn.Split(')')[0] : acn.Split(')')[0];
                        tableDes    = acnn;
                        // =======================================================
                        tableName = Assist.FirstLetterUp(dt.TableName);
                        e         = new ExcelToCSharp(inHeritNames, "Cfg" + tableName, inFolderName, dicFunctions);
                        e.SetInherit(inHeritNames);

                        DataRowCollection rows = dt.Rows;
                        values              = new List <string[]>();
                        string note         = null;
                        string strFieldName = null;
                        for (int x = 0; x < dt.Columns.Count; x++)
                        {
                            if (rows[2][x].ToString() != "")
                            {
                                string[] v = new string[4];
                                v[0]       = rows[0][x].ToString().Trim();
                                v[1]       = rows[2][x].ToString().Trim();
                                if (bExcel)
                                {
                                    v[2] = rows[1][x].ToString().Trim();
                                    v[3] = rows[3][x].ToString().Trim();
                                }
                                else
                                {
                                    strFieldName = rows[1][x].ToString().Trim();
                                    note         = rows[3][x].ToString().Trim();
                                    v[2]         = note == "" ? strFieldName : string.Concat(strFieldName, ";", note);
                                    v[3]         = rows[4][x].ToString().Trim();
                                }

                                values.Add(v);
                            }
                        }
                        e.SetValue(acnn, values);
                        dicEc.Add(tableName, e);

                        finalclassname.Add(dt.TableName, new string[] { acnn, e.GetKeyType() });
                    }
                });
            }
            catch (Exception ex)
            {
                throw new Exception(tableDes + ex.Message + "可能是Excel打开表左下角的名字跟其它表重复。");
            }

            foreach (ExcelToCSharp ec in dicEc.Values)
            {
                ec.CreateCode(dicEc);
            }

            CreatePBData final = new CreatePBData(inHeritNames, "PBData", inFolderName);

            final.SetValue(finalclassname);
            return(true);
        }
Пример #9
0
    /// <summary>
    ///
    /// </summary>
    /// <param name="inPath"></param>
    /// <param name="outPath"></param>
    private void ForGen(string inPath, string outPath)
    {
        List <string> listClassNames = new List <string>();

        Assist.ClearDirFiles(outPath);

        DirectoryInfo folder = new DirectoryInfo(inPath);

        FileSystemInfo[] files = folder.GetFileSystemInfos();
        int length             = files.Length;

        for (int index = 0; index < length; index++)
        {
            if (files[index] is DirectoryInfo)
            {
                //this.ForGen(files[index].FullName);
            }
            else
            {
                if (files[index].Name.EndsWith(".xlsx"))
                {
                    //DataSet mResultSet = Assist.ExcelToDataSet(files[index].FullName);
                    FileStream       stream      = File.Open(files[index].FullName, FileMode.Open, FileAccess.Read);
                    IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
                    DataSet          mResultSet  = excelReader.AsDataSet();

                    //判断Excel文件中是否存在数据表
                    if (mResultSet.Tables.Count < 1)
                    {
                        return;
                    }

                    //默认读取第一个数据表
                    DataTable mSheet = mResultSet.Tables[0];

                    string tableName = mSheet.TableName;
                    string csName    = m_itemHeader + Stringer.FirstLetterUp(tableName);
                    listClassNames.Add(csName);

                    CreateCSItemData csItemData = new CreateCSItemData(m_nameSpace, csName, m_outPath);

                    //读取数据表行数和列数
                    int rowCount = mSheet.Rows.Count;
                    int colCount = mSheet.Columns.Count;


                    List <string> mainKeyList = new List <string>();

                    for (int j = 0; j < colCount; j++)//列
                    {
                        string key = mSheet.Rows[titleIndex][j].ToString();
                        if (key == "")
                        {
                            Assist.Log("下标" + "(" + titleIndex + "," + j + ")" + "不能为空");
                            return;
                        }

                        string   strData       = mSheet.Rows[typeIndex][j].ToString();
                        string[] strs          = strData.Split('+');
                        string   keyType       = strs[0];
                        int      isMainkey     = int.Parse(strs[1]);
                        string   linkTableName = strs[2];

                        ItemField itemField = new ItemField(key, keyType, MemberAttributes.Private);
                        csItemData.AddFieldValue(itemField);

                        ItemProperty itemProperty = new ItemProperty(key);
                        itemProperty.SetGetName();
                        itemProperty.SetSetName();
                        itemProperty.SetComment(mSheet.Rows[summary][j].ToString());
                        itemProperty.SetValueType(keyType);
                        itemProperty.SetModifier(MemberAttributes.Public | MemberAttributes.Final);
                        itemProperty.SetField("ProtoMember", (j + 1).ToString());
                        csItemData.AddPropertyValue(itemProperty);

                        //是主键,或者是合成主键的一部分字段
                        if (isMainkey == 1)
                        {
                            mainKeyList.Add(key);
                        }

                        //有链接的表
                        if (linkTableName != "0")
                        {
                            linkTableName = m_itemHeader + Stringer.FirstLetterUp(linkTableName);
                            string     subClassname = linkTableName;
                            ItemMethod mis          = new ItemMethod("Get" + subClassname, MemberAttributes.Final | MemberAttributes.Public, new List <string>()
                            {
                                "System.String"
                            });
                            csItemData.SetComment("获取" + subClassname, mis.Method);
                            mis.Method.ReturnType = new CodeTypeReference(subClassname);
                            mis.Method.Statements.Add(new CodeMethodReturnStatement(new CodeArgumentReferenceExpression("CfgData.Instance.m_PBData." + subClassname + "Dic[inArg0]")));
                            csItemData.AddMethodValue(mis);
                        }
                    }

                    //最多由3个字段组成主键
                    string MainKey = "";
                    if (mainKeyList.Count == 1)
                    {
                        MainKey = mainKeyList[0] + ".ToString()";
                    }
                    else if (mainKeyList.Count == 2)
                    {
                        MainKey = mainKeyList[0] + ".ToString() + \"_\" + this.m_" + mainKeyList[1] + ".ToString()";
                    }
                    else if (mainKeyList.Count == 3)
                    {
                        MainKey = mainKeyList[0] + ".ToString() + \"_\" + this.m_" + mainKeyList[1] + ".ToString() + \"_\" + this.m_" + mainKeyList[2] + ".ToString()";
                    }

                    ItemProperty itemProperty2 = new ItemProperty("MainKey");
                    itemProperty2.SetGetName(MainKey);
                    itemProperty2.SetComment("主键");
                    itemProperty2.SetValueType("string");
                    itemProperty2.SetModifier(MemberAttributes.Public | MemberAttributes.Final);
                    csItemData.AddPropertyValue(itemProperty2);

                    csItemData.Create();
                }
            }
        }

        CreatePBData final = new CreatePBData(m_nameSpace, m_PBData, m_outPath);

        final.SetValue(listClassNames);
        final.Create();


        List <string> dyncUsingList = new List <string>();

        dyncUsingList.Add("protobuf-net.dll");
        dyncUsingList.Add("mscorlib.dll");

        List <string> dyncCsFilesName = Assist.GetObjPaths(".cs", m_outPath);
        string        csDataPoolPath  = Path.Combine(Environment.CurrentDirectory, "CfgData.cs");

        dyncCsFilesName.Add(csDataPoolPath);
        for (int i = 0; i < dyncCsFilesName.Count; i++)
        {
            dyncCsFilesName[i] = dyncCsFilesName[i].Replace("/", "\\");
        }

        string          dyncDllPath = Path.Combine(m_outPath, "CfgData.dll");
        CompilerResults cr          = DyncLibTool.CompileCSharpCode(dyncCsFilesName, dyncDllPath, dyncUsingList);

        //Assembly assembly = cr.CompiledAssembly;
        Assist.Log("Gen OK");
    }
Пример #10
0
        static void InitAssemblyFromFile(string typeName, bool loadAll, string dirName, List <string> lisName = null)
        {
            if (dirName == null)
            {
                dirName = "ExcelItems";
            }
            string        csFileRootPath = Assist.RootPath + dirName;
            List <string> allCsFiles;

            if (loadAll)
            {
                allCsFiles = Assist.GetObjPaths(".cs", csFileRootPath);
                for (int i = 0; i < allCsFiles.Count; i++)
                {
                    string path = allCsFiles[i];
                    allCsFiles[i] = path.Replace("/", "\\");
                }

                //适配GInterface.m_DictConfig
                if (dirName == "ExcelItems")
                {
                    string classPath = Assist.RootPath + "Cfg\\GInterface.cs";
                    allCsFiles.Add(classPath);
                }
            }
            else
            {
                allCsFiles = new List <string>();
                if (lisName != null)
                {
                    lisName.ForEach(delegate(string name)
                    {
                        string path = csFileRootPath + "\\" + name + ".cs";
                        allCsFiles.Add(path);
                    });
                }
                else
                {
                    string path = csFileRootPath + "\\" + typeName + ".cs";
                    allCsFiles.Add(path);
                }
            }

            CSharpCodeProvider provider = new CSharpCodeProvider();

            CompilerParameters paras = new CompilerParameters();

            paras.GenerateExecutable = false;
            //paras.GenerateInMemory = true;
            paras.GenerateInMemory = false;

            string dllName = "TypeMapper1.dll";

            if (index > 0)
            {
                dllName = "TypeMapper2.dll";
                index   = 0;
            }
            index++;
            paras.OutputAssembly = dllName;

            paras.ReferencedAssemblies.Add("protobuf-net.dll");
            paras.ReferencedAssemblies.Add("mscorlib.dll");
            paras.ReferencedAssemblies.Add("AutoCSharp.exe");
            //for test
            //string[] files = new string[2];
            //files[0] = "F:\\work\\game\\Client\\Demo3Tools\\ExceltoProtoBuf\\AutoCSharp\\bin\\Release\\ExcelItems\\CfgAccomplish.cs";
            //files[1] = "F:\\work\\game\\Client\\Demo3Tools\\ExceltoProtoBuf\\AutoCSharp\\bin\\Release\\ExcelItems\\PBData.cs";

            try
            {
                CompilerResults result = provider.CompileAssemblyFromFile(paras, allCsFiles.ToArray());
                //assemblyDynamic = result.CompiledAssembly;

                Assembly assem = result.CompiledAssembly;
                InitDomain();

                //remoteLoader.LoadAssembly(Assist.RootPath + dllName);
                remoteLoader.assembly = assem;
            }
            catch (Exception ex)
            {
                throw new Exception("动态加载cs文件出错,可能是表的字段重复或命名问题,请检查cs文件!!\n" + ex.ToString());
            }
        }