Example #1
0
        private DataType ConvertToDatabaseType(DataType dataType)
        {
            DataType databaseType = null;

            var primitiveReturnType = dataType as PrimitiveDataType;

            if (primitiveReturnType != null)
            {
                databaseType = primitiveReturnType.Clone();
            }
            else
            {
                var collectionReturnType = dataType as CollectionDataType;
                ExceptionUtilities.CheckObjectNotNull(collectionReturnType, "Unsupported data type: '{0}'. Only primitive data types and collection of rows can be converted to a database type.", dataType);

                var rowDataType = collectionReturnType.ElementDataType as RowDataType;
                ExceptionUtilities.CheckObjectNotNull(rowDataType, "Unsupported collection's element data type: '{0}'. Only row data type is supported as element data type of a collection when converting to a database type.", collectionReturnType.ElementDataType);

                TableDataType table = new TableDataType();
                foreach (var property in rowDataType.Definition.Properties)
                {
                    var primitivePropertyType = property.PropertyType as PrimitiveDataType;
                    ExceptionUtilities.CheckObjectNotNull(primitivePropertyType, "Unsupported property's data type: '{0}'. Only primitive data types are supported.", property.PropertyType);

                    var column = new Column(property.Name, primitivePropertyType);
                    this.ApplyDataGeneratorAnnotationToStoreItem(column, property);
                    table.Columns.Add(column);
                }

                databaseType = table;
            }

            return(databaseType);
        }
Example #2
0
        void PreparingCellForEdit(object sender, DataGridPreparingCellForEditEventArgs e)
        {
            TableColumn c = e.Row.DataContext as TableColumn;

            if (e.Column.DisplayIndex == 2)
            {
                if (TableDataType.IsLengthFixed(c.DataType))
                {
                    TextBox textBox = (e.EditingElement as TextBox);
                    textBox.IsReadOnly = true;
                }
                else
                {
                    TextBox textBox = (e.EditingElement as TextBox);
                    textBox.IsReadOnly = false;
                }
            }
            if (e.Column.DisplayIndex == 3)
            {
                if (TableDataType.IsNullFixed(c.DataType))
                {
                    CheckBox checkBox = (e.EditingElement as CheckBox);
                    checkBox.IsEnabled = false;
                    checkBox.IsChecked = false;
                }
                else
                {
                    CheckBox checkBox = (e.EditingElement as CheckBox);
                    checkBox.IsEnabled = true;
                    checkBox.IsChecked = false;
                }
            }
        }
Example #3
0
        /// <summary>
        /// 生成基本类型字符
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        private string GenerateTypeByTableDataType(TableDataType type, string attributeName)
        {
            switch (type)
            {
            case TableDataType.INT:
                return("int");

            case TableDataType.FLOAT:
                return("float");

            case TableDataType.STRING:
                return("string");

            case TableDataType.ENUM:
                return(GetEnumTypeName(attributeName));

            case TableDataType.LONG:
                return("long");

            case TableDataType.DOUBLE:
                return("double");

            // TODO:根据需求扩展类型
            default:
                return("");
            }
        }
Example #4
0
        private void DataTypeFieldChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            var item = dgridCols.SelectedItem as TableColumn;

            if (item != null)
            {
                item.Length = TableDataType.GetDefaultLength(item.DataType);
            }
        }
Example #5
0
        private void DataTypeFieldChanged(object sender, SelectionChangedEventArgs e)
        {
            var item = dgridCols.SelectedItem as TableColumn;

            if (item != null)
            {
                item.Length    = TableDataType.GetDefaultLength(item.DataType);
                item.Precision = TableDataType.GetDefaultPrecision(item.DataType);
                item.Scale     = TableDataType.GetDefaultScale(item.DataType);
            }
        }
Example #6
0
    private void ParseFieldType()
    {
        List <string> fieldTypes = new List <string>();
        IRow          typeRow    = _sheet.GetRow(1);

        if (typeRow == null)
        {
            StopCompile(
                string.Format(k_SimpleErrMsgHeader + ": Missing type definitoins.",
                              _tableCompiler.FilePath, _sheet.SheetName));
            return;
        }
        for (int i = 0; i <= typeRow.LastCellNum; ++i)
        {
            ICell cell = typeRow.GetCell(i);
            if (cell == null || cell.CellType == CellType.Blank)
            {
                break;
            }
            else if (cell.CellType == CellType.String)
            {
                var rawTypeInfo = cell.StringCellValue.Replace(" ", "").ToLower();
                var defInfo     = rawTypeInfo.Split('|');
                var type        = defInfo[0];
                if (!TableDataType.HasType(type))
                {
                    StopCompile(string.Format(k_ErrorMsgHeader + ": (3) type is unsupported",
                                              _tableCompiler.FilePath, _sheet.SheetName, cell.RowIndex + 1, i + 1, type));
                    return;
                }
                fieldTypes.Add(rawTypeInfo);
            }
            else if (cell.CellType == CellType.Unknown)
            {
                StopCompile(string.Format(k_ErrorMsgHeader + ": Unrecognizable type",
                                          _tableCompiler.FilePath, _sheet.SheetName, cell.RowIndex + 1, i + 1));
                return;
            }
        }
        if (_tableCompiler.FieldTypes == null)
        {
            _tableCompiler.FieldTypes = fieldTypes;
        }
        else if (!CheckTypes(fieldTypes))
        {
            StopCompile(string.Format(k_SimpleErrMsgHeader + ": type definition in different sheets should keep identical.",
                                      _tableCompiler.FilePath, _sheet.SheetName));
        }
    }
        private void PreparingCellForEdit(object sender, DataGridPreparingCellForEditEventArgs e)
        {
            var c = e.Row.DataContext as TableColumn;

            if (e.Column.DisplayIndex == 2)
            {
                if (c != null && TableDataType.IsLengthFixed(c.DataType))
                {
                    var textBox = (e.EditingElement as TextBox);
                    if (textBox != null)
                    {
                        textBox.IsReadOnly = true;
                    }
                }
                else
                {
                    var textBox = (e.EditingElement as TextBox);
                    if (textBox != null)
                    {
                        textBox.IsReadOnly = false;
                    }
                }
            }
            if (e.Column.DisplayIndex != 3)
            {
                return;
            }
            if (c != null && TableDataType.IsNullFixed(c.DataType))
            {
                var checkBox = (e.EditingElement as CheckBox);
                if (checkBox != null)
                {
                    checkBox.IsEnabled = false;
                    checkBox.IsChecked = false;
                }
            }
            else
            {
                var checkBox = (e.EditingElement as CheckBox);
                if (checkBox != null)
                {
                    checkBox.IsEnabled = true;
                    checkBox.IsChecked = false;
                }
            }
        }
Example #8
0
        /// <summary>
        /// 生成属性代码
        /// </summary>
        /// <param name="type"></param>
        /// <param name="attributeName"></param>
        /// <param name="comment"></param>
        /// <returns></returns>
        private string GenerateAttributeCode(TableDataType type, string attributeName, string comment)
        {
            string typeName = GenerateTypeByTableDataType(type, attributeName);

            if (string.IsNullOrEmpty(typeName))
            {
                return("");
            }
            string[]      commentSplit   = comment.Split(new char[] { '\r', '\n' }, System.StringSplitOptions.RemoveEmptyEntries);
            StringBuilder commentBuilder = new StringBuilder();

            for (int i = 0; i < commentSplit.Length; ++i)
            {
                commentBuilder.Append(commentSplit[i]);
                if (i != commentSplit.Length - 1)
                {
                    commentBuilder.Append(@"
    /// ");
                }
            }
            return(string.Format(codeVariableTemplate, commentBuilder, typeName, attributeName));
        }
Example #9
0
    /// <summary>
    /// 加载数据模板
    /// </summary>
    /// <returns>数据列表</returns>
    /// <param name="data">二进制表数据</param>
    /// <typeparam name="T">自动生成的数据类型</typeparam>
    private static List <T> LoadDataTemplate <T>(TextAsset data) where T : new()
    {
        List <T> list = new List <T>();

        using (BinaryReader reader = new BinaryReader(new MemoryStream(data.bytes)))
        {
            Type            type      = typeof(T);
            FieldInfo[]     fields    = type.GetFields();
            TableDataType[] dataTypes = new TableDataType[fields.Length];
            /*int version = */
            reader.ReadInt32();
            int dataLength = reader.ReadInt32();
            for (int i = 0; i < dataTypes.Length; ++i)
            {
                dataTypes[i] = (TableDataType)reader.ReadByte();
            }
            for (int dataIndex = 0; dataIndex < dataLength; ++dataIndex)
            {
                T      dataT   = new T();
                object dataObj = dataT as object;
                for (int fieldIndex = 0; fieldIndex < fields.Length; ++fieldIndex)
                {
                    object fieldData = null;
                    switch (dataTypes[fieldIndex])
                    {
                    case TableDataType.INT:
                        fieldData = reader.ReadInt32();
                        break;

                    case TableDataType.FLOAT:
                        fieldData = reader.ReadSingle();
                        break;

                    case TableDataType.STRING:
                        fieldData = reader.ReadString();
                        break;

                    case TableDataType.ENUM:
                        fieldData = reader.ReadInt32();
                        break;

                    case TableDataType.LONG:
                        fieldData = reader.ReadInt64();
                        break;

                    case TableDataType.DOUBLE:
                        fieldData = reader.ReadDouble();
                        break;

                    // TODO:根据需要扩展类型
                    default: break;
                    }
                    if (fieldData != null)
                    {
                        fields[fieldIndex].SetValue(dataObj, fieldData);
                        dataT = (T)dataObj;
                    }
                    else
                    {
                        Debug.LogWarning("--Toto-- LoadTableManager->LoadDataTemplate: fieldData is null.");
                        continue;
                    }
                }
                list.Add(dataT);
            }
        }

        return(list);
    }
        private DataType ConvertToDatabaseType(DataType dataType)
        {
            DataType databaseType = null;

            var primitiveReturnType = dataType as PrimitiveDataType;

            if (primitiveReturnType != null)
            {
                databaseType = primitiveReturnType.Clone();
            }
            else
            {
                var collectionReturnType = dataType as CollectionDataType;
                ExceptionUtilities.CheckObjectNotNull(collectionReturnType, "Unsupported data type: '{0}'. Only primitive data types and collection of rows can be converted to a database type.", dataType);

                var rowDataType = collectionReturnType.ElementDataType as RowDataType;
                ExceptionUtilities.CheckObjectNotNull(rowDataType, "Unsupported collection's element data type: '{0}'. Only row data type is supported as element data type of a collection when converting to a database type.", collectionReturnType.ElementDataType);

                TableDataType table = new TableDataType();
                foreach (var property in rowDataType.Definition.Properties)
                {
                    var primitivePropertyType = property.PropertyType as PrimitiveDataType;
                    ExceptionUtilities.CheckObjectNotNull(primitivePropertyType, "Unsupported property's data type: '{0}'. Only primitive data types are supported.", property.PropertyType);

                    var column = new Column(property.Name, primitivePropertyType);
                    this.ApplyDataGeneratorAnnotationToStoreItem(column, property);
                    table.Columns.Add(column);
                }

                databaseType = table;
            }

            return databaseType;
        }
Example #11
0
 public void GenerateCodeData(ExcelData excelData)
 {
     try
     {
         StringBuilder codeBuilder           = new StringBuilder();
         List <int>    mainKeyIndexList      = new List <int>(excelData.mainKeyIndexs); // 主关键字列表
         int[]         ignoreFieldIndexArray = excelData.ignoreFieldIndexs.ToArray();   // 忽略字段列表
         mainKeyIndexList.RemoveAll((match) => { return(excelData.ignoreFieldIndexs.Contains(match)); });
         if (mainKeyIndexList.Count == 0)
         {
             throw new Exception("没有有效的关键字段");
         }
         // 生成文件头
         string        date           = DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString();
         StringBuilder mainKeyBuilder = new StringBuilder();     // 文件头关键字段说明
         foreach (var v in mainKeyIndexList)
         {
             mainKeyBuilder.Append(excelData.names[v]).Append(" ");
         }
         StringBuilder ignoreKeyBuilder = new StringBuilder();       // 文件头忽略字段说明
         foreach (var v in excelData.ignoreFieldIndexs)
         {
             ignoreKeyBuilder.Append(excelData.names[v]).Append(" ");
         }
         string headText = FormatCode(codeHeadTemplate, date, excelData.fileNameWithExtension, mainKeyBuilder, ignoreKeyBuilder);
         codeBuilder.Append(headText);
         StringBuilder classCodeBuilder = new StringBuilder();       // 类代码部分,不含文件头说明和命名空间
         // 生成主键,key超过1时生成数据结构
         if (mainKeyIndexList.Count > 1)
         {
             TableDataType[] mainKeyTypes          = new TableDataType[mainKeyIndexList.Count];
             string[]        mainKeyAttributeNames = new string[mainKeyIndexList.Count];
             string[]        mainKeyComments       = new string[mainKeyIndexList.Count];
             for (int i = 0; i < mainKeyIndexList.Count; ++i)
             {
                 int index = mainKeyIndexList[i];
                 mainKeyTypes[i]          = excelData.types[index];
                 mainKeyAttributeNames[i] = excelData.names[index];
                 mainKeyComments[i]       = excelData.descriptions[index];
             }
             string mainKeyAttributeCode = GenerateAttributeCode(mainKeyTypes, mainKeyAttributeNames, mainKeyComments, new int[0]);
             classCodeBuilder.Append(FormatCode(
                                         codeStructTemplate, GetKeyStructName(excelData.fileName), mainKeyAttributeCode
                                         ));
         }
         // 生成数据结构
         StringBuilder dataCodeBuilder   = new StringBuilder();      // 数据代码
         string        dataAttributeCode = GenerateAttributeCode(excelData.types.ToArray(), excelData.names.ToArray(), excelData.descriptions.ToArray(), ignoreFieldIndexArray);
         dataCodeBuilder.Append(dataAttributeCode).Append("\r\n");
         StringBuilder newKeyBuilder = new StringBuilder(); // 实例化key
         string        keyTypeString = "";
         if (mainKeyIndexList.Count > 1)                    // 多个参数时
         {
             newKeyBuilder.Append("\t\tvar key = new ").Append(GetKeyStructName(excelData.fileName)).Append("();\r\n");
             for (int i = 0; i < mainKeyIndexList.Count; ++i)
             {
                 int    index     = mainKeyIndexList[i];
                 string paramName = excelData.names[index];
                 newKeyBuilder.Append("\t\tkey.").Append(paramName).Append(" = ").Append(paramName).Append(";");
                 if (i != mainKeyIndexList.Count - 1)
                 {
                     newKeyBuilder.Append("\r\n");
                 }
             }
             keyTypeString = GetKeyStructName(excelData.fileName);
         }
         else
         {
             int index = mainKeyIndexList[0];
             newKeyBuilder.Append("\t\tvar key = ").Append(excelData.names[index]).Append(";");
             keyTypeString = GenerateTypeByTableDataType(excelData.types[index], excelData.names[index]);
         }
         dataCodeBuilder.Append(FormatCode(codeGetKeyTemplate, keyTypeString, newKeyBuilder));
         classCodeBuilder.Append(FormatCode(
                                     codeStructTemplate, GetDataStructName(excelData.fileName), dataCodeBuilder
                                     ));
         // 生成枚举
         List <int> enumIndexs = new List <int>();
         for (int i = 0; i < excelData.types.Count; ++i)
         {
             if (excelData.types[i] == TableDataType.ENUM && excelData.enumTypeIndexs.Contains(i))       // 判断是枚举类型且标记"#"
             {
                 enumIndexs.Add(i);
             }
         }
         if (enumIndexs.Count > 0)
         {
             string[] attributeNames = new string[enumIndexs.Count];
             string[] typeStrings    = new string[enumIndexs.Count];
             for (int i = 0; i < enumIndexs.Count; ++i)
             {
                 int index = enumIndexs[i];
                 attributeNames[i] = excelData.names[index];
                 typeStrings[i]    = excelData.typeStrings[index];
             }
             string enumCode = GenerateEnemCode(attributeNames, typeStrings);
             classCodeBuilder.Append(enumCode);
         }
         // 生成数据管理器
         string[] managerCodeUnits = new string[11];
         managerCodeUnits[0] = excelData.fileName;
         string keyType = "";
         if (mainKeyIndexList.Count > 1)
         {
             keyType = GetKeyStructName(excelData.fileName);
         }
         else
         {
             int index = mainKeyIndexList[0];
             keyType = GenerateTypeByTableDataType(excelData.types[index], excelData.names[index]);
         }
         managerCodeUnits[1]     = managerCodeUnits[3] = managerCodeUnits[5] = keyType;
         managerCodeUnits[2]     = managerCodeUnits[4] = managerCodeUnits[6] = managerCodeUnits[7] =
             managerCodeUnits[8] = GetDataStructName(excelData.fileName);
         StringBuilder addItemParamBuilder = new StringBuilder();
         for (int i = 0; i < mainKeyIndexList.Count; ++i)
         {
             int    index     = mainKeyIndexList[i];
             string paramType = GenerateTypeByTableDataType(excelData.types[index], excelData.names[i]);
             addItemParamBuilder.Append(paramType).Append(" ").Append(excelData.names[i]);
             if (i != mainKeyIndexList.Count - 1)
             {
                 addItemParamBuilder.Append(", ");
             }
         }
         managerCodeUnits[9]  = addItemParamBuilder.ToString();
         managerCodeUnits[10] = newKeyBuilder.ToString();     // 与GetKey函数相同
         classCodeBuilder.Append(FormatCode(codeManagerTemplate, managerCodeUnits));
         // 将类代码、命名空间添加到代码
         string namespaceClassCode = FormatCode(namespaceTemplate, classCodeBuilder);
         codeBuilder.Append(namespaceClassCode);
         // 保存代码文件
         string codeFilePath = excelData.path + "/" + excelData.fileName + ".cs";
         using (StreamWriter sw = new StreamWriter(codeFilePath, false))
         {
             sw.Write(codeBuilder);
         }
     }
     catch (Exception ex)
     {
         throw new Exception(excelData.fileName + ":" + ex.Message, ex);
     }
 }
        private CompareCondition(string propertyName, CompareOperator opertaor, string value, TableDataType dataType)
        {
            string valueString;

            switch (dataType)
            {
                case TableDataType.Boolean:
                case TableDataType.Int32:
                case TableDataType.Int64:
                    valueString = value;
                    break;
                case TableDataType.DateTime:
                    valueString = "datetime'" + value + "'";
                    break;
                case TableDataType.Double:
                    valueString = int.TryParse(value, out var parsedValue) ? parsedValue.ToString(CultureInfo.InvariantCulture) + ".0" : value;
                    break;
                case TableDataType.Guid:
                    valueString = "guid'" + value + "'";
                    break;
                default:
                    if (value.IndexOf('\'') != -1) value = value.Replace("'", "''");
                    valueString = "'" + value + "'";
                    break;
            }

            FilterString = "(" + propertyName + opertaor.Operator + valueString + ")";
        }
 public static Type Resolve(TableDataType tableType)
 {
     return(typeLookup[tableType]);
 }