private static PlatformTableSourceColumnInfo GetPlatformColumnInfo(TableSourceInfo tableSource, string columnName, DataTypeInfo dataType,
                                                                    bool isMandatory, bool isPrimaryKey, AutoNumberColumnInfo autoNumberInfo)
 {
     return(new PlatformTableSourceColumnInfo(tableSource, columnName, (PlatformDataTypeInfo)dataType, isMandatory, isPrimaryKey, autoNumberInfo));
 }
Exemplo n.º 2
0
        public ActionResult SaveSelection(int index, long selectedUnit, long selectedDataType, long selectedAttribute, string varName, string lastSelection)
        {
            /**
             * if selectedAttribute == -1 == Unknown
             *    selectedAttribute == -2 ==  Not found
             *
             */


            List <DataTypeInfo>         dataTypeInfos      = new List <DataTypeInfo>();
            List <UnitInfo>             unitInfos          = new List <UnitInfo>();
            List <DataAttrInfo>         dataAttributeInfos = new List <DataAttrInfo>();
            List <EasyUploadSuggestion> suggestions        = new List <EasyUploadSuggestion>();
            List <string> headers = new List <string>();


            EasyUploadTaskManager TaskManager = (EasyUploadTaskManager)Session["TaskManager"];

            //suggestions

            #region load all lists

            //dataattr
            if (Session["DataAttributes"] != null)
            {
                dataAttributeInfos = (List <DataAttrInfo>)Session["DataAttributes"];
            }

            if (!string.IsNullOrEmpty(varName))
            {
                suggestions = getSuggestions(varName, dataAttributeInfos);
            }

            unitInfos = (List <UnitInfo>)TaskManager.Bus[EasyUploadTaskManager.VERIFICATION_AVAILABLEUNITS];

            dataTypeInfos = (List <DataTypeInfo>)TaskManager.Bus[EasyUploadTaskManager.ALL_DATATYPES];

            #endregion


            #region load current seleted items

            UnitInfo     currentUnit         = unitInfos.FirstOrDefault(u => u.UnitId == selectedUnit);
            DataTypeInfo currentDataTypeInfo = dataTypeInfos.FirstOrDefault(d => d.DataTypeId.Equals(selectedDataType));

            DataAttrInfo currentDataAttrInfo = null;
            if (selectedAttribute > 0)
            {
                currentDataAttrInfo = dataAttributeInfos.FirstOrDefault(da => da.Id.Equals(selectedAttribute));
            }
            if (selectedAttribute == -1)
            {
                currentDataAttrInfo = new DataAttrInfo(-1, 0, 0, "Unknown", "Unknow", 1);
            }
            if (selectedAttribute == -2)
            {
                currentDataAttrInfo = new DataAttrInfo(-2, 0, 0, "Not found", "Not found", 1);
            }
            ;

            #endregion

            #region filtering



            if (currentUnit != null)
            {
                unitInfos = unitInfos.Where(u => u.UnitId.Equals(currentUnit.UnitId) || u.DimensionId.Equals(currentUnit.DimensionId)).ToList();

                // filtering data attrs where the attr has the unit or there dimension
                if (selectedAttribute == 0)
                {
                    dataAttributeInfos = dataAttributeInfos.Where(d => d.UnitId.Equals(currentUnit.UnitId) || d.DimensionId.Equals(currentUnit.DimensionId)).ToList();
                }
                else
                {
                    dataAttributeInfos = dataAttributeInfos.Where(d => d.Id.Equals(currentDataAttrInfo.Id)).ToList();
                }

                if (selectedDataType == 0)
                {
                    dataTypeInfos = dataTypeInfos.Where(d => currentUnit.DataTypeInfos.Any(ud => ud.DataTypeId.Equals(d.DataTypeId))).ToList();
                }
                else
                {
                    dataTypeInfos = dataTypeInfos.Where(dt => dt.DataTypeId.Equals(currentDataTypeInfo.DataTypeId)).ToList();
                }
            }

            if (currentDataTypeInfo != null)
            {
                dataTypeInfos = dataTypeInfos.Where(dt => dt.DataTypeId.Equals(currentDataTypeInfo.DataTypeId)).ToList();

                if (selectedAttribute == 0)
                {
                    dataAttributeInfos = dataAttributeInfos.Where(d => d.DataTypeId.Equals(currentDataTypeInfo.DataTypeId)).ToList();
                }
                else
                {
                    dataAttributeInfos = dataAttributeInfos.Where(d => d.Id.Equals(currentDataAttrInfo.Id)).ToList();
                }

                if (selectedUnit == 0)
                {
                    unitInfos = unitInfos.Where(u => u.DataTypeInfos.Any(d => d.DataTypeId.Equals(currentDataTypeInfo.DataTypeId))).ToList();
                }
                else
                {
                    unitInfos.Where(u => u.UnitId.Equals(currentUnit.UnitId) || u.DimensionId.Equals(currentUnit.DimensionId)).ToList();
                }
            }


            if (currentDataAttrInfo != null)
            {
                // is the seletced currentDataAttrInfo a suggestion then overrigth all selected items
                if (currentDataAttrInfo.Id > 0)
                {
                    #region existing selected dataset

                    if (suggestions.Any(s => s.attributeName.Equals(currentDataAttrInfo.Name)))
                    {
                        dataAttributeInfos = dataAttributeInfos.Where(d => d.Id.Equals(currentDataAttrInfo.Id)).ToList();
                        unitInfos          = unitInfos.Where(u => u.UnitId.Equals(currentDataAttrInfo.UnitId) || u.DimensionId.Equals(currentDataAttrInfo.DimensionId)).ToList();
                        dataTypeInfos      = unitInfos.SelectMany(u => u.DataTypeInfos).GroupBy(d => d.DataTypeId).Select(g => g.Last()).ToList();

                        if (lastSelection == "Suggestions")
                        {
                            currentUnit         = unitInfos.FirstOrDefault(u => u.UnitId.Equals(dataAttributeInfos.First().UnitId));
                            currentDataTypeInfo = dataTypeInfos.FirstOrDefault(d => d.DataTypeId.Equals(dataAttributeInfos.First().DataTypeId));
                        }
                    }
                    else
                    {
                        dataAttributeInfos = dataAttributeInfos.Where(d => d.Id.Equals(currentDataAttrInfo.Id)).ToList();

                        //filtering units when data attr is selected, if id or dimension is the same
                        if (selectedUnit == 0)
                        {
                            unitInfos   = unitInfos.Where(u => u.UnitId.Equals(currentDataAttrInfo.UnitId) || u.DimensionId.Equals(currentDataAttrInfo.DimensionId)).ToList();
                            currentUnit = unitInfos.FirstOrDefault(u => u.UnitId.Equals(currentDataAttrInfo.UnitId));
                        }
                        else
                        {
                            unitInfos = unitInfos.Where(u => u.UnitId.Equals(currentUnit.UnitId) || u.DimensionId.Equals(currentUnit.DimensionId)).ToList();
                        }

                        if (selectedDataType == 0)
                        {
                            dataTypeInfos = unitInfos.SelectMany(u => u.DataTypeInfos).GroupBy(d => d.DataTypeId).Select(g => g.Last()).ToList();

                            currentDataTypeInfo = dataTypeInfos.FirstOrDefault(d => d.DataTypeId.Equals(currentDataAttrInfo.DataTypeId));
                        }
                        else
                        {
                            dataTypeInfos = dataTypeInfos.Where(dt => dt.DataTypeId.Equals(currentDataTypeInfo.DataTypeId)).ToList();
                        }
                    }

                    #endregion existing selected dataset
                }
                else
                if (currentDataAttrInfo.Id == -1) //unknow
                {
                    // do nothing
                }
                else
                if (currentDataAttrInfo.Id == -2) //not found
                {
                    // do nothing
                }
            }



            #endregion


            RowModel model = new RowModel(
                index,
                varName,
                currentDataAttrInfo,
                currentUnit,
                currentDataTypeInfo,
                suggestions,
                unitInfos,
                dataAttributeInfos,
                dataTypeInfos
                );

            //update row in the bus of the taskmanager
            UpdateRowInBus(model);

            return(PartialView("Row", model));
        }
        private static bool IsTableColumnDataTypeAndLengthEquals(DatabaseType databaseType, TableColumn column1, TableColumn column2)
        {
            if (column1.IsUserDefined != column2.IsUserDefined)
            {
                return(false);
            }
            else if (column1.IsUserDefined && column2.IsUserDefined)
            {
                return(column1.DataType == column2.DataType);
            }

            DataTypeInfo dataTypeInfo1 = DataTypeHelper.GetDataTypeInfo(column1.DataType);
            DataTypeInfo dataTypeInfo2 = DataTypeHelper.GetDataTypeInfo(column2.DataType);

            var dataTypeSpecs1 = DataTypeManager.GetDataTypeSpecifications(databaseType);
            var dataTypeSpecs2 = DataTypeManager.GetDataTypeSpecifications(databaseType);

            string dataType1 = dataTypeInfo1.DataType;
            string dataType2 = dataTypeInfo2.DataType;

            if (!dataTypeSpecs1.Any(item => item.Name == dataType1))
            {
                dataTypeInfo1 = DataTypeHelper.GetSpecialDataTypeInfo(column1.DataType.ToLower());
                dataType1     = dataTypeInfo1.DataType;
            }

            if (!dataTypeSpecs2.Any(item => item.Name == dataType2))
            {
                dataTypeInfo2 = DataTypeHelper.GetSpecialDataTypeInfo(column2.DataType.ToLower());
                dataType2     = dataTypeInfo2.DataType;
            }

            if (dataType1.ToLower() != dataType2.ToLower())
            {
                return(false);
            }

            DataTypeSpecification dataTypeSpec1 = dataTypeSpecs1.FirstOrDefault(item => item.Name == dataType1);
            DataTypeSpecification dataTypeSpec2 = dataTypeSpecs2.FirstOrDefault(item => item.Name == dataType2);

            if (dataTypeInfo1.DataType == dataTypeInfo2.DataType && string.IsNullOrEmpty(dataTypeSpec1.Args) && string.IsNullOrEmpty(dataTypeSpec2.Args))
            {
                return(true);
            }

            bool isChar1 = DataTypeHelper.IsCharType(dataType1);
            bool isChar2 = DataTypeHelper.IsCharType(dataType2);

            bool isBytes1 = DataTypeHelper.IsCharType(dataType1);
            bool isBytes2 = DataTypeHelper.IsCharType(dataType2);

            if (isBytes1 && isBytes2)
            {
                return(column1.MaxLength == column2.MaxLength);
            }
            else if (isChar1 && isChar2 && DataTypeHelper.StartWithN(dataType1) && DataTypeHelper.StartWithN(dataType2))
            {
                return(column1.MaxLength == column2.MaxLength);
            }
            else if ((column1.Precision == null && column1.Scale == null && column1.MaxLength == column2.Precision) ||
                     (column2.Precision == null && column2.Scale == null && column2.MaxLength == column1.Precision))
            {
                return(true);
            }

            if (dataTypeSpec1.Name == dataTypeSpec2.Name && dataTypeSpec1.Args?.Contains("length") == false)
            {
                if (dataTypeSpec1.Args == "scale")
                {
                    return(IsPrecisionScaleEquals(column1.Scale, column2.Scale));
                }
                else if (dataTypeSpec1.Args == "precision")
                {
                    return(IsPrecisionScaleEquals(column1.Precision, column2.Precision));
                }
                else if (dataTypeSpec1.Args?.Contains("scale") == true || dataTypeSpec1.Args?.Contains("precision") == true)
                {
                    return(IsPrecisionScaleEquals(column1.Precision, column2.Precision) &&
                           IsPrecisionScaleEquals(column1.Scale, column2.Scale));
                }
            }

            return(column1.MaxLength == column2.MaxLength &&
                   IsPrecisionScaleEquals(column1.Precision, column2.Precision) &&
                   IsPrecisionScaleEquals(column1.Scale, column2.Scale));
        }
Exemplo n.º 4
0
        public string GenerateRoutineScripts(RoutineScript script)
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine($"CREATE OR REPLACE {script.Type.ToString()} {script.FullName}");

            if (script.Parameters.Count > 0)
            {
                sb.AppendLine("(");

                int i = 0;
                foreach (Parameter parameter in script.Parameters)
                {
                    ParameterType parameterType = parameter.ParameterType;

                    string dataType         = parameter.DataType.Symbol;
                    string strParameterType = "";

                    int parenthesesIndex = dataType.IndexOf("(");

                    if (parenthesesIndex > 0)
                    {
                        dataType = dataType.Substring(0, parenthesesIndex);
                    }

                    if (parameterType.HasFlag(ParameterType.IN) && parameterType.HasFlag(ParameterType.OUT))
                    {
                        strParameterType = "IN OUT";
                    }
                    else if (parameterType != ParameterType.NONE)
                    {
                        strParameterType = parameterType.ToString();
                    }

                    sb.AppendLine($"{parameter.Name} {strParameterType} {dataType}{(i == script.Parameters.Count - 1 ? "" : ",")}");

                    i++;
                }

                sb.AppendLine(")");
            }

            if (script.Type == RoutineType.FUNCTION)
            {
                if (script.ReturnDataType != null)
                {
                    string dataType = script.ReturnDataType.Symbol;

                    if (DataTypeHelper.IsCharType(dataType))
                    {
                        DataTypeInfo dataTypeInfo = DataTypeHelper.GetDataTypeInfo(dataType);
                        dataType = dataTypeInfo.DataType;
                    }

                    sb.AppendLine($"RETURN {dataType}");
                }
                else if (script.ReturnTable != null)
                {
                    //sb.AppendLine($"RETURN {script.ReturnTable}");
                }
            }

            sb.AppendLine("AS");

            foreach (Statement statement in script.Statements.Where(item => item is DeclareStatement || item is DeclareCursorStatement))
            {
                sb.Append(this.BuildStatement(statement).Replace("DECLARE ", ""));
            }

            sb.AppendLine("BEGIN");

            if (script.ReturnTable != null)
            {
            }

            FetchCursorStatement fetchCursorStatement = null;

            foreach (Statement statement in script.Statements.Where(item => !(item is DeclareStatement || item is DeclareCursorStatement)))
            {
                if (statement is FetchCursorStatement fetch)
                {
                    fetchCursorStatement = fetch;
                    continue;
                }
                else if (statement is WhileStatement @while)
                {
                    FetchCursorStatement fs = @while.Statements.FirstOrDefault(item => item is FetchCursorStatement) as FetchCursorStatement;

                    if (fetchCursorStatement != null && fs != null)
                    {
                        @while.Condition.Symbol = "1=1";

                        if (fs.Variables.Count == 0)
                        {
                            @while.Statements.Insert(0, new LoopExitStatement()
                            {
                                Condition = new TokenInfo($"{fs.CursorName}%NOTFOUND")
                            });
                            @while.Statements.Insert(0, fetchCursorStatement);
                        }
                    }
                }

                sb.AppendLine(this.BuildStatement(statement));
            }

            sb.AppendLine($"END {script.FullName};");

            return(this.FormatScripts(sb.ToString()));
        }
Exemplo n.º 5
0
        protected override Type GetSystemType(string dataType, string columnType, DataTypeInfo dataTypeInfo, long? length, int? precision, int? scale)
        {
            if (dataType == "NUMBER" && precision > 0 && (scale ?? 0) == 0)
            {
                if (precision <  3) return typeof(sbyte);
                if (precision <  5) return typeof(short);
                if (precision < 10) return typeof(int);
                if (precision < 20) return typeof(long);
            }

            if (dataType.StartsWith("TIMESTAMP"))
                return dataType.EndsWith("TIME ZONE") ? typeof(DateTimeOffset) : typeof(DateTime);

            return base.GetSystemType(dataType, columnType, dataTypeInfo, length, precision, scale);
        }
Exemplo n.º 6
0
        private SqlValueType CreateValueType(IDataRecord row,
                                             int typeNameIndex, int precisionIndex, int scaleIndex, int charLengthIndex)
        {
            string typeName   = row.GetString(typeNameIndex).ToUpperInvariant();
            string columnName = row.GetString(6).ToUpperInvariant();

            int precision = row.IsDBNull(precisionIndex) ? DefaultPrecision : ReadInt(row, precisionIndex);
            int scale     = row.IsDBNull(scaleIndex) ? DefaultScale : ReadInt(row, scaleIndex);

            var decimalAssignedNames = new List <string>()
            {
                "DECIMAL", "NUMERIC", "NUMBER"
            };
            var doubleAssignedNames = new List <string>()
            {
                "DOUBLE", "REAL"
            };

            if (decimalAssignedNames.Contains(typeName))
            {
                return(new SqlValueType(SqlType.Decimal, precision, scale));
            }

            if (doubleAssignedNames.Contains(typeName))
            {
                return(new SqlValueType(SqlType.Double));
            }

            if (columnName == "TINYINT(1)")
            {
                return(new SqlValueType(SqlType.Boolean));
            }

            if (typeName.StartsWith("TINYINT"))
            {
                // ignoring "day precision" and "second precision"
                // although they can be read as "scale" and "precision"
                return(new SqlValueType(SqlType.Int8));
            }

            if (typeName.StartsWith("SMALLINT"))
            {
                // ignoring "day precision" and "second precision"
                // although they can be read as "scale" and "precision"
                return(new SqlValueType(SqlType.Int16));
            }

            if (typeName.StartsWith("MEDIUMINT")) //There is not 34bit Int in SqlType
            {
                // ignoring "day precision" and "second precision"
                // although they can be read as "scale" and "precision"
                return(new SqlValueType(SqlType.Int32));
            }

            if (typeName.StartsWith("INT"))
            {
                // ignoring "day precision" and "second precision"
                // although they can be read as "scale" and "precision"
                return(new SqlValueType(SqlType.Int32));
            }

            if (typeName.StartsWith("BIGINT"))
            {
                // ignoring "day precision" and "second precision"
                // although they can be read as "scale" and "precision"
                return(new SqlValueType(SqlType.Int64));
            }

            if (typeName.StartsWith("TIME"))
            {
                // "timestamp precision" is saved as "scale", ignoring too
                return(new SqlValueType(SqlType.DateTime));
            }
            if (typeName.StartsWith("YEAR"))
            {
                // "timestamp precision" is saved as "scale", ignoring too
                return(new SqlValueType(SqlType.Decimal, 4, 0));
            }

            if (typeName == "LONGTEXT")
            {
                return(new SqlValueType(SqlType.VarCharMax));
            }

            if (typeName.Contains("TEXT"))
            {
                int length = ReadInt(row, charLengthIndex);
                return(new SqlValueType(SqlType.VarCharMax, length));
            }

            if (typeName.Contains("BLOB"))
            {
                return(new SqlValueType(SqlType.VarBinaryMax));
            }

            if (typeName == "VARBINARY")
            {
                int length = ReadInt(row, charLengthIndex);
                return(new SqlValueType(SqlType.VarBinary, length));
            }

            if (typeName == "VARCHAR" || typeName == "CHAR")
            {
                int     length  = Convert.ToInt32(row[charLengthIndex]);
                SqlType sqlType = typeName.Length == 4 ? SqlType.Char : SqlType.VarChar;
                return(new SqlValueType(sqlType, length));
            }
            DataTypeInfo typeInfo = Driver.ServerInfo.DataTypes[typeName];

            return(typeInfo != null
        ? new SqlValueType(typeInfo.Type)
        : new SqlValueType(typeName));
        }
Exemplo n.º 7
0
        private void btnModField_Click(object sender, EventArgs e)
        {
            StdFieldInfo aftermodstdFieldInfo = new StdFieldInfo();

            aftermodstdFieldInfo.Gid         = _beforemodstdFieldInfo.Gid;
            aftermodstdFieldInfo.Name        = txtName.Text.Trim();
            aftermodstdFieldInfo.ChineseName = txtChineseName.Text.Trim();
            aftermodstdFieldInfo.DataType    = lueFieldType.EditValue.ToString();

            StringBuilder content = new StringBuilder();

            #region 检查一下字段是否存在
            foreach (StdFieldInfo dataTypeInfo in _lstDataTypeInfo)
            {
                if (string.IsNullOrEmpty(dataTypeInfo.Gid))
                {
                    continue;
                }

                // 与别的字段重名,不允许修改
                if (string.Equals(aftermodstdFieldInfo.Name, dataTypeInfo.Name) && !string.Equals(_beforemodstdFieldInfo.Name, dataTypeInfo.Name))
                {
                    LogHelper.WriteLog(LogLevel.LOG_LEVEL_ERR, "该标准字段已存在,不允许修改", typeof(FrmModField));
                    MessageDxUtil.ShowWarning("该标准字段已存在,不允许修改");
                    return;
                }
            }
            #endregion

            #region 取project.xml 判断当前数据库
            XmlHelper   xmlprojectthelper = new XmlHelper(@"XML\project.xml");
            XmlNodeList xmlprejectNodeLst = xmlprojectthelper.Read("datatype");

            if (xmlprejectNodeLst.Count == 0)
            {
                return;
            }

            XmlNode xn1project = xmlprejectNodeLst[0];

            // 将节点转换为元素,便于得到节点的属性值
            XmlElement xeproject = (XmlElement)xn1project;

            // 得到DataTypeInfo节点的所有子节点
            XmlNodeList xnl0project = xeproject.ChildNodes;

            string dbType = xnl0project.Item(4).InnerText;
            #endregion

            #region 生成SQL文件
            if (!string.Equals(_beforemodstdFieldInfo.Name, aftermodstdFieldInfo.Name) || !string.Equals(_beforemodstdFieldInfo.DataType, aftermodstdFieldInfo.DataType))
            {
                // SQLServer 修改字段   exec sp_rename '表名.列名','新列名' -- 注意,单引号不可省略。
                // SQLServer 修改字段类型 alter table 表名 alter column 字段名 type not null
                // MySql 修改字段 ALTER TABLE  表名 CHANGE  旧字段名 新字段名 字段类型
                // MySql 修改字段类型 ALTER TABLE  表名 CHANGE  字段名 字段名 新字段类型
                string saveFile = FileDialogHelper.SaveText("更新字段.sql", "C:\\myares\\");
                if (!string.IsNullOrEmpty(saveFile))
                {
                    String[] sqltablefileNames = DirectoryUtil.GetFileNames(@"XML\", "*.table", true);
                    foreach (string tablefileName in sqltablefileNames)
                    {
                        LogHelper.WriteLog(LogLevel.LOG_LEVEL_DEBUG, string.Format("开始变更{0}文件中变更前字段为{1}", tablefileName, _beforemodstdFieldInfo.Name), typeof(FrmModField));
                        XmlHelper xmltablehelper = new XmlHelper(tablefileName);
                        try
                        {
                            XmlNodeList xmlNodeLst = xmltablehelper.Read("datatype/fieldsinfo");
                            for (Int32 i = 0; i < xmlNodeLst.Count; i++)
                            {
                                // 字段变更
                                if (string.Equals(xmlNodeLst[i].ChildNodes.Item(0).InnerText, _beforemodstdFieldInfo.Name) && !string.Equals(_beforemodstdFieldInfo.Name, aftermodstdFieldInfo.Name))
                                {
                                    #region 读取Table.xml 配置信息

                                    XmlHelper   xmltableshelper            = new XmlHelper(@"XML\tables.xml");
                                    XmlNodeList xmlNodeLst22               = xmltableshelper.Read("datatype/tabletype");
                                    Dictionary <string, string> guidGroup  = new Dictionary <string, string>();
                                    Dictionary <string, string> tableGroup = new Dictionary <string, string>();
                                    guidGroup.Clear();
                                    tableGroup.Clear();
                                    foreach (XmlNode xn1 in xmlNodeLst22)
                                    {
                                        // 将节点转换为元素,便于得到节点的属性值
                                        XmlElement xe = (XmlElement)xn1;

                                        // 获取字符串中的英文字母 [a-zA-Z]+
                                        string GroupEnglishName = CRegex.GetText(xe.GetAttribute("name").ToString(), "[a-zA-Z]+", 0);

                                        guidGroup.Add(xe.GetAttribute("gid").ToString(), string.Format("{0}{1}_", Const.TablePre, GroupEnglishName));
                                    }

                                    XmlNodeList xmlNodeLst2 = xmltableshelper.Read("datatype/dataitem");
                                    foreach (XmlNode xn1 in xmlNodeLst2)
                                    {
                                        // 将节点转换为元素,便于得到节点的属性值
                                        XmlElement xe = (XmlElement)xn1;
                                        // 得到Type和ISBN两个属性的属性值

                                        // 得到ConstantInfo节点的所有子节点
                                        XmlNodeList xnl0 = xe.ChildNodes;

                                        tableGroup.Add(xnl0.Item(0).InnerText, guidGroup[xnl0.Item(3).InnerText]);
                                    }
                                    #endregion

                                    string tableName = xmltablehelper.Read("datatype/basicinfo/item/name").Item(0).InnerText;
                                    content.Append(string.Format("exec sp_rename '{0}.{1}','{2}';\r\nGO\r\n\r\n", tableGroup[tableName] + tableName, _beforemodstdFieldInfo.Name, aftermodstdFieldInfo.Name));
                                }

                                if (string.Equals(xmlNodeLst[i].ChildNodes.Item(0).InnerText, _beforemodstdFieldInfo.Name) && !string.Equals(_beforemodstdFieldInfo.DataType, aftermodstdFieldInfo.DataType))
                                {
                                    #region 先读取datatype.xml 在读取defaulttype.xml 然后Linq 查询保存到数据字典dic中
                                    XmlHelper           xmldatatypehelper  = new XmlHelper(@"XML\datatype.xml");
                                    XmlNodeList         xmldatatypeNodeLst = xmldatatypehelper.Read("datatype");
                                    List <DataTypeInfo> dataTypeInfoList   = new List <DataTypeInfo>();
                                    foreach (XmlNode xn1 in xmldatatypeNodeLst)
                                    {
                                        DataTypeInfo dataTypeInfo = new DataTypeInfo();
                                        // 将节点转换为元素,便于得到节点的属性值
                                        XmlElement xe = (XmlElement)xn1;
                                        // 得到Type和ISBN两个属性的属性值
                                        dataTypeInfo.Gid = xe.GetAttribute("gid").ToString();

                                        // 得到DataTypeInfo节点的所有子节点
                                        XmlNodeList xnl0 = xe.ChildNodes;
                                        dataTypeInfo.Name      = xnl0.Item(0).InnerText;
                                        dataTypeInfo.StdType   = xnl0.Item(2).InnerText;
                                        dataTypeInfo.Length    = xnl0.Item(3).InnerText;
                                        dataTypeInfo.Precision = xnl0.Item(4).InnerText;

                                        dataTypeInfoList.Add(dataTypeInfo);
                                    }

                                    XmlHelper   defaulttypexmlHelper  = new XmlHelper(@"XML\defaulttype.xml");
                                    XmlNodeList defaulttypexmlNodeLst = defaulttypexmlHelper.Read("datatype");
                                    Dictionary <string, string> dict  = new Dictionary <string, string>();
                                    foreach (var dataTypeInfo in dataTypeInfoList)
                                    {
                                        foreach (XmlNode xn1 in defaulttypexmlNodeLst)
                                        {
                                            // 将节点转换为元素,便于得到节点的属性值
                                            XmlElement xe = (XmlElement)xn1;
                                            // 得到DataTypeInfo节点的所有子节点
                                            XmlNodeList xnl0  = xe.ChildNodes;
                                            string      value = string.Empty;
                                            if (dbType == "Oracle")
                                            {
                                                value = xnl0.Item(2).InnerText;
                                            }
                                            else if (dbType == "Mysql")
                                            {
                                                value = xnl0.Item(3).InnerText;
                                            }
                                            else if (dbType == "DB2")
                                            {
                                                value = xnl0.Item(4).InnerText;
                                            }
                                            else if (dbType == "SqlServer")
                                            {
                                                value = xnl0.Item(5).InnerText;
                                            }
                                            else if (dbType == "Sqlite")
                                            {
                                                value = xnl0.Item(6).InnerText;
                                            }
                                            else if (dbType == "Access")
                                            {
                                                value = xnl0.Item(7).InnerText;
                                            }

                                            // 找到匹配记录
                                            if (dataTypeInfo.StdType == xnl0.Item(0).InnerText)
                                            {
                                                if (value.Contains("$L"))
                                                {
                                                    if (String.Empty == dataTypeInfo.Length)
                                                    {
                                                        value = value.Replace("$L", "0");
                                                    }
                                                    else
                                                    {
                                                        value = value.Replace("$L", dataTypeInfo.Length);
                                                    }
                                                }
                                                if (value.Contains("$P"))
                                                {
                                                    if (String.Empty == dataTypeInfo.Precision)
                                                    {
                                                        value = value.Replace("$P", "0");
                                                    }
                                                    else
                                                    {
                                                        value = value.Replace("$P", dataTypeInfo.Precision);
                                                    }
                                                }
                                                dict.Add(dataTypeInfo.Name, value);
                                            }
                                        }
                                    }
                                    #endregion

                                    #region 读取Table.xml 配置信息

                                    XmlHelper   xmltableshelper            = new XmlHelper(@"XML\tables.xml");
                                    XmlNodeList xmlNodeLst22               = xmltableshelper.Read("datatype/tabletype");
                                    Dictionary <string, string> guidGroup  = new Dictionary <string, string>();
                                    Dictionary <string, string> tableGroup = new Dictionary <string, string>();
                                    guidGroup.Clear();
                                    tableGroup.Clear();
                                    foreach (XmlNode xn1 in xmlNodeLst22)
                                    {
                                        // 将节点转换为元素,便于得到节点的属性值
                                        XmlElement xe = (XmlElement)xn1;

                                        // 获取字符串中的英文字母 [a-zA-Z]+
                                        string GroupEnglishName = CRegex.GetText(xe.GetAttribute("name").ToString(), "[a-zA-Z]+", 0);

                                        guidGroup.Add(xe.GetAttribute("gid").ToString(), string.Format("{0}{1}_", Const.TablePre, GroupEnglishName));
                                    }

                                    XmlNodeList xmlNodeLst2 = xmltableshelper.Read("datatype/dataitem");
                                    foreach (XmlNode xn1 in xmlNodeLst2)
                                    {
                                        // 将节点转换为元素,便于得到节点的属性值
                                        XmlElement xe = (XmlElement)xn1;
                                        // 得到Type和ISBN两个属性的属性值

                                        // 得到ConstantInfo节点的所有子节点
                                        XmlNodeList xnl0 = xe.ChildNodes;

                                        tableGroup.Add(xnl0.Item(0).InnerText, guidGroup[xnl0.Item(3).InnerText]);
                                    }
                                    #endregion

                                    string tableName = xmltablehelper.Read("datatype/basicinfo/item/name").Item(0).InnerText;
                                    content.Append(string.Format("alter table {0} alter column {1} {2};\r\nGO\r\n\r\n", tableGroup[tableName] + tableName, aftermodstdFieldInfo.Name, dict[aftermodstdFieldInfo.DataType]));
                                }
                            }
                            xmltablehelper.Save(false);
                        }
                        catch (Exception ex)
                        {
                            LogHelper.WriteLog(LogLevel.LOG_LEVEL_CRIT, ex, typeof(FrmModField));
                            MessageDxUtil.ShowError(ex.Message);
                        }
                        LogHelper.WriteLog(LogLevel.LOG_LEVEL_DEBUG, string.Format("结束变更{0}文件中变更前字段为{1}", tablefileName, _beforemodstdFieldInfo.Name), typeof(FrmModField));
                    }

                    FileUtil.WriteText(saveFile, content.ToString(), Encoding.UTF8);

                    if (MessageDxUtil.ShowYesNoAndTips("保存成功,是否打开文件?") == System.Windows.Forms.DialogResult.Yes)
                    {
                        System.Diagnostics.Process.Start(saveFile);
                    }
                }
            }
            #endregion

            #region 修改*.table 字段
            String[] tablefileNames = DirectoryUtil.GetFileNames(@"XML\", "*.table", true);
            foreach (string tablefileName in tablefileNames)
            {
                LogHelper.WriteLog(LogLevel.LOG_LEVEL_DEBUG, string.Format("开始变更{0}文件中变更前字段为{1}", tablefileName, _beforemodstdFieldInfo.Name), typeof(FrmModField));
                XmlHelper xmltablehelper = new XmlHelper(tablefileName);
                try
                {
                    #region 更新数据
                    if (!string.Equals(_beforemodstdFieldInfo.Name, aftermodstdFieldInfo.Name))
                    {
                        XmlNodeList xmlNodeLst = xmltablehelper.Read("datatype/fieldsinfo");
                        for (Int32 i = 0; i < xmlNodeLst.Count; i++)
                        {
                            if (string.Equals(xmlNodeLst[i].ChildNodes.Item(0).InnerText, _beforemodstdFieldInfo.Name))
                            {
                                xmlNodeLst[i].ChildNodes.Item(0).InnerText = aftermodstdFieldInfo.Name;
                            }
                        }
                    }
                    xmltablehelper.Save(false);
                    #endregion
                }
                catch (Exception ex)
                {
                    LogHelper.WriteLog(LogLevel.LOG_LEVEL_CRIT, ex, typeof(FrmModField));
                    MessageDxUtil.ShowError(ex.Message);
                }
                LogHelper.WriteLog(LogLevel.LOG_LEVEL_DEBUG, string.Format("结束变更{0}文件中变更前字段为{1}", tablefileName, _beforemodstdFieldInfo.Name), typeof(FrmModField));
            }
            #endregion

            #region 修改*.entity 字段
            String[] entityfileNames = DirectoryUtil.GetFileNames(@"XML\", "*.entity", true);
            foreach (string entityfileName in entityfileNames)
            {
                LogHelper.WriteLog(LogLevel.LOG_LEVEL_DEBUG, string.Format("开始变更{0}文件中变更前字段为{1}", entityfileName, _beforemodstdFieldInfo.Name), typeof(FrmModField));
                XmlHelper xmlentityhelper = new XmlHelper(entityfileName);
                try
                {
                    #region 更新数据
                    if (!string.Equals(_beforemodstdFieldInfo.Name, aftermodstdFieldInfo.Name))
                    {
                        XmlNodeList xmlNodeLst = xmlentityhelper.Read("datatype/fieldsinfo");
                        for (Int32 i = 0; i < xmlNodeLst.Count; i++)
                        {
                            if (string.Equals(xmlNodeLst[i].ChildNodes.Item(0).InnerText, _beforemodstdFieldInfo.Name))
                            {
                                xmlNodeLst[i].ChildNodes.Item(0).InnerText = aftermodstdFieldInfo.Name;
                            }
                        }
                    }
                    xmlentityhelper.Save(false);
                    #endregion
                }
                catch (Exception ex)
                {
                    LogHelper.WriteLog(LogLevel.LOG_LEVEL_CRIT, ex, typeof(FrmModField));
                    MessageDxUtil.ShowError(ex.Message);
                }
                LogHelper.WriteLog(LogLevel.LOG_LEVEL_DEBUG, string.Format("结束变更{0}文件中变更前字段为{1}", entityfileName, _beforemodstdFieldInfo.Name), typeof(FrmModField));
            }
            #endregion

            #region 修改stdfield.xml文件
            XmlHelper xmlstdfieldhelper = new XmlHelper(@"XML\stdfield.xml");
            try
            {
                #region 更新数据
                if (!string.Equals(_beforemodstdFieldInfo.Name, aftermodstdFieldInfo.Name))
                {
                    xmlstdfieldhelper.Replace(string.Format("datatype/dataitem/item[@gid=\"{0}\"]/name", aftermodstdFieldInfo.Gid), aftermodstdFieldInfo.Name);
                }
                if (!string.Equals(_beforemodstdFieldInfo.ChineseName, aftermodstdFieldInfo.ChineseName))
                {
                    xmlstdfieldhelper.Replace(string.Format("datatype/dataitem/item[@gid=\"{0}\"]/chineseName", aftermodstdFieldInfo.Gid), aftermodstdFieldInfo.ChineseName);
                }
                if (!string.Equals(_beforemodstdFieldInfo.DataType, aftermodstdFieldInfo.DataType))
                {
                    xmlstdfieldhelper.Replace(string.Format("datatype/dataitem/item[@gid=\"{0}\"]/datatype", aftermodstdFieldInfo.Gid), aftermodstdFieldInfo.DataType);
                }
                xmlstdfieldhelper.Save(false);
                #endregion
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(LogLevel.LOG_LEVEL_CRIT, ex, typeof(FrmModField));
                MessageDxUtil.ShowError(ex.Message);
            }
            #endregion



            this.Close();
        }
Exemplo n.º 8
0
        protected override Type GetSystemType(string columnType, DataTypeInfo dataType, int length, int precision, int scale)
        {
            switch (columnType)
            {
                case "datetime2" : return typeof(DateTime);
            }

            return base.GetSystemType(columnType, dataType, length, precision, scale);
        }
        public void ConvertDataType(TableColumn column)
        {
            string originalDataType = column.DataType;

            DataTypeInfo dataTypeInfo   = DataTypeHelper.GetDataTypeInfo(this.sourceDbInterpreter, originalDataType);
            string       sourceDataType = dataTypeInfo.DataType;

            column.DataType = sourceDataType;

            DataTypeSpecification sourceDataTypeSpec = this.GetDataTypeSpecification(this.sourceDataTypeSpecs, sourceDataType);

            if (!string.IsNullOrEmpty(dataTypeInfo.Args))
            {
                if (sourceDataTypeSpec.Args == "scale")
                {
                    column.Scale = int.Parse(dataTypeInfo.Args);
                }
                else if (sourceDataTypeSpec.Args == "length")
                {
                    if (column.MaxLength == null)
                    {
                        column.MaxLength = int.Parse(dataTypeInfo.Args);
                    }
                }
            }

            DataTypeMapping dataTypeMapping = this.dataTypeMappings.FirstOrDefault(item => item.Source.Type?.ToLower() == column.DataType?.ToLower() ||
                                                                                   (item.Source.IsExpression && Regex.IsMatch(column.DataType, item.Source.Type, RegexOptions.IgnoreCase))
                                                                                   );

            if (dataTypeMapping != null)
            {
                DataTypeMappingSource sourceMapping = dataTypeMapping.Source;
                DataTypeMappingTarget targetMapping = dataTypeMapping.Target;
                string targetDataType = targetMapping.Type;

                DataTypeSpecification targetDataTypeSpec = this.GetDataTypeSpecification(this.targetDataTypeSpecs, targetDataType);

                column.DataType = targetDataType;

                bool isChar   = DataTypeHelper.IsCharType(column.DataType);
                bool isBinary = DataTypeHelper.IsBinaryType(column.DataType);

                if (isChar || isBinary)
                {
                    if (isChar)
                    {
                        if (!string.IsNullOrEmpty(targetMapping.Length))
                        {
                            column.MaxLength = int.Parse(targetMapping.Length);

                            if (DataTypeHelper.StartWithN(targetDataType) && !DataTypeHelper.StartWithN(sourceDataType))
                            {
                                column.MaxLength *= 2;
                            }
                        }
                    }

                    if (dataTypeMapping.Specials != null && dataTypeMapping.Specials.Count > 0)
                    {
                        DataTypeMappingSpecial special = dataTypeMapping.Specials.FirstOrDefault(item => this.IsSpecialMaxLengthMatched(item, column));

                        if (special != null)
                        {
                            column.DataType = special.Type;

                            if (!string.IsNullOrEmpty(special.TargetMaxLength))
                            {
                                column.MaxLength = int.Parse(special.TargetMaxLength);
                            }
                        }
                    }

                    if (column.MaxLength == -1)
                    {
                        ArgumentRange?sourceLengthRange = DataTypeManager.GetArgumentRange(sourceDataTypeSpec, "length");

                        if (sourceLengthRange.HasValue)
                        {
                            column.MaxLength = sourceLengthRange.Value.Max;
                        }
                    }

                    ArgumentRange?targetLengthRange = DataTypeManager.GetArgumentRange(targetDataTypeSpec, "length");

                    if (targetLengthRange.HasValue)
                    {
                        int targetMaxLength = targetLengthRange.Value.Max;

                        if (column.MaxLength > targetMaxLength)
                        {
                            if (!string.IsNullOrEmpty(targetMapping.Substitute))
                            {
                                string[] substitutes = targetMapping.Substitute.Split(',');

                                foreach (string substitute in substitutes)
                                {
                                    DataTypeSpecification dataTypeSpec = this.GetDataTypeSpecification(this.targetDataTypeSpecs, substitute.Trim());

                                    if (dataTypeSpec != null)
                                    {
                                        if (string.IsNullOrEmpty(dataTypeSpec.Args))
                                        {
                                            column.DataType = substitute;
                                            break;
                                        }
                                        else
                                        {
                                            ArgumentRange?range = DataTypeManager.GetArgumentRange(dataTypeSpec, "length");

                                            if (range.HasValue && range.Value.Max >= column.MaxLength)
                                            {
                                                column.DataType = substitute;
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    if (dataTypeMapping.Specials != null && dataTypeMapping.Specials.Count > 0)
                    {
                        foreach (DataTypeMappingSpecial special in dataTypeMapping.Specials)
                        {
                            string name    = special.Name;
                            bool   matched = false;

                            if (name == "maxLength")
                            {
                                matched = this.IsSpecialMaxLengthMatched(special, column);
                            }
                            else if (name.Contains("precision") || name.Contains("scale"))
                            {
                                matched = this.IsSpecialPrecisionOrScaleMatched(special, column);
                            }
                            else if (name == "expression")
                            {
                                matched = this.IsSpecialExpressionMatched(special, originalDataType);
                            }

                            if (matched)
                            {
                                column.DataType = special.Type;
                            }

                            if (!string.IsNullOrEmpty(special.TargetMaxLength))
                            {
                                column.MaxLength = int.Parse(special.TargetMaxLength);
                            }
                        }
                    }

                    if (string.IsNullOrEmpty(targetDataTypeSpec.Format))
                    {
                        bool useConfigPrecisionScale = false;

                        if (!string.IsNullOrEmpty(targetMapping.Precision))
                        {
                            column.Precision = int.Parse(targetMapping.Precision);

                            useConfigPrecisionScale = true;
                        }

                        if (!string.IsNullOrEmpty(targetMapping.Scale))
                        {
                            column.Scale = int.Parse(targetMapping.Scale);

                            useConfigPrecisionScale = true;
                        }

                        if (!useConfigPrecisionScale)
                        {
                            if (sourceDataTypeSpec.Args == "scale")
                            {
                                column.Precision = default(int?);
                            }
                            else if (sourceDataTypeSpec.Args == "precision,scale" && sourceDataTypeSpec.Args == targetDataTypeSpec.Args)
                            {
                                ArgumentRange?precisionRange = DataTypeManager.GetArgumentRange(targetDataTypeSpec, "precision");
                                ArgumentRange?scaleRange     = DataTypeManager.GetArgumentRange(targetDataTypeSpec, "scale");

                                if (precisionRange.HasValue && column.Precision > precisionRange.Value.Max)
                                {
                                    column.Precision = precisionRange.Value.Max;
                                }

                                if (scaleRange.HasValue && column.Scale > scaleRange.Value.Max)
                                {
                                    column.Scale = scaleRange.Value.Max;
                                }

                                if (column.Precision.HasValue)
                                {
                                    if (column.DataType.ToLower() == "int")
                                    {
                                        if (column.Precision.Value > 10)
                                        {
                                            column.DataType = "bigint";
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        string format   = targetDataTypeSpec.Format;
                        string dataType = format;

                        string[] defaultValues     = targetDataTypeSpec.Default?.Split(',');
                        string   targetMappingArgs = targetMapping.Args;

                        int i = 0;
                        foreach (DataTypeArgument arg in targetDataTypeSpec.Arugments)
                        {
                            if (arg.Name.ToLower() == "scale")
                            {
                                ArgumentRange?targetScaleRange = DataTypeManager.GetArgumentRange(targetDataTypeSpec, "scale");

                                int scale = column.Scale == null ? 0 : column.Scale.Value;

                                if (targetScaleRange.HasValue && scale > targetScaleRange.Value.Max)
                                {
                                    scale = targetScaleRange.Value.Max;
                                }

                                dataType = dataType.Replace("$scale$", scale.ToString());
                            }
                            else
                            {
                                string defaultValue = defaultValues != null && defaultValues.Length > i ? defaultValues[i] : "";

                                string value = defaultValue;

                                if (targetMapping.Arguments.Any(item => item.Name == arg.Name))
                                {
                                    value = targetMapping.Arguments.FirstOrDefault(item => item.Name == arg.Name).Value;
                                }

                                dataType = dataType.Replace($"${arg.Name}$", value);
                            }

                            i++;
                        }

                        column.DataType = dataType;
                    }
                }
            }
        }
Exemplo n.º 10
0
        protected override Type GetSystemType(string columnType, DataTypeInfo dataType, int length, int precision, int scale)
        {
            switch (columnType)
            {
                case "hierarchyid" :
                case "geography"   :
                case "geometry"    : return SqlServerDataProvider.GetUdtType(columnType);
            }

            return base.GetSystemType(columnType, dataType, length, precision, scale);
        }
Exemplo n.º 11
0
 public MySQLiteObjectMap(string name, DataTypeInfo dataType)
 {
     this.Name     = name;
     this.DataType = dataType;
 }
        public override DataTypeCollection GetDataTypesInfo()
        {
            var commonFeatures =
                DataTypeFeatures.Clustering |
                DataTypeFeatures.Grouping |
                DataTypeFeatures.Indexing |
                DataTypeFeatures.KeyConstraint |
                DataTypeFeatures.Nullable |
                DataTypeFeatures.Ordering |
                DataTypeFeatures.Multiple |
                DataTypeFeatures.Default;

            var dtc = new DataTypeCollection();

            dtc.Boolean = DataTypeInfo.Range(SqlType.Boolean, commonFeatures,
                                             ValueRange.Bool, "boolean", "bool");

            dtc.Int16 = DataTypeInfo.Range(SqlType.Int16, commonFeatures,
                                           ValueRange.Int16,
                                           "smallint", "int2");

            dtc.Int32 = DataTypeInfo.Range(SqlType.Int32, commonFeatures,
                                           ValueRange.Int32, "integer", "int4");

            dtc.Int64 = DataTypeInfo.Range(SqlType.Int64, commonFeatures,
                                           ValueRange.Int64, "bigint", "int8");

            dtc.Decimal = DataTypeInfo.Fractional(SqlType.Decimal, commonFeatures,
                                                  ValueRange.Decimal, 49, "numeric", "decimal");

            dtc.Float = DataTypeInfo.Range(SqlType.Float, commonFeatures,
                                           ValueRange.Float, "real", "float4");

            dtc.Double = DataTypeInfo.Range(SqlType.Double, commonFeatures,
                                            ValueRange.Double, "double precision", "float8");

            dtc.DateTime = DataTypeInfo.Range(SqlType.DateTime, commonFeatures,
                                              ValueRange.DateTime, "timestamp");

            dtc.Interval = DataTypeInfo.Range(SqlType.Interval, commonFeatures,
                                              ValueRange.TimeSpan, "interval");

            dtc.Char         = DataTypeInfo.Stream(SqlType.Char, commonFeatures, MaxCharLength, "character", "char", "bpchar");
            dtc.VarChar      = DataTypeInfo.Stream(SqlType.VarChar, commonFeatures, MaxCharLength, "character varying", "varchar");
            dtc.VarCharMax   = DataTypeInfo.Regular(SqlType.VarCharMax, commonFeatures, "text");
            dtc.VarBinaryMax = DataTypeInfo.Stream(SqlType.VarBinaryMax, commonFeatures, MaxTextLength, "bytea");

            dtc.DateTimeOffset = DataTypeInfo.Range(SqlType.DateTimeOffset, commonFeatures,
                                                    new ValueRange <DateTimeOffset>(new DateTimeOffset(1, 1, 1, 0, 0, 0, 0, new TimeSpan(0)),
                                                                                    new DateTimeOffset(9999, 12, 31, 0, 0, 0, 0, new TimeSpan(0))),
                                                    "timestamptz");

            var geo = DataTypeFeatures.Default | DataTypeFeatures.Nullable | DataTypeFeatures.Multiple | DataTypeFeatures.Spatial;

            dtc.Add(CustomSqlType.Point, DataTypeInfo.Regular(CustomSqlType.Point, geo, "point"));
            dtc.Add(CustomSqlType.LSeg, DataTypeInfo.Regular(CustomSqlType.LSeg, geo, "lseg"));
            dtc.Add(CustomSqlType.Box, DataTypeInfo.Regular(CustomSqlType.Box, geo, "box"));
            dtc.Add(CustomSqlType.Path, DataTypeInfo.Regular(CustomSqlType.Path, geo, "path"));
            dtc.Add(CustomSqlType.Polygon, DataTypeInfo.Regular(CustomSqlType.Polygon, geo, "polygon"));
            dtc.Add(CustomSqlType.Circle, DataTypeInfo.Regular(CustomSqlType.Circle, geo, "circle"));

            return(dtc);
        }
 private static TableSourceColumnInfo GetColumnInfo(TableSourceInfo tableSource, string columnName, DataTypeInfo dataType, bool isMandatory,
                                                    bool isPrimaryKey, AutoNumberColumnInfo autoNumberInfo)
 {
     return(new TableSourceColumnInfo(tableSource, columnName, dataType, isMandatory, isPrimaryKey, autoNumberInfo != null));
 }
Exemplo n.º 14
0
		protected override Type GetSystemType(string dataType, string columnType, DataTypeInfo dataTypeInfo, long? length, int? precision, int? scale)
		{
			if (columnType != null && columnType.Contains("unsigned"))
			{
				switch (dataType.ToLower())
				{
					case "smallint"   : return typeof(UInt16);
					case "int"        : return typeof(UInt32);
					case "mediumint"  : return typeof(UInt32);
					case "bigint"     : return typeof(UInt64);
					case "tiny int"   : return typeof(Byte);
				}
			}

			switch (dataType)
			{
				case "tinyint"   :
					if (columnType == "tinyint(1)")
						return typeof(Boolean);
					break;
				case "datetime2" : return typeof(DateTime);
			}

			return base.GetSystemType(dataType, columnType, dataTypeInfo, length, precision, scale);
		}
Exemplo n.º 15
0
 public DataTypeInfoObjectNodeFactory(DataTypeInfo dataTypeInfo)
 {
     _dataTypeInfo = dataTypeInfo;
 }
Exemplo n.º 16
0
        protected virtual Type GetSystemType(string columnType, DataTypeInfo dataType, int length, int precision, int scale)
        {
            var systemType = dataType != null ? Type.GetType(dataType.DataType) : null;

            if (length == 1 && !GenerateChar1AsString && systemType == typeof(string))
                systemType = typeof(char);

            return systemType;
        }
Exemplo n.º 17
0
 public EqualsConformity(DataTypeInfo dataTypeInfo)
 {
     this.DataTypeInfo = dataTypeInfo;
 }
Exemplo n.º 18
0
        protected override Type GetSystemType(string dataType, string columnType, DataTypeInfo dataTypeInfo, long length, int precision, int scale)
        {
            switch (dataType.ToLower())
            {
                case "tinyint" : return typeof(byte);
            }

            return base.GetSystemType(dataType, columnType, dataTypeInfo, length, precision, scale);
        }
Exemplo n.º 19
0
 public DataTypeInfoObjectNodeFactory(DataTypeInfo dataTypeInfo)
 {
     _dataTypeInfo = dataTypeInfo;
 }
        protected IEnumerable <ITableSourceColumnInfo> GetColumns(IEnumerable <TableSourceInfo> tableSources, DatabaseInfo dbInfo,
                                                                  CreateAutoNumberInfo createAutoNumber, CreateDataTypeInfo createDataType, CreateColumnInfo createColumnInfo)
        {
            var result = new List <ITableSourceColumnInfo>();

            using (IDbConnection conn = DatabaseServices.TransactionService.CreateConnection()) {
                var execService = DatabaseServices.ExecutionService as ExecutionService.ExecutionService;
                // #417717 - In these queries we don't want to use the CIAI settings
                if (execService != null)
                {
                    execService.ForceCSASSetting(conn);
                }

                IDictionary <string, AutoNumberColumnInfo> autoGeneratedColumns = new Dictionary <string, AutoNumberColumnInfo>();
                IList <TableSourceInfo> tableSourceList = tableSources.ToList();

                using (IDataReader reader = GetTriggersBulk(conn, tableSourceList, /*onlyAutoNumbers*/ true, String.Empty, dbInfo)) {
                    while (reader.Read())
                    {
                        string tableName = Convert.ToString(reader["TABLE_NAME"]);
                        if (autoGeneratedColumns.ContainsKey(tableName))
                        {
                            break;
                        }
                        string triggerName     = Convert.ToString(reader["trigger_name"]).ToUpperInvariant();
                        string triggerBody     = Convert.ToString(reader["trigger_body"]).ToUpperInvariant();
                        string triggerType     = Convert.ToString(reader["trigger_type"]).ToUpperInvariant();
                        string triggeringEvent = Convert.ToString(reader["triggering_event"]).ToUpperInvariant();
                        var    autoNumberInfo  = createAutoNumber(triggerType, triggeringEvent, triggerName, triggerBody);
                        if (autoNumberInfo != null)
                        {
                            autoGeneratedColumns[GetAutoNumberColumnKey(tableName, autoNumberInfo.ColumnName)] = autoNumberInfo;
                        }
                    }
                }

                using (IDataReader reader = GetColumnsBulk(conn, tableSourceList, dbInfo)) {
                    while (reader.Read())
                    {
                        string dataDefault    = Convert.ToString(reader["DATA_DEFAULT"]);
                        string tableName      = Convert.ToString(reader["TABLE_NAME"]);
                        string columnName     = Convert.ToString(reader["COLUMN_NAME"]);
                        object constraintType = reader["CONSTRAINT_TYPE"];
                        object dataPrecision  = reader["DATA_PRECISION"];
                        object dataScale      = reader["DATA_SCALE"];

                        bool isMandatory  = Convert.ToString(reader["NULLABLE"]).ToUpper() != "Y";
                        bool isPrimaryKey = !constraintType.Equals(DBNull.Value) && Convert.ToString(constraintType) == "P";
                        int  precision    = dataPrecision.Equals(DBNull.Value) ? 0 : Convert.ToInt32(dataPrecision);
                        int  scale        = dataScale.Equals(DBNull.Value) ? 0 : Convert.ToInt32(dataScale);

                        DataTypeInfo dataType = createDataType(Convert.ToString(reader["DATA_TYPE"]), Convert.ToInt32(reader["CHAR_LENGTH"]),
                                                               precision, scale);

                        AutoNumberColumnInfo autoNumberInfo;
                        autoGeneratedColumns.TryGetValue(GetAutoNumberColumnKey(tableName, columnName), out autoNumberInfo);

                        if (autoNumberInfo == null)   // For versions above 12c (12.1) autonumbers can be generated via identity or sequences
                        {
                            if (IsSequenceValue(dataDefault))
                            {
                                autoNumberInfo = new AutoNumberColumnInfo()
                                {
                                    ColumnName = columnName
                                };
                            }
                        }

                        TableSourceInfo tableSource = tableSourceList.First(ts => ts.Name.EqualsIgnoreCase(tableName));
                        result.Add(createColumnInfo(tableSource, columnName, dataType, isMandatory, isPrimaryKey, autoNumberInfo));
                    }
                }
            }
            return(result);
        }
Exemplo n.º 21
0
        public ActionResult Verification(object[] data)
        {
            TaskManager = (EasyUploadTaskManager)Session["TaskManager"];
            SelectVerificationModel model = new SelectVerificationModel();

            model.StepInfo = TaskManager.Current();

            if (TaskManager != null)
            {
                TaskManager.Current().SetValid(false);

                if (TaskManager.Bus.ContainsKey(EasyUploadTaskManager.VERIFICATION_MAPPEDHEADERUNITS))
                {
                    List <Tuple <int, String, UnitInfo> > mappedHeaderUnits = (List <Tuple <int, String, UnitInfo> >)TaskManager.Bus[EasyUploadTaskManager.VERIFICATION_MAPPEDHEADERUNITS];
                    //Moved handling of this case to SaveUnitSelection, just leaving it here in case of problems:

                    /*foreach (Tuple<int, String, UnitInfo> tuple in mappedHeaderUnits)
                     * {
                     *
                     *  if (tuple.Item3.SelectedDataTypeId < 0)
                     *  {
                     *      tuple.Item3.SelectedDataTypeId = tuple.Item3.DataTypeInfos.FirstOrDefault().DataTypeId;
                     *  }
                     * }*/
                    model.AssignedHeaderUnits = mappedHeaderUnits;

                    TaskManager.Current().SetValid(true);
                }
                else
                {
                    model.ErrorList.Add(new Error(ErrorType.Other, "Some Areas are not selected."));
                }

                if (TaskManager.Current().valid == true)
                {
                    TaskManager.AddExecutedStep(TaskManager.Current());
                    TaskManager.GoToNext();
                    Session["TaskManager"] = TaskManager;
                    ActionInfo actionInfo = TaskManager.Current().GetActionInfo;
                    return(RedirectToAction(actionInfo.ActionName, actionInfo.ControllerName, new RouteValueDictionary {
                        { "area", actionInfo.AreaName }, { "index", TaskManager.GetCurrentStepInfoIndex() }
                    }));
                }
                else
                {
                    TaskManager.Current().SetStatus(StepStatus.error);

                    //reload model
                    model.StepInfo = TaskManager.Current();
                }
            }

            //Default unit should be "none" if it exists, otherwise just take the first unit
            UnitInfo currentUnitInfo = model.AvailableUnits.FirstOrDefault(u => u.Name.ToLower() == "none");

            if (currentUnitInfo != null)
            {
                currentUnitInfo = (UnitInfo)currentUnitInfo.Clone();
            }
            else
            {
                currentUnitInfo = (UnitInfo)model.AvailableUnits.FirstOrDefault().Clone();
            }

            DataTypeInfo dtinfo = currentUnitInfo.DataTypeInfos.FirstOrDefault();

            currentUnitInfo.SelectedDataTypeId = dtinfo.DataTypeId;
            ViewData["defaultUnitID"]          = currentUnitInfo.UnitId;
            ViewData["defaultDatatypeID"]      = dtinfo.DataTypeId;

            return(PartialView(model));
        }
Exemplo n.º 22
0
        private void SetColumnMetaData(object compilationColumns, int hiddenColumns)
        {
            Debug.WriteLineIf(CLI.FnTrace.Enabled, "ManagedCommand.SetColumnMetaData");
            object[] descriptions = null;
            if (compilationColumns is object[])
            {
                descriptions = (object[])compilationColumns;
            }

            if (descriptions == null || descriptions.Length == 0)
            {
                columns = null;
                return;
            }

            bool hasKeyColumns = false;

            columns = new ColumnData[descriptions.Length];
            for (int i = 0; i < columns.Length; i++)
            {
                object[] description = (object[])descriptions[i];

                ColumnData column = new ColumnData();
                columns[i] = column;

                ColumnFlags flags = (ColumnFlags)description[11];

                column.columnName = (string)description[0];
                column.columnType = DataTypeInfo.MapDvType((BoxTag)description[1]);
                if (0 != (flags & ColumnFlags.CDF_XMLTYPE))
                {
                    Debug.WriteLineIf(SqlXml.Switch.TraceVerbose,
                                      String.Format("Set XML type for {0}", column.columnName));
                    column.columnType = DataTypeInfo.Xml;
                }
                if (column.columnType == null)
                {
                    throw new SystemException("Unknown data type");
                }
                column.bufferType = column.columnType.bufferType;

                column.columnSize = column.columnType.GetFieldSize((int)description[3]);
                column.precision  = (short)column.columnSize;
                column.scale      = (short)((int)description[2]);
                column.IsLong     = column.columnType.isLong;
                column.IsNullable = (0 != (int)description[4]);

                CLI.Updatable updatable = (CLI.Updatable)(int) description[5];
                column.IsReadOnly = (updatable == CLI.Updatable.SQL_ATTR_READONLY);

                column.IsAutoIncrement = (0 != (flags & ColumnFlags.CDF_AUTOINCREMENT));
                column.IsKey           = (0 != (flags & ColumnFlags.CDF_KEY));
                if (column.IsKey)
                {
                    hasKeyColumns = true;
                }

                column.IsHidden     = (i >= (columns.Length - hiddenColumns));
                column.IsRowVersion = (column.columnType == DataTypeInfo.Timestamp);
                // TODO: check for unique columns as well.
                column.IsUnique = false;

                column.baseCatalogName = (string)Values.NullIfZero(description[7]);
                column.baseColumnName  = (string)Values.NullIfZero(description[8]);
                column.baseSchemaName  = (string)Values.NullIfZero(description[9]);
                column.baseTableName   = (string)Values.NullIfZero(description[10]);

                if (column.baseTableName == null || column.baseTableName == "")
                {
                    column.IsExpression = true;
                }
                else
                {
                    column.IsExpression = false;
                }
            }

            if (uniqueRows && !hasKeyColumns)
            {
                uniqueRows = false;
            }
        }
Exemplo n.º 23
0
        public ActionResult SaveUnitSelection()
        {
            int?selectFieldId  = null;
            int?selectOptionId = null;

            //Keys submitted by Javascript in Verification.cshtml
            foreach (string key in Request.Form.AllKeys)
            {
                if ("selectFieldId" == key)
                {
                    selectFieldId = Convert.ToInt32(Request.Form[key]);
                }
                if ("selectOptionId" == key)
                {
                    selectOptionId = Convert.ToInt32(Request.Form[key]);
                }
            }

            SelectVerificationModel model = new SelectVerificationModel();

            EasyUploadTaskManager TaskManager = (EasyUploadTaskManager)Session["TaskManager"];

            if (TaskManager.Bus.ContainsKey(EasyUploadTaskManager.VERIFICATION_MAPPEDHEADERUNITS))
            {
                model.AssignedHeaderUnits = (List <Tuple <int, string, UnitInfo> >)TaskManager.Bus[EasyUploadTaskManager.VERIFICATION_MAPPEDHEADERUNITS];
            }

            if (TaskManager.Bus.ContainsKey(EasyUploadTaskManager.VERIFICATION_ATTRIBUTESUGGESTIONS))
            {
                model.Suggestions = (Dictionary <int, List <EasyUploadSuggestion> >)TaskManager.Bus[EasyUploadTaskManager.VERIFICATION_ATTRIBUTESUGGESTIONS];
            }

            /*
             * Find the selected unit and adjust the AssignedHeaderUnits
             * Also resets the Variable name
             * */
            if (selectFieldId != null && selectOptionId != null)
            {
                List <UnitInfo> availableUnits = (List <UnitInfo>)TaskManager.Bus[EasyUploadTaskManager.VERIFICATION_AVAILABLEUNITS];
                string[]        headerFields   = (string[])TaskManager.Bus[EasyUploadTaskManager.VERIFICATION_HEADERFIELDS];

                string   currentHeader = headerFields.ElementAt((int)selectFieldId);
                UnitInfo currentUnit   = availableUnits.Where(u => u.UnitId == selectOptionId).FirstOrDefault();

                Tuple <int, string, UnitInfo> existingTuple = model.AssignedHeaderUnits.Where(t => t.Item1 == (int)selectFieldId).FirstOrDefault();
                if (existingTuple != null)
                {
                    model.AssignedHeaderUnits.Remove(existingTuple);
                }
                model.AssignedHeaderUnits.Add(new Tuple <int, string, UnitInfo>((int)selectFieldId, currentHeader, currentUnit));

                //Set the Datatype to the first one suitable for the selected unit
                if (currentUnit.SelectedDataTypeId < 0)
                {
                    currentUnit.SelectedDataTypeId = currentUnit.DataTypeInfos.FirstOrDefault().DataTypeId;
                }

                //Filter the suggestions to only show those, that use the selected unit
                int index = selectFieldId ?? -1;
                List <EasyUploadSuggestion> suggestionList = null;
                if (model.Suggestions.TryGetValue(index, out suggestionList))
                {
                    if (suggestionList != null)
                    {
                        foreach (EasyUploadSuggestion suggestion in suggestionList)
                        {
                            suggestion.show = (suggestion.unitID == selectOptionId);
                        }
                    }
                }
            }

            TaskManager.AddToBus(EasyUploadTaskManager.VERIFICATION_MAPPEDHEADERUNITS, model.AssignedHeaderUnits);

            if (TaskManager.Bus.ContainsKey(EasyUploadTaskManager.VERIFICATION_HEADERFIELDS))
            {
                model.HeaderFields = (string[])TaskManager.Bus[EasyUploadTaskManager.VERIFICATION_HEADERFIELDS];
            }

            if (TaskManager.Bus.ContainsKey(EasyUploadTaskManager.VERIFICATION_AVAILABLEUNITS))
            {
                model.AvailableUnits = (List <UnitInfo>)TaskManager.Bus[EasyUploadTaskManager.VERIFICATION_AVAILABLEUNITS];
            }


            Session["TaskManager"] = TaskManager;


            //create Model
            model.StepInfo = TaskManager.Current();

            //Submit default datatype id
            //Default unit should be "none" if it exists, otherwise just take the first unit
            UnitInfo currentUnitInfo = model.AvailableUnits.FirstOrDefault(u => u.Name.ToLower() == "none");

            if (currentUnitInfo != null)
            {
                currentUnitInfo = (UnitInfo)currentUnitInfo.Clone();
            }
            else
            {
                currentUnitInfo = (UnitInfo)model.AvailableUnits.FirstOrDefault().Clone();
            }

            DataTypeInfo dtinfo = currentUnitInfo.DataTypeInfos.FirstOrDefault();

            currentUnitInfo.SelectedDataTypeId = dtinfo.DataTypeId;
            ViewData["defaultUnitID"]          = currentUnitInfo.UnitId;
            ViewData["defaultDatatypeID"]      = dtinfo.DataTypeId;

            return(PartialView("Verification", model));
        }
        public object Convert(ConfigObject configObject)
        {
            DataTypeInfo typeInfo = new DataTypeInfo();

            // 0 = "Pattern"
            int         typeOffset = 1;
            List <Guid> typeUuids  = new List <Guid>();
            int         count      = configObject.Values.Count - 1;

            for (int t = 0; t < count; t++)
            {
                // T - type descriptor
                ConfigObject descriptor = configObject.GetObject(new int[] { t + typeOffset });

                // T.Q - property type qualifiers
                string[] qualifiers = new string[descriptor.Values.Count];
                for (int q = 0; q < descriptor.Values.Count; q++)
                {
                    qualifiers[q] = configObject.GetString(new int[] { t + typeOffset, q });
                }
                if (qualifiers[0] == MetadataTokens.B)
                {
                    typeInfo.CanBeBoolean = true;                                    // {"B"}
                }
                else if (qualifiers[0] == MetadataTokens.S)
                {
                    typeInfo.CanBeString = true; // {"S"} | {"S",10,0} | {"S",10,1}
                    if (qualifiers.Length == 1)
                    {
                        typeInfo.StringLength = -1;
                        typeInfo.StringKind   = StringKind.Unlimited;
                    }
                    else
                    {
                        typeInfo.StringLength = int.Parse(qualifiers[1]);
                        typeInfo.StringKind   = (StringKind)int.Parse(qualifiers[2]);
                    }
                }
                else if (qualifiers[0] == MetadataTokens.N)
                {
                    typeInfo.CanBeNumeric     = true; // {"N",10,2,0} | {"N",10,2,1}
                    typeInfo.NumericPrecision = int.Parse(qualifiers[1]);
                    typeInfo.NumericScale     = int.Parse(qualifiers[2]);
                    typeInfo.NumericKind      = (NumericKind)int.Parse(qualifiers[3]);
                }
                else if (qualifiers[0] == MetadataTokens.D)
                {
                    typeInfo.CanBeDateTime = true; // {"D"} | {"D","D"} | {"D","T"}
                    if (qualifiers.Length == 1)
                    {
                        typeInfo.DateTimePart = DateTimePart.DateTime;
                    }
                    else if (qualifiers[1] == MetadataTokens.D)
                    {
                        typeInfo.DateTimePart = DateTimePart.Date;
                    }
                    else
                    {
                        typeInfo.DateTimePart = DateTimePart.Time;
                    }
                }
                else if (qualifiers[0] == MetadataTokens.R) // {"#",70497451-981e-43b8-af46-fae8d65d16f2}
                {
                    Guid typeUuid = new Guid(qualifiers[1]);
                    if (typeUuid == new Guid("e199ca70-93cf-46ce-a54b-6edc88c3a296")) // ХранилищеЗначения - varbinary(max)
                    {
                        typeInfo.IsValueStorage = true;
                    }
                    else if (typeUuid == new Guid("fc01b5df-97fe-449b-83d4-218a090e681e")) // УникальныйИдентификатор - binary(16)
                    {
                        typeInfo.IsUuid = true;
                    }
                    else if (ReferenceBaseTypes.TryGetValue(typeUuid, out Dictionary <Guid, ApplicationObject> collection))
                    {
                        if (collection == null) // Любая ссылка
                        {
                            typeInfo.CanBeReference = true;
                            typeUuids.Add(Guid.Empty);
                        }
                        else if (collection.Count == 1) // Единственный объект метаданных в коллекции
                        {
                            typeInfo.CanBeReference = true;
                            typeUuids.Add(collection.Values.First().Uuid);
                        }
                        else // Множественный ссылочный тип данных
                        {
                            typeInfo.CanBeReference = true;
                            typeUuids.Add(Guid.Empty);
                        }
                    }
                    else if (Configurator.InfoBase.CompoundTypes.TryGetValue(typeUuid, out CompoundType compound))
                    {
                        // since 8.3.3
                        Configurator.InfoBase.ApplyCompoundType(typeInfo, compound);
                        typeUuids.Add(compound.TypeInfo.ReferenceTypeUuid);
                    }
                    else if (Configurator.InfoBase.CharacteristicTypes.TryGetValue(typeUuid, out Characteristic characteristic))
                    {
                        Configurator.InfoBase.ApplyCharacteristic(typeInfo, characteristic);
                        typeUuids.Add(characteristic.TypeInfo.ReferenceTypeUuid);
                    }
                    //else if (Configurator.InfoBase.MetaReferenceTypes.TryGetValue(typeUuid, out ApplicationObject metaObject))
                    //{
                    //    typeInfo.CanBeReference = true;
                    //    typeUuids.Add(typeUuid);
                    //}
                    else
                    {
                        // идентификатор ссылочного типа данных (см. закомментированную ветку выше)
                        // или
                        // идентификатор типа данных (определяемый или характеристика) ещё не загружен
                        // или
                        // неизвестный тип данных (работа с этим типом данных не реализована)
                        typeInfo.CanBeReference = true;
                        typeUuids.Add(typeUuid);
                    }
                }
            }
            if (typeUuids.Count == 1) // single type value
            {
                typeInfo.ReferenceTypeUuid = typeUuids[0];
            }

            return(typeInfo);
        }
Exemplo n.º 25
0
        public ActionResult Verification(int index)
        {
            TaskManager = (EasyUploadTaskManager)Session["TaskManager"];

            List <Dlm.Entities.DataStructure.Unit> tempUnitList = new List <Dlm.Entities.DataStructure.Unit>();
            List <DataType>      allDataypes       = new List <DataType>();
            List <DataAttribute> allDataAttributes = new List <DataAttribute>();

            using (IUnitOfWork unitOfWork = this.GetUnitOfWork())
            {
                //set current stepinfo based on index
                if (TaskManager != null)
                {
                    TaskManager.SetCurrent(index);

                    // remove if existing
                    TaskManager.RemoveExecutedStep(TaskManager.Current());
                }

                SelectVerificationModel model = new SelectVerificationModel();

                //Grab all necessary managers and lists
                //UnitManager unitManager = new UnitManager();
                //this.Disposables.Add(unitManager);

                //DataTypeManager dataTypeManager = new DataTypeManager();
                //this.Disposables.Add(dataTypeManager);

                tempUnitList      = unitOfWork.GetReadOnlyRepository <Dlm.Entities.DataStructure.Unit>().Get().ToList();
                allDataypes       = unitOfWork.GetReadOnlyRepository <DataType>().Get().ToList();
                allDataAttributes = unitOfWork.GetReadOnlyRepository <DataAttribute>().Get().ToList();



                //DataStructureManager dsm = new DataStructureManager();
                //this.Disposables.Add(dsm);

                //DataContainerManager dam = new DataContainerManager();
                //this.Disposables.Add(dam);


                //Important for jumping back to this step
                if (TaskManager.Bus.ContainsKey(EasyUploadTaskManager.VERIFICATION_MAPPEDHEADERUNITS))
                {
                    model.AssignedHeaderUnits = (List <Tuple <int, string, UnitInfo> >)TaskManager.Bus[EasyUploadTaskManager.VERIFICATION_MAPPEDHEADERUNITS];
                }

                // get all DataTypes for each Units
                foreach (Dlm.Entities.DataStructure.Unit unit in tempUnitList)
                {
                    UnitInfo unitInfo = new UnitInfo();

                    unitInfo.UnitId       = unit.Id;
                    unitInfo.Description  = unit.Description;
                    unitInfo.Name         = unit.Name;
                    unitInfo.Abbreviation = unit.Abbreviation;

                    if (unit.Name.ToLower() == "none")
                    {
                        foreach (DataType fullDataType in allDataypes)
                        {
                            DataTypeInfo dataTypeInfo = new DataTypeInfo();
                            dataTypeInfo.DataTypeId  = fullDataType.Id;
                            dataTypeInfo.Description = fullDataType.Description;
                            dataTypeInfo.Name        = fullDataType.Name;

                            unitInfo.DataTypeInfos.Add(dataTypeInfo);
                        }
                        model.AvailableUnits.Add(unitInfo);
                    }
                    else
                    {
                        Boolean hasDatatype = false; //Make sure only units that have at least one datatype are shown

                        foreach (DataType dummyDataType in unit.AssociatedDataTypes)
                        {
                            if (!hasDatatype)
                            {
                                hasDatatype = true;
                            }

                            DataTypeInfo dataTypeInfo = new DataTypeInfo();

                            DataType fullDataType = allDataypes.Where(p => p.Id == dummyDataType.Id).FirstOrDefault();
                            dataTypeInfo.DataTypeId  = fullDataType.Id;
                            dataTypeInfo.Description = fullDataType.Description;
                            dataTypeInfo.Name        = fullDataType.Name;

                            unitInfo.DataTypeInfos.Add(dataTypeInfo);
                        }
                        if (hasDatatype)
                        {
                            model.AvailableUnits.Add(unitInfo);
                        }
                    }
                }

                //Sort the units by name
                model.AvailableUnits.Sort(delegate(UnitInfo u1, UnitInfo u2)
                {
                    return(String.Compare(u1.Name, u2.Name, StringComparison.InvariantCultureIgnoreCase));
                });

                if (!TaskManager.Bus.ContainsKey(EasyUploadTaskManager.VERIFICATION_AVAILABLEUNITS))
                {
                    TaskManager.AddToBus(EasyUploadTaskManager.VERIFICATION_AVAILABLEUNITS, model.AvailableUnits);
                }

                string filePath = TaskManager.Bus[EasyUploadTaskManager.FILEPATH].ToString();
                string selectedHeaderAreaJson = TaskManager.Bus[EasyUploadTaskManager.SHEET_HEADER_AREA].ToString();

                FileStream fis = null;
                fis = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                ExcelPackage ep = new ExcelPackage(fis);
                fis.Close();

                ExcelWorkbook  excelWorkbook  = ep.Workbook;
                ExcelWorksheet firstWorksheet = excelWorkbook.Worksheets[1];

                string sheetFormatString = Convert.ToString(TaskManager.Bus[EasyUploadTaskManager.SHEET_FORMAT]);

                SheetFormat sheetFormat = 0;
                Enum.TryParse <SheetFormat>(sheetFormatString, true, out sheetFormat);

                model.HeaderFields = GetExcelHeaderFields(firstWorksheet, sheetFormat, selectedHeaderAreaJson).ToArray();

                if (!TaskManager.Bus.ContainsKey(EasyUploadTaskManager.VERIFICATION_HEADERFIELDS))
                {
                    TaskManager.AddToBus(EasyUploadTaskManager.VERIFICATION_HEADERFIELDS, model.HeaderFields);
                }


                model.Suggestions = new Dictionary <int, List <EasyUploadSuggestion> >();

                for (int i = 0; i < model.HeaderFields.Length; i++)
                {
                    //Default unit should be "none" if it exists, otherwise just take the first unit
                    UnitInfo currentUnitInfo = model.AvailableUnits.FirstOrDefault(u => u.Name.ToLower() == "none");
                    if (currentUnitInfo != null)
                    {
                        currentUnitInfo = (UnitInfo)currentUnitInfo.Clone();
                    }
                    else
                    {
                        currentUnitInfo = (UnitInfo)model.AvailableUnits.FirstOrDefault().Clone();
                    }

                    DataTypeInfo dtinfo = currentUnitInfo.DataTypeInfos.FirstOrDefault();
                    currentUnitInfo.SelectedDataTypeId = dtinfo.DataTypeId;
                    ViewData["defaultUnitID"]          = currentUnitInfo.UnitId;
                    ViewData["defaultDatatypeID"]      = dtinfo.DataTypeId;

                    if (model.AssignedHeaderUnits.Where(t => t.Item1 == i).FirstOrDefault() == null)
                    {
                        model.AssignedHeaderUnits.Add(new Tuple <int, string, UnitInfo>(i, model.HeaderFields[i], currentUnitInfo));
                    }

                    #region suggestions
                    //Add a variable to the suggestions if the names are similar
                    model.Suggestions.Add(i, new List <EasyUploadSuggestion>());

                    //Calculate similarity metric
                    //Accept suggestion if the similarity is greater than some threshold
                    double threshold = 0.5;
                    IEnumerable <DataAttribute> suggestions = allDataAttributes.Where(att => similarity(att.Name, model.HeaderFields[i]) >= threshold);

                    //Order the suggestions according to the similarity
                    List <DataAttribute> ordered = suggestions.ToList <DataAttribute>();
                    ordered.Sort((x, y) => (similarity(y.Name, model.HeaderFields[i])).CompareTo(similarity(x.Name, model.HeaderFields[i])));

                    //Add the ordered suggestions to the model
                    foreach (DataAttribute att in ordered)
                    {
                        model.Suggestions[i].Add(new EasyUploadSuggestion(att.Name, att.Unit.Id, att.DataType.Id, att.Unit.Name, att.DataType.Name, true));
                    }

                    //Use the following to order suggestions alphabetically instead of ordering according to the metric
                    //model.Suggestions[i] = model.Suggestions[i].Distinct().OrderBy(s => s.attributeName).ToList<EasyUploadSuggestion>();

                    //Each Name-Unit-Datatype-Tuple should be unique
                    model.Suggestions[i] = model.Suggestions[i].Distinct().ToList <EasyUploadSuggestion>();
                    #endregion
                }


                TaskManager.AddToBus(EasyUploadTaskManager.VERIFICATION_ATTRIBUTESUGGESTIONS, model.Suggestions);

                TaskManager.AddToBus(EasyUploadTaskManager.VERIFICATION_MAPPEDHEADERUNITS, model.AssignedHeaderUnits);

                // when jumping back to this step
                if (TaskManager.Bus.ContainsKey(EasyUploadTaskManager.SHEET_JSON_DATA))
                {
                    if (!String.IsNullOrEmpty(Convert.ToString(TaskManager.Bus[EasyUploadTaskManager.SHEET_JSON_DATA])))
                    {
                    }
                }

                model.StepInfo = TaskManager.Current();

                return(PartialView(model));
            }
        }
Exemplo n.º 26
0
        public async Task <DataTable> GetPagedDataTableAsync(DbConnection connection, Table table, List <TableColumn> columns, string orderColumns, long total, int pageSize, long pageNumber, string whereClause = "")
        {
            string quotedTableName = this.GetQuotedObjectName(table);

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

            foreach (TableColumn column in columns)
            {
                string columnName = this.GetQuotedString(column.Name);

                #region Convert MySql float to decimal, avoid scientific notation
                if (this.DatabaseType == DatabaseType.MySql && column.DataType.ToLower().Contains("float"))
                {
                    DataTypeInfo dataTypeInfo = DataTypeHelper.GetDataTypeInfo(column.DataType);

                    if (!string.IsNullOrEmpty(dataTypeInfo.Args))
                    {
                        string strPrecision = dataTypeInfo.Args.Split(',')[0].Trim();
                        int    precision;

                        DataTypeSpecification dataTypeSpec = this.GetDataTypeSpecification("decimal");

                        if (dataTypeSpec != null)
                        {
                            ArgumentRange?precisionRange = DataTypeManager.GetArgumentRange(dataTypeSpec, "precision");

                            if (precisionRange.HasValue)
                            {
                                if (int.TryParse(strPrecision, out precision) && precision > 0 && precision <= precisionRange.Value.Max)
                                {
                                    columnName = $"CONVERT({columnName},DECIMAL({dataTypeInfo.Args})) AS {columnName}";
                                }
                            }
                        }
                    }
                }
                #endregion

                #region Convert Oracle number to char
                else if (this.DatabaseType == DatabaseType.Oracle && column.DataType.ToLower().Contains("number"))
                {
                    columnName = $"TO_CHAR({columnName}) AS {columnName}";
                }
                #endregion

                columnNames.Add(columnName);
            }

            string strColumnNames = string.Join(",", columnNames);

            string pagedSql = this.GetSqlForPagination(quotedTableName, strColumnNames, orderColumns, whereClause, pageNumber, pageSize);

            DataTable dt = await this.GetDataTableAsync(connection, pagedSql);

            if (dt.Columns.OfType <DataColumn>().Any(item => item.ColumnName == RowNumberColumnName))
            {
                dt.Columns.Remove(RowNumberColumnName);
            }

            return(dt);
        }
Exemplo n.º 27
0
        public ActionResult SaveDataTypeSelection()
        {
            int?selectFieldId      = null;
            int?selectedDataTypeId = null;

            //Keys submitted by Javascript in Verification.cshtml
            foreach (string key in Request.Form.AllKeys)
            {
                if ("headerfieldId" == key)
                {
                    selectFieldId = Convert.ToInt32(Request.Form[key]);
                }
                if ("selectedDataTypeId" == key)
                {
                    selectedDataTypeId = Convert.ToInt32(Request.Form[key]);
                }
            }

            SelectVerificationModel model = new SelectVerificationModel();

            EasyUploadTaskManager TaskManager = (EasyUploadTaskManager)Session["TaskManager"];

            if (TaskManager.Bus.ContainsKey(EasyUploadTaskManager.VERIFICATION_MAPPEDHEADERUNITS))
            {
                model.AssignedHeaderUnits = (List <Tuple <int, string, UnitInfo> >)TaskManager.Bus[EasyUploadTaskManager.VERIFICATION_MAPPEDHEADERUNITS];
            }

            //Reset the name of the variable and save the new Datatype
            string[] headerFields  = (string[])TaskManager.Bus[EasyUploadTaskManager.VERIFICATION_HEADERFIELDS];
            string   currentHeader = headerFields.ElementAt((int)selectFieldId);
            Tuple <int, string, UnitInfo> existingTuple = model.AssignedHeaderUnits.Where(t => t.Item1 == selectFieldId).FirstOrDefault();

            existingTuple = new Tuple <int, string, UnitInfo>(existingTuple.Item1, existingTuple.Item2, (UnitInfo)existingTuple.Item3.Clone());

            int j = model.AssignedHeaderUnits.FindIndex(i => ((i.Item1 == existingTuple.Item1)));

            model.AssignedHeaderUnits[j] = new Tuple <int, string, UnitInfo>(existingTuple.Item1, currentHeader, existingTuple.Item3);
            model.AssignedHeaderUnits[j].Item3.SelectedDataTypeId = Convert.ToInt32(selectedDataTypeId);

            TaskManager.AddToBus(EasyUploadTaskManager.VERIFICATION_MAPPEDHEADERUNITS, model.AssignedHeaderUnits);

            if (TaskManager.Bus.ContainsKey(EasyUploadTaskManager.VERIFICATION_HEADERFIELDS))
            {
                model.HeaderFields = (string[])TaskManager.Bus[EasyUploadTaskManager.VERIFICATION_HEADERFIELDS];
            }

            if (TaskManager.Bus.ContainsKey(EasyUploadTaskManager.VERIFICATION_AVAILABLEUNITS))
            {
                model.AvailableUnits = (List <UnitInfo>)TaskManager.Bus[EasyUploadTaskManager.VERIFICATION_AVAILABLEUNITS];
            }

            //Grab the suggestions from the bus and filter them to only show those, that use the selected datatype
            model.Suggestions = (Dictionary <int, List <EasyUploadSuggestion> >)TaskManager.Bus[EasyUploadTaskManager.VERIFICATION_ATTRIBUTESUGGESTIONS];
            //Filter the suggestions to only show those, that use the selected unit
            int index = selectFieldId ?? -1;
            List <EasyUploadSuggestion> suggestionList = null;

            if (model.Suggestions.TryGetValue(index, out suggestionList))
            {
                if (suggestionList != null)
                {
                    foreach (EasyUploadSuggestion suggestion in suggestionList)
                    {
                        suggestion.show = (suggestion.dataTypeID == selectedDataTypeId);
                    }
                }
            }

            Session["TaskManager"] = TaskManager;

            model.StepInfo = TaskManager.Current();

            //Default unit should be "none" if it exists, otherwise just take the first unit
            UnitInfo currentUnitInfo = model.AvailableUnits.FirstOrDefault(u => u.Name.ToLower() == "none");

            if (currentUnitInfo != null)
            {
                currentUnitInfo = (UnitInfo)currentUnitInfo.Clone();
            }
            else
            {
                currentUnitInfo = (UnitInfo)model.AvailableUnits.FirstOrDefault().Clone();
            }

            DataTypeInfo dtinfo = currentUnitInfo.DataTypeInfos.FirstOrDefault();

            currentUnitInfo.SelectedDataTypeId = dtinfo.DataTypeId;
            ViewData["defaultUnitID"]          = currentUnitInfo.UnitId;
            ViewData["defaultDatatypeID"]      = dtinfo.DataTypeId;

            return(PartialView("Verification", model));
        }
Exemplo n.º 28
0
        public ColumnData[] GetColumnMetaData()
        {
            int columnCount = GetResultColumns();

            if (columnCount == 0)
            {
                return(null);
            }

            ColumnData[] columns = new ColumnData[columnCount];

            MemoryHandle name = new MemoryHandle((CLI.SQL_MAX_COLUMN_NAME_LEN + 1) * Platform.WideCharSize);

            try
            {
                for (int i = 0; i < columnCount; i++)
                {
                    CLI.ReturnCode rc;
                    short          length, dataType, decimalDigits, nullable;
                    uint           columnSize;
                    IntPtr         iVal;

                    ColumnData column = new ColumnData();
                    columns[i] = column;

                    rc = (CLI.ReturnCode)CLI.SQLDescribeCol(
                        hstmt, (ushort)(i + 1),
                        name.Handle, (short)name.Length, out length,
                        out dataType, out columnSize, out decimalDigits, out nullable);
                    if (rc != CLI.ReturnCode.SQL_SUCCESS)
                    {
                        Diagnostics.HandleResult(rc, this, outerCommand.Connection);
                    }
                    length = (short)(length * Platform.WideCharSize);

                    column.columnName = Platform.WideCharsToString(name.Handle, length);
                    //System.Console.WriteLine ("name.Length: {0}, length: {1}, columnName: {2}", name.Length, length, column.columnName);
                    Debug.WriteLineIf(SqlXml.Switch.TraceVerbose,
                                      String.Format("SQLColAttribute col={0} data_type={1}",
                                                    column.columnName, dataType));
                    column.columnType = DataTypeInfo.MapSqlType((CLI.SqlType)dataType);
                    if (((CLI.SqlType)dataType) == CLI.SqlType.SQL_WLONGVARCHAR)
                    {
                        MemoryHandle bcolt = new MemoryHandle(
                            (CLI.SQL_MAX_COLUMN_NAME_LEN + 1) * Platform.WideCharSize);
                        short  blength;
                        IntPtr biVal;

                        Debug.WriteLineIf(SqlXml.Switch.TraceVerbose,
                                          String.Format("Calling SQLColAttribute for col {0}",
                                                        column.columnName));
                        rc = (CLI.ReturnCode)CLI.SQLColAttribute(
                            hstmt, (ushort)(i + 1),
                            (ushort)CLI.DescriptorField.SQL_DESC_LOCAL_TYPE_NAME,
                            bcolt.Handle, (short)bcolt.Length, out blength, out biVal);
                        Debug.WriteLineIf(SqlXml.Switch.TraceInfo,
                                          String.Format(
                                              "Calling SQLColAttribute for col {0} returned rc={1}",
                                              column.columnName, rc));
                        if (rc == CLI.ReturnCode.SQL_SUCCESS)
                        {
                            String baseColumnType = Platform.WideCharsToString(
                                bcolt.Handle, blength);
                            Debug.WriteLineIf(SqlXml.Switch.TraceInfo,
                                              String.Format(
                                                  "Calling SQLColAttribute for col {0} returned type={1}",
                                                  column.columnName, baseColumnType));
                            if (baseColumnType == "XMLType")
                            {
                                column.columnType = DataTypeInfo.Xml;
                            }
                        }
                    }

                    if (column.columnType == null)
                    {
                        throw new SystemException("Unknown data type");
                    }
                    column.bufferType = column.columnType.bufferType;
                    column.columnSize = column.columnType.GetFieldSize((int)columnSize);
                    column.precision  = (short)column.columnSize;
                    column.scale      = decimalDigits;

                    column.IsLong     = column.columnType.isLong;
                    column.IsNullable = nullable == 0 ? false : true;

                    rc = (CLI.ReturnCode)CLI.SQLColAttribute(
                        hstmt, (ushort)(i + 1),
                        (ushort)CLI.ColumnAttribute.SQL_COLUMN_UPDATABLE,
                        IntPtr.Zero, (short)0, out length, out iVal);
                    if (rc != CLI.ReturnCode.SQL_SUCCESS)
                    {
                        Diagnostics.HandleResult(rc, this, outerCommand.Connection);
                    }
                    CLI.Updatable updatable = (CLI.Updatable)(int) iVal;
                    column.IsReadOnly = (updatable == CLI.Updatable.SQL_ATTR_READONLY);

                    rc = (CLI.ReturnCode)CLI.SQLColAttribute(
                        hstmt, (ushort)(i + 1),
                        (ushort)CLI.ColumnAttribute.SQL_COLUMN_KEY,
                        IntPtr.Zero, (short)0, out length, out iVal);
                    if (rc != CLI.ReturnCode.SQL_SUCCESS)
                    {
                        Diagnostics.HandleResult(rc, this, outerCommand.Connection);
                    }
                    column.IsKey = (((int)iVal) != 0);

                    rc = (CLI.ReturnCode)CLI.SQLColAttribute(
                        hstmt, (ushort)(i + 1),
                        (ushort)CLI.ColumnAttribute.SQL_COLUMN_HIDDEN,
                        IntPtr.Zero, (short)0, out length, out iVal);
                    if (rc != CLI.ReturnCode.SQL_SUCCESS)
                    {
                        Diagnostics.HandleResult(rc, this, outerCommand.Connection);
                    }
                    column.IsHidden = (((int)iVal) != 0);

                    rc = (CLI.ReturnCode)CLI.SQLColAttribute(
                        hstmt, (ushort)(i + 1),
                        (ushort)CLI.ColumnAttribute.SQL_COLUMN_AUTO_INCREMENT,
                        IntPtr.Zero, (short)0, out length, out iVal);
                    if (rc != CLI.ReturnCode.SQL_SUCCESS)
                    {
                        Diagnostics.HandleResult(rc, this, outerCommand.Connection);
                    }
                    column.IsAutoIncrement = (((int)iVal) != 0);

                    rc = (CLI.ReturnCode)CLI.SQLColAttribute(
                        hstmt, (ushort)(i + 1),
                        (ushort)CLI.DescriptorField.SQL_DESC_ROWVER,
                        IntPtr.Zero, (short)0, out length, out iVal);
                    if (rc != CLI.ReturnCode.SQL_SUCCESS)
                    {
                        Diagnostics.HandleResult(rc, this, outerCommand.Connection);
                    }
                    column.IsRowVersion = (((int)iVal) != 0);

                    // TODO: check for unique columns as well.
                    column.IsUnique = false;

                    rc = (CLI.ReturnCode)CLI.SQLColAttribute(
                        hstmt, (ushort)(i + 1),
                        (ushort)CLI.DescriptorField.SQL_DESC_BASE_COLUMN_NAME,
                        name.Handle, (short)name.Length, out length, out iVal);
                    if (rc != CLI.ReturnCode.SQL_SUCCESS)
                    {
                        Diagnostics.HandleResult(rc, this, outerCommand.Connection);
                    }
                    column.baseColumnName = Platform.WideCharsToString(name.Handle, length);
                    //System.Console.WriteLine ("name.Length: {0}, length: {1}, baseColumnName: {2}", name.Length, length, column.baseColumnName);

                    rc = (CLI.ReturnCode)CLI.SQLColAttribute(
                        hstmt, (ushort)(i + 1),
                        (ushort)CLI.DescriptorField.SQL_DESC_BASE_TABLE_NAME,
                        name.Handle, (short)name.Length, out length, out iVal);
                    if (rc != CLI.ReturnCode.SQL_SUCCESS)
                    {
                        Diagnostics.HandleResult(rc, this, outerCommand.Connection);
                    }
                    column.baseTableName = Platform.WideCharsToString(name.Handle, length);

                    rc = (CLI.ReturnCode)CLI.SQLColAttribute(
                        hstmt, (ushort)(i + 1),
                        (ushort)CLI.DescriptorField.SQL_DESC_SCHEMA_NAME,
                        name.Handle, (short)name.Length, out length, out iVal);
                    if (rc != CLI.ReturnCode.SQL_SUCCESS)
                    {
                        Diagnostics.HandleResult(rc, this, outerCommand.Connection);
                    }
                    column.baseSchemaName = Platform.WideCharsToString(name.Handle, length);

                    rc = (CLI.ReturnCode)CLI.SQLColAttribute(
                        hstmt, (ushort)(i + 1),
                        (ushort)CLI.DescriptorField.SQL_DESC_CATALOG_NAME,
                        name.Handle, (short)name.Length, out length, out iVal);
                    if (rc != CLI.ReturnCode.SQL_SUCCESS)
                    {
                        Diagnostics.HandleResult(rc, this, outerCommand.Connection);
                    }
                    column.baseCatalogName = Platform.WideCharsToString(name.Handle, length);

                    if (column.baseTableName == null || column.baseTableName == "")
                    {
                        column.IsExpression = true;
                    }
                    else
                    {
                        column.IsExpression = false;
                    }
                }

                GC.KeepAlive(this);
            }
            finally
            {
                name.Dispose();
            }

            return(columns);
        }
Exemplo n.º 29
0
        public ActionResult SaveSuggestionSelection()
        {
            SelectVerificationModel model = new SelectVerificationModel();

            int?   selectFieldId        = null;
            int?   selectedUnitId       = null;
            int?   selectedDatatypeId   = null;
            string selectedVariableName = null;

            //Keys submitted by Javascript in Verification.cshtml
            foreach (string key in Request.Form.AllKeys)
            {
                if ("headerfieldId" == key)
                {
                    selectFieldId = Convert.ToInt32(Request.Form[key]);
                }
                if ("selectedVariableName" == key)
                {
                    selectedVariableName = Convert.ToString(Request.Form[key]);
                }
                if ("selectedUnitId" == key)
                {
                    selectedUnitId = Convert.ToInt32(Request.Form[key]);
                }
                if ("selectedDataTypeId" == key)
                {
                    var test = Request.Form[key];
                    selectedDatatypeId = Convert.ToInt32(Request.Form[key]);
                }
            }

            EasyUploadTaskManager TaskManager = (EasyUploadTaskManager)Session["TaskManager"];

            if (TaskManager.Bus.ContainsKey(EasyUploadTaskManager.VERIFICATION_MAPPEDHEADERUNITS))
            {
                model.AssignedHeaderUnits = (List <Tuple <int, string, UnitInfo> >)TaskManager.Bus[EasyUploadTaskManager.VERIFICATION_MAPPEDHEADERUNITS];
            }

            /*
             * Copy the assignedHeaderUnits, change the entry for which the suggestion was selected
             * */
            if (selectFieldId != null)
            {
                //Find the position of the Tuple that is about to be changed
                Tuple <int, string, UnitInfo> exTuple = model.AssignedHeaderUnits.Where(t => t.Item1 == selectFieldId).FirstOrDefault();
                int i = model.AssignedHeaderUnits.FindIndex(t => t.Equals(exTuple));
                //Insert a new Tuple at this position
                model.AssignedHeaderUnits[i] = new Tuple <int, string, UnitInfo>(exTuple.Item1, selectedVariableName, exTuple.Item3);
            }


            //Save unit and datatype
            if (selectFieldId != null && selectedUnitId != null)
            {
                //Get all units
                List <UnitInfo> availableUnits = (List <UnitInfo>)TaskManager.Bus[EasyUploadTaskManager.VERIFICATION_AVAILABLEUNITS];

                //Get the current unit and clone it
                UnitInfo currentUnit = (UnitInfo)availableUnits.Where(u => u.UnitId == selectedUnitId).FirstOrDefault().Clone();
                currentUnit.SelectedDataTypeId = Convert.ToInt32(selectedDatatypeId);

                //Find the index of the suggestion that is about to be changed
                Tuple <int, string, UnitInfo> existingTuple = model.AssignedHeaderUnits.Where(t => t.Item1 == (int)selectFieldId).FirstOrDefault();
                int j = model.AssignedHeaderUnits.FindIndex(t => t.Equals(existingTuple));
                //Save the new unit with the new datatype
                model.AssignedHeaderUnits[j] = new Tuple <int, string, UnitInfo>(existingTuple.Item1, selectedVariableName, currentUnit);
            }

            TaskManager.AddToBus(EasyUploadTaskManager.VERIFICATION_MAPPEDHEADERUNITS, model.AssignedHeaderUnits);

            if (TaskManager.Bus.ContainsKey(EasyUploadTaskManager.VERIFICATION_HEADERFIELDS))
            {
                model.HeaderFields = (string[])TaskManager.Bus[EasyUploadTaskManager.VERIFICATION_HEADERFIELDS];
            }

            if (TaskManager.Bus.ContainsKey(EasyUploadTaskManager.VERIFICATION_AVAILABLEUNITS))
            {
                model.AvailableUnits = (List <UnitInfo>)TaskManager.Bus[EasyUploadTaskManager.VERIFICATION_AVAILABLEUNITS];
            }

            model.Suggestions = (Dictionary <int, List <EasyUploadSuggestion> >)TaskManager.Bus[EasyUploadTaskManager.VERIFICATION_ATTRIBUTESUGGESTIONS];

            Session["TaskManager"] = TaskManager;

            //create Model
            model.StepInfo = TaskManager.Current();

            //Submit default datatype id
            //Default unit should be "none" if it exists, otherwise just take the first unit
            UnitInfo currentUnitInfo = model.AvailableUnits.FirstOrDefault(u => u.Name.ToLower() == "none");

            if (currentUnitInfo != null)
            {
                currentUnitInfo = (UnitInfo)currentUnitInfo.Clone();
            }
            else
            {
                currentUnitInfo = (UnitInfo)model.AvailableUnits.FirstOrDefault().Clone();
            }

            DataTypeInfo dtinfo = currentUnitInfo.DataTypeInfos.FirstOrDefault();

            currentUnitInfo.SelectedDataTypeId = dtinfo.DataTypeId;
            ViewData["defaultUnitID"]          = currentUnitInfo.UnitId;
            ViewData["defaultDatatypeID"]      = dtinfo.DataTypeId;

            return(PartialView("Verification", model));
        }
Exemplo n.º 30
0
        public ActionResult Verification(int index)
        {
            TaskManager = (EasyUploadTaskManager)Session["TaskManager"];

            List <Dlm.Entities.DataStructure.Unit> tempUnitList = new List <Dlm.Entities.DataStructure.Unit>();
            List <DataType>      allDataypes       = new List <DataType>();
            List <DataAttribute> allDataAttributes = new List <DataAttribute>();

            using (IUnitOfWork unitOfWork = this.GetUnitOfWork())
            {
                //set current stepinfo based on index
                if (TaskManager != null)
                {
                    TaskManager.SetCurrent(index);

                    // remove if existing
                    TaskManager.RemoveExecutedStep(TaskManager.Current());
                }

                SelectVerificationModel     model              = new SelectVerificationModel();
                List <DataTypeInfo>         dataTypeInfos      = new List <DataTypeInfo>();
                List <UnitInfo>             unitInfos          = new List <UnitInfo>();
                List <DataAttrInfo>         dataAttributeInfos = new List <DataAttrInfo>();
                List <EasyUploadSuggestion> suggestions        = new List <EasyUploadSuggestion>();
                List <string> headers = new List <string>();


                tempUnitList      = unitOfWork.GetReadOnlyRepository <Dlm.Entities.DataStructure.Unit>().Get().ToList();
                allDataypes       = unitOfWork.GetReadOnlyRepository <DataType>().Get().ToList();
                allDataAttributes = unitOfWork.GetReadOnlyRepository <DataAttribute>().Get().ToList();


                //Important for jumping back to this step
                if (TaskManager.Bus.ContainsKey(EasyUploadTaskManager.ROWS))
                {
                    model.Rows = (List <RowModel>)TaskManager.Bus[EasyUploadTaskManager.ROWS];
                }

                // get all DataTypes for each Units
                foreach (Dlm.Entities.DataStructure.Unit unit in tempUnitList)
                {
                    UnitInfo unitInfo = new UnitInfo();

                    unitInfo.UnitId       = unit.Id;
                    unitInfo.Description  = unit.Description;
                    unitInfo.Name         = unit.Name;
                    unitInfo.Abbreviation = unit.Abbreviation;
                    unitInfo.DimensionId  = unit.Dimension.Id;

                    if (unit.Name.ToLower() == "none")
                    {
                        foreach (DataType fullDataType in allDataypes)
                        {
                            DataTypeInfo dataTypeInfo = new DataTypeInfo();
                            dataTypeInfo.DataTypeId  = fullDataType.Id;
                            dataTypeInfo.Description = fullDataType.Description;
                            dataTypeInfo.Name        = fullDataType.Name;

                            unitInfo.DataTypeInfos.Add(dataTypeInfo);
                        }

                        unitInfos.Add(unitInfo);
                    }
                    else
                    {
                        Boolean hasDatatype = false; //Make sure only units that have at least one datatype are shown

                        foreach (DataType dummyDataType in unit.AssociatedDataTypes)
                        {
                            if (!hasDatatype)
                            {
                                hasDatatype = true;
                            }

                            DataTypeInfo dataTypeInfo = new DataTypeInfo();

                            DataType fullDataType = allDataypes.Where(p => p.Id == dummyDataType.Id).FirstOrDefault();
                            dataTypeInfo.DataTypeId  = fullDataType.Id;
                            dataTypeInfo.Description = fullDataType.Description;
                            dataTypeInfo.Name        = fullDataType.Name;

                            unitInfo.DataTypeInfos.Add(dataTypeInfo);
                        }
                        if (hasDatatype)
                        {
                            unitInfos.Add(unitInfo);
                        }
                    }
                }

                //Sort the units by name
                unitInfos.Sort(delegate(UnitInfo u1, UnitInfo u2)
                {
                    return(String.Compare(u1.Name, u2.Name, StringComparison.InvariantCultureIgnoreCase));
                });


                TaskManager.AddToBus(EasyUploadTaskManager.VERIFICATION_AVAILABLEUNITS, unitInfos);

                // all datatypesinfos
                dataTypeInfos = unitInfos.SelectMany(u => u.DataTypeInfos).GroupBy(d => d.DataTypeId).Select(g => g.Last()).ToList();
                TaskManager.AddToBus(EasyUploadTaskManager.ALL_DATATYPES, dataTypeInfos);


                //Setall Data AttrInfos to Session -> default
                allDataAttributes.ForEach(d => dataAttributeInfos.Add(new DataAttrInfo(d.Id, d.Unit.Id, d.DataType.Id, d.Description, d.Name, d.Unit.Dimension.Id)));
                Session["DataAttributes"] = dataAttributeInfos;



                string filePath = TaskManager.Bus[EasyUploadTaskManager.FILEPATH].ToString();
                string selectedHeaderAreaJson = TaskManager.Bus[EasyUploadTaskManager.SHEET_HEADER_AREA].ToString();

                FileStream fis = null;
                fis = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                using (ExcelPackage ep = new ExcelPackage(fis))
                {
                    fis.Close();

                    ExcelWorkbook  excelWorkbook  = ep.Workbook;
                    ExcelWorksheet firstWorksheet = excelWorkbook.Worksheets[1];

                    string sheetFormatString = Convert.ToString(TaskManager.Bus[EasyUploadTaskManager.SHEET_FORMAT]);

                    SheetFormat sheetFormat = 0;
                    Enum.TryParse <SheetFormat>(sheetFormatString, true, out sheetFormat);

                    headers = GetExcelHeaderFields(firstWorksheet, sheetFormat, selectedHeaderAreaJson);

                    headers = makeHeaderUnique(headers);

                    suggestions = new List <EasyUploadSuggestion>();

                    if (!model.Rows.Any())
                    {
                        foreach (string varName in headers)
                        {
                            #region suggestions

                            //Add a variable to the suggestions if the names are similar
                            suggestions = getSuggestions(varName, dataAttributeInfos);

                            #endregion

                            //set rowmodel
                            RowModel row = new RowModel(
                                headers.IndexOf(varName),
                                varName,
                                null,
                                null,
                                null,
                                suggestions,
                                unitInfos,
                                dataAttributeInfos,
                                dataTypeInfos
                                );

                            model.Rows.Add(row);

                            TaskManager.AddToBus(EasyUploadTaskManager.ROWS, model.Rows);
                            TaskManager.AddToBus(EasyUploadTaskManager.VERIFICATION_MAPPEDHEADERUNITS, RowsToTuples());
                        }
                    }

                    TaskManager.AddToBus(EasyUploadTaskManager.VERIFICATION_MAPPEDHEADERUNITS, headers);

                    model.StepInfo = TaskManager.Current();

                    return(PartialView(model));
                }
            }
        }
Exemplo n.º 31
0
        private static IEnumerable <DataTypeDescriptor> CollectDataTypes(
            ClientModel model,
            IMapperContext context)
        {
            var dataTypes = context.Types
                            .OfType <ObjectTypeDescriptor>()
                            .Where(x => x.IsDataType())
                            .ToList();

            var unionTypes = model.Schema.Types
                             .OfType <UnionType>()
                             .ToList();

            var dataTypeInfos = new Dictionary <NameString, DataTypeInfo>();

            foreach (ObjectTypeDescriptor dataType in dataTypes)
            {
                ObjectType objectType = model.Schema.GetType <ObjectType>(dataType.Name);

                var abstractTypes = new List <INamedType>();
                abstractTypes.AddRange(unionTypes.Where(t => t.ContainsType(dataType.Name)));
                abstractTypes.AddRange(objectType.Implements);

                if (!dataTypeInfos.TryGetValue(dataType.Name, out var dataTypeInfo))
                {
                    dataTypeInfo = new DataTypeInfo(dataType.Name, dataType.Description);
                    dataTypeInfo.AbstractTypeParentName.AddRange(
                        abstractTypes.Select(abstractType => abstractType.Name.Value));
                    dataTypeInfos.Add(dataType.Name, dataTypeInfo);
                }

                dataTypeInfo.Components.Add(dataType.RuntimeType.Name);
            }

            var handledAbstractTypes = new HashSet <string>();

            foreach (DataTypeInfo dataTypeInfo in dataTypeInfos.Values)
            {
                var implements = new List <string>();

                foreach (var abstractTypeName in dataTypeInfo.AbstractTypeParentName)
                {
                    var dataTypeInterfaceName = GetInterfaceName(abstractTypeName);
                    implements.Add(dataTypeInterfaceName);
                    if (handledAbstractTypes.Add(dataTypeInterfaceName))
                    {
                        yield return(new DataTypeDescriptor(
                                         dataTypeInterfaceName,
                                         NamingConventions.CreateStateNamespace(context.Namespace),
                                         Array.Empty <ComplexTypeDescriptor>(),
                                         Array.Empty <string>(),
                                         dataTypeInfo.Description,
                                         true));
                    }
                }

                yield return(new DataTypeDescriptor(
                                 dataTypeInfo.Name,
                                 NamingConventions.CreateStateNamespace(context.Namespace),
                                 dataTypeInfo.Components
                                 .Select(name => context.Types.Single(t => t.RuntimeType.Name.Equals(name)))
                                 .OfType <ComplexTypeDescriptor>()
                                 .ToList(),
                                 implements,
                                 dataTypeInfo.Description));
            }
        }
Exemplo n.º 32
0
        protected virtual string GetDbType(string columnType, DataTypeInfo dataType, int length, int prec, int scale)
        {
            var dbType = columnType;

            if (dataType != null)
            {
                var format = dataType.CreateFormat;
                var parms  = dataType.CreateParameters;

                if (!string.IsNullOrWhiteSpace(format) && !string.IsNullOrWhiteSpace(parms))
                {
                    var paramNames  = parms.Split(',');
                    var paramValues = new object[paramNames.Length];

                    for (var i = 0; i < paramNames.Length; i++)
                    {
                        switch (paramNames[i].Trim().ToLower())
                        {
                            case "size"       :
                            case "length"     :
                            case "max length" : paramValues[i] = length; break;
                            case "precision"  : paramValues[i] = prec;   break;
                            case "scale"      : paramValues[i] = scale;  break;
                        }
                    }

                    if (paramValues.All(v => v != null && (int)v != 0))
                        dbType = format.Args(paramValues);
                }
            }

            return dbType;
        }
Exemplo n.º 33
0
 public static string MakeEqualsConformity(DataTypeInfo dataTypeInfo)
 {
     return(new EqualsConformity(dataTypeInfo).TransformText());
 }
Exemplo n.º 34
0
        protected override string GetDbType(string columnType, DataTypeInfo dataType, long length, int prec, int scale)
        {
            var type = DataTypes.FirstOrDefault(dt => dt.TypeName == columnType);

            if (type != null)
            {
                if (type.CreateParameters == null)
                    length = prec = scale = 0;
                else
                {
                    if (type.CreateParameters == "LENGTH")
                        prec = scale = 0;
                    else
                        length = 0;

                    if (type.CreateFormat == null)
                    {
                        if (type.TypeName.IndexOf("()") >= 0)
                        {
                            type.CreateFormat = type.TypeName.Replace("()", "({0})");
                        }
                        else
                        {
                            var format = string.Join(",",
                                type.CreateParameters
                                    .Split(',')
                                    .Select((p,i) => "{" + i + "}")
                                    .ToArray());

                            type.CreateFormat = type.TypeName + "(" + format + ")";
                        }
                    }
                }
            }

            return base.GetDbType(columnType, dataType, length, prec, scale);
        }
        protected override string GetDbType(GetSchemaOptions options, string columnType, DataTypeInfo dataType, long?length, int?prec, int?scale, string udtCatalog, string udtSchema, string udtName)
        {
            var dt = GetDataType(columnType, options);

            if (dt != null)
            {
                if (dt.CreateParameters == null)
                {
                    scale  = 0;
                    prec   = scale;
                    length = prec;
                }
                else
                {
                    if (dt.CreateParameters == "LENGTH")
                    {
                        scale = 0;
                        prec  = scale;
                    }
                    else
                    {
                        length = 0;
                    }
                    if (dt.CreateFormat == null)
                    {
                        if (dt.TypeName.IndexOf("()", StringComparison.Ordinal) >= 0)
                        {
                            dt.CreateFormat = dt.TypeName.Replace("()", "({0})");
                        }
                        else
                        {
                            var format = string.Join(",", dt.CreateParameters.Split(',').Select((p, i) => "{" + i + "}").ToArray());
                            dt.CreateFormat = dt.TypeName + "(" + format + ")";
                        }
                    }
                }
            }
            return(base.GetDbType(options, columnType, dataType, length, prec, scale, udtCatalog, udtSchema, udtName));
        }
Exemplo n.º 36
0
        protected override Type GetSystemType(string columnType, DataTypeInfo dataType, int length, int precision, int scale)
        {
            if (dataType == null)
            {
                switch (columnType.ToLower())
                {
                    //case "text" : return typeof(string);
                    default     : throw new InvalidOperationException();
                }
            }

            return base.GetSystemType(columnType, dataType, length, precision, scale);
        }
 public EqualityThroughMembers(DataTypeInfo classInfo, IEnumerable <string> statedMembers)
 {
     this.DataTypeInfo  = classInfo ?? throw new ArgumentNullException(nameof(classInfo));
     this.StatedMembers = statedMembers ?? throw new ArgumentNullException(nameof(statedMembers));
 }
Exemplo n.º 38
0
        protected override string GetDbType(string columnType, DataTypeInfo dataType, long? length, int? prec, int? scale)
        {
            switch (columnType)
            {
                case "NUMBER" :
                    if (prec == 0) return columnType;
                    break;
            }

            return base.GetDbType(columnType, dataType, length, prec, scale);
        }
Exemplo n.º 39
0
        //第二步:定义执行线程主体事件
        //线程主体方法
        public void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            List <object> args = e.Argument as List <object>;

            #region 根据项目属性获取数据类型
            XmlHelper   xmlprojectthelper = new XmlHelper(@"XML\project.xml");
            XmlNodeList xmlprejectNodeLst = xmlprojectthelper.Read("datatype");

            if (xmlprejectNodeLst.Count == 0)
            {
                return;
            }

            XmlNode xn1project = xmlprejectNodeLst[0];

            // 将节点转换为元素,便于得到节点的属性值
            XmlElement xeproject = (XmlElement)xn1project;

            // 得到DataTypeInfo节点的所有子节点
            XmlNodeList xnl0project = xeproject.ChildNodes;

            string dbType   = xnl0project.Item(4).InnerText;
            string filePath = xnl0project.Item(9).InnerText;
            #endregion

            switch (args[0].ToString())
            {
            case "GenerTableSql":
                string[] filenames = args[1] as string[];
                Dictionary <string, string> constrainttypelst = new Dictionary <string, string>();
                constrainttypelst.Add("0", "主键");
                constrainttypelst.Add("1", "索引");
                constrainttypelst.Add("2", "唯一索引");

                //在线程中更新UI(通过ReportProgress方法)
                //...执行线程任务

                #region 先读取datatype.xml 在读取defaulttype.xml 然后Linq 查询保存到数据字典dic中
                XmlHelper           xmldatatypehelper  = new XmlHelper(@"XML\datatype.xml");
                XmlNodeList         xmldatatypeNodeLst = xmldatatypehelper.Read("datatype");
                List <DataTypeInfo> dataTypeInfoList   = new List <DataTypeInfo>();
                foreach (XmlNode xn1 in xmldatatypeNodeLst)
                {
                    DataTypeInfo dataTypeInfo = new DataTypeInfo();
                    // 将节点转换为元素,便于得到节点的属性值
                    XmlElement xe = (XmlElement)xn1;
                    // 得到Type和ISBN两个属性的属性值
                    dataTypeInfo.Gid = xe.GetAttribute("gid").ToString();

                    // 得到DataTypeInfo节点的所有子节点
                    XmlNodeList xnl0 = xe.ChildNodes;
                    dataTypeInfo.Name      = xnl0.Item(0).InnerText;
                    dataTypeInfo.StdType   = xnl0.Item(2).InnerText;
                    dataTypeInfo.Length    = xnl0.Item(3).InnerText;
                    dataTypeInfo.Precision = xnl0.Item(4).InnerText;

                    dataTypeInfoList.Add(dataTypeInfo);
                }

                XmlHelper   defaulttypexmlHelper  = new XmlHelper(@"XML\defaulttype.xml");
                XmlNodeList defaulttypexmlNodeLst = defaulttypexmlHelper.Read("datatype");
                Dictionary <string, string> dict  = new Dictionary <string, string>();
                foreach (var dataTypeInfo in dataTypeInfoList)
                {
                    foreach (XmlNode xn1 in defaulttypexmlNodeLst)
                    {
                        // 将节点转换为元素,便于得到节点的属性值
                        XmlElement xe = (XmlElement)xn1;
                        // 得到DataTypeInfo节点的所有子节点
                        XmlNodeList xnl0  = xe.ChildNodes;
                        string      value = string.Empty;
                        if (dbType == "Oracle")
                        {
                            value = xnl0.Item(2).InnerText;
                        }
                        else if (dbType == "Mysql")
                        {
                            value = xnl0.Item(3).InnerText;
                        }
                        else if (dbType == "DB2")
                        {
                            value = xnl0.Item(4).InnerText;
                        }
                        else if (dbType == "SqlServer")
                        {
                            value = xnl0.Item(5).InnerText;
                        }
                        else if (dbType == "Sqlite")
                        {
                            value = xnl0.Item(6).InnerText;
                        }
                        else if (dbType == "Access")
                        {
                            value = xnl0.Item(7).InnerText;
                        }

                        // 找到匹配记录
                        if (dataTypeInfo.StdType == xnl0.Item(0).InnerText)
                        {
                            if (value.Contains("$L"))
                            {
                                if (String.Empty == dataTypeInfo.Length)
                                {
                                    value = value.Replace("$L", "0");
                                }
                                else
                                {
                                    value = value.Replace("$L", dataTypeInfo.Length);
                                }
                            }
                            if (value.Contains("$P"))
                            {
                                if (String.Empty == dataTypeInfo.Precision)
                                {
                                    value = value.Replace("$P", "0");
                                }
                                else
                                {
                                    value = value.Replace("$P", dataTypeInfo.Precision);
                                }
                            }
                            dict.Add(dataTypeInfo.Name, value);
                        }
                    }
                }

                XmlHelper   stdfieldxmlHelper  = new XmlHelper(@"XML\stdfield.xml");
                XmlNodeList stdfieldxmlNodeLst = stdfieldxmlHelper.Read("datatype/dataitem");

                List <StdFieldComboBox> stdFieldInfoList = new List <StdFieldComboBox>();
                foreach (XmlNode xn1 in stdfieldxmlNodeLst)
                {
                    // 将节点转换为元素,便于得到节点的属性值
                    XmlElement xe = (XmlElement)xn1;
                    // 得到DataTypeInfo节点的所有子节点
                    XmlNodeList      xnl0     = xe.ChildNodes;
                    StdFieldComboBox listItem = new StdFieldComboBox();
                    listItem.Name        = xnl0.Item(0).InnerText;
                    listItem.ChineseName = xnl0.Item(1).InnerText;
                    listItem.DataType    = xnl0.Item(2).InnerText;
                    listItem.DictNo      = xnl0.Item(3).InnerText.ToInt32();
                    if (dictTypeInfoList != null)
                    {
                        var dictType = dictTypeInfoList.Find(new Predicate <DictInfo>(dictinfo => dictinfo.Id == xnl0.Item(3).InnerText.ToInt32()));
                        if (dictType != null)
                        {
                            listItem.DictNameLst = dictType.Remark;
                        }
                    }

                    stdFieldInfoList.Add(listItem);
                }
                #endregion

                if (FileUtil.IsExistFile(filePath + "\\TableInit.sql"))
                {
                    FileUtil.DeleteFile(filePath + "\\TableInit.sql");
                }

                FileUtil.CreateFile(filePath + "\\TableInit.sql");

                #region 处理每个Table脚本
                for (Int32 ii = 0; ii < filenames.Length; ii++)
                {
                    // 20190925 没有做好的不生成
                    if (filenames[ii].Contains("_TODO"))
                    {
                        Console.WriteLine(string.Format("{0} [{1})]无需处理.\r\n", LogLevel.LOG_LEVEL_INFO, filenames[ii]));
                        backgroundWorker1.ReportProgress((Int32)(progressBar.Position + 1) / progressBar.Properties.Maximum, string.Format("{0} [{1})]无需处理.\r\n", LogLevel.LOG_LEVEL_INFO, filenames[ii]));
                        continue;
                    }

                    XmlHelper xmltablesinfohelper = new XmlHelper(filenames[ii]);

                    XmlNodeList xmlbasicsLst = xmltablesinfohelper.Read(string.Format("datatype/basicinfo"));
                    XmlNodeList xmlbasicsOne = ((XmlElement)xmlbasicsLst[0]).ChildNodes;
                    string      functionStr  = xmlbasicsOne.Item(0).InnerText;
                    string      englishName  = xmlbasicsOne.Item(1).InnerText;
                    string      chineseName  = xmlbasicsOne.Item(2).InnerText;
                    Boolean     checkHis     = Convert.ToInt32(xmlbasicsOne.Item(3).InnerText) == 0 ? false : true;

                    XmlNodeList            xmlfieldsLst  = xmltablesinfohelper.Read(string.Format("datatype/fieldsinfo"));
                    List <TableFieldsInfo> FieldsInfoLst = new List <TableFieldsInfo>();
                    foreach (XmlNode xn1 in xmlfieldsLst)
                    {
                        TableFieldsInfo tablefieldInfo = new TableFieldsInfo();

                        // 将节点转换为元素,便于得到节点的属性值
                        XmlElement xe = (XmlElement)xn1;

                        tablefieldInfo.Gid = xe.GetAttribute("gid").ToString();

                        // 得到DataTypeInfo节点的所有子节点
                        XmlNodeList xnl0 = xe.ChildNodes;

                        for (Int32 i = 0; i < stdFieldInfoList.Count; i++)
                        {
                            if (string.Equals(stdFieldInfoList[i].Name, xnl0.Item(0).InnerText))
                            {
                                tablefieldInfo.FieldName   = stdFieldInfoList[i].Name;
                                tablefieldInfo.ChineseName = stdFieldInfoList[i].ChineseName;
                                tablefieldInfo.DataType    = stdFieldInfoList[i].DataType;
                                tablefieldInfo.FieldInfo   = stdFieldInfoList[i].DictNameLst;
                                break;
                            }
                        }

                        tablefieldInfo.IsNull  = (short)(xnl0.Item(1).InnerText == "0" ? 0 : 1);
                        tablefieldInfo.Remark  = xnl0.Item(2).InnerText;
                        tablefieldInfo.lstInfo = new Dictionary <string, DevExpress.XtraEditors.DXErrorProvider.ErrorInfo>();
                        FieldsInfoLst.Add(tablefieldInfo);
                    }

                    // 如果没有字段则写日志继续
                    if (FieldsInfoLst.Count == 0)
                    {
                        backgroundWorker1.ReportProgress((Int32)(progressBar.Position + 1) / progressBar.Properties.Maximum, string.Format("{0} 表[{1}({2})]不存在字段,请检查,处理完成.\r\n", LogLevel.LOG_LEVEL_ERR, chineseName, englishName));
                        continue;
                    }

                    XmlNodeList xmlindexLst = xmltablesinfohelper.Read(string.Format("datatype/indexsinfo"));

                    List <TableIndexsInfo> IndexsInfoLst = new List <TableIndexsInfo>();

                    foreach (XmlNode xn1 in xmlindexLst)
                    {
                        TableIndexsInfo tableindexsInfo = new TableIndexsInfo();

                        // 将节点转换为元素,便于得到节点的属性值
                        XmlElement xe = (XmlElement)xn1;
                        tableindexsInfo.Gid = xe.GetAttribute("gid").ToString();

                        // 得到DataTypeInfo节点的所有子节点
                        XmlNodeList xnl0 = xe.ChildNodes;
                        tableindexsInfo.IndexName      = xnl0.Item(0).InnerText;
                        tableindexsInfo.IndexFieldLst  = xnl0.Item(1).InnerText;
                        tableindexsInfo.ConstraintType = string.IsNullOrEmpty(xnl0.Item(2).InnerText) ? (short)-1 : Convert.ToInt16(xnl0.Item(2).InnerText);
                        tableindexsInfo.lstInfo        = new Dictionary <string, DevExpress.XtraEditors.DXErrorProvider.ErrorInfo>();
                        IndexsInfoLst.Add(tableindexsInfo);
                    }

                    FileUtil.AppendText(filePath + "\\TableInit.sql", JCodes.Framework.Common.Proj.SqlOperate.initTableInfo(dbType, tableGroup[englishName] + englishName, string.Format("{0}({1})", chineseName, functionStr), checkHis, FieldsInfoLst, IndexsInfoLst, dict), Encoding.UTF8);

                    Console.WriteLine(string.Format("{0} [{1}({2})]处理完成.\r\n", LogLevel.LOG_LEVEL_INFO, chineseName, englishName));
                    backgroundWorker1.ReportProgress((Int32)(progressBar.Position + 1) / progressBar.Properties.Maximum, string.Format("{0} [{1}({2})]处理完成.\r\n", LogLevel.LOG_LEVEL_INFO, chineseName, englishName));
                }
                #endregion
                break;

            case "TableDataSql":
                string[] filenames2 = args[1] as string[];

                //在线程中更新UI(通过ReportProgress方法)
                if (FileUtil.IsExistFile(filePath + "\\TableDataSql.sql"))
                {
                    FileUtil.DeleteFile(filePath + "\\TableDataSql.sql");
                }

                FileUtil.CreateFile(filePath + "\\TableDataSql.sql");

                #region 处理每个Table脚本
                for (Int32 ii = 0; ii < filenames2.Length; ii++)
                {
                    DataTable dt = new DataTable();
                    // 先读取表结构信息
                    XmlHelper xmltablefieldhelper = new XmlHelper(filenames2[ii].Replace("basicdata", "table"));

                    XmlNodeList xmlfieldsbasicLst = xmltablefieldhelper.Read(string.Format("datatype/basicinfo"));

                    XmlNodeList xnl0basic   = ((XmlElement)xmlfieldsbasicLst[0]).ChildNodes;
                    string      englishName = xnl0basic.Item(1).InnerText;
                    string      chineseName = xnl0basic.Item(2).InnerText;

                    XmlNodeList xmlfieldsLst = xmltablefieldhelper.Read(string.Format("datatype/fieldsinfo"));

                    foreach (XmlNode xn1 in xmlfieldsLst)
                    {
                        // 将节点转换为元素,便于得到节点的属性值
                        XmlElement xe = (XmlElement)xn1;
                        // 得到DataTypeInfo节点的所有子节点
                        XmlNodeList xnl0 = xe.ChildNodes;

                        dt.Columns.Add(xnl0.Item(0).InnerText);
                    }

                    // 读取数据信息
                    XmlHelper   xmltabledatahelper = new XmlHelper(filenames2[ii]);
                    XmlNodeList xmlNodeLst         = xmltabledatahelper.Read("datatype/dataitem");

                    foreach (XmlNode xn1 in xmlNodeLst)
                    {
                        DataRow dr = dt.NewRow();
                        // 将节点转换为元素,便于得到节点的属性值
                        XmlElement xe = (XmlElement)xn1;

                        for (int i = 0; i < dt.Columns.Count; i++)
                        {
                            if (xe.Attributes[dt.Columns[i].ColumnName.ToLower()] != null)
                            {
                                dr[dt.Columns[i].ColumnName] = xe.GetAttribute(dt.Columns[i].ColumnName.ToLower()).ToString();
                            }
                            else
                            {
                                xe.SetAttribute(dt.Columns[i].ColumnName.ToLower(), string.Empty);
                            }
                        }
                        xmltabledatahelper.Save(false);
                        dt.Rows.Add(dr);

                        // 根据属性去反查是否存在不存在则删除
                        List <String> tmp = new List <string>();
                        foreach (XmlAttribute a in xe.Attributes)
                        {
                            if (dt.Columns[a.Name] == null && !string.Equals(a.Name, "gid"))
                            {
                                tmp.Add(a.Name);
                            }
                        }
                        foreach (var s in tmp)
                        {
                            xe.RemoveAttribute(s);
                        }
                        xmltabledatahelper.Save(false);
                    }

                    FileUtil.AppendText(filePath + "\\TableDataSql.sql", JCodes.Framework.Common.Proj.SqlOperate.initTableDataInfo(dbType, tableGroup[englishName] + englishName, chineseName, dt), Encoding.Default);

                    backgroundWorker1.ReportProgress((Int32)(progressBar.Position + 1) / progressBar.Properties.Maximum, string.Format("{0} [{1}({2})]处理完成.\r\n", LogLevel.LOG_LEVEL_INFO, chineseName, englishName));
                }
                #endregion
                break;

            case "DictionarySql":
                //在线程中更新UI(通过ReportProgress方法)
                if (FileUtil.IsExistFile(filePath + "\\Dict.sql"))
                {
                    FileUtil.DeleteFile(filePath + "\\Dict.sql");
                }

                FileUtil.CreateFile(filePath + "\\Dict.sql");

                #region 处理每个Table脚本
                XmlHelper           xmldicthelper      = new XmlHelper(@"XML\dict.xml");
                XmlNodeList         xmlNodeLst2        = xmldicthelper.Read("datatype/dataitem");
                List <DictInfo>     dictTypeInfoList2  = new List <DictInfo>();
                List <DictDataInfo> dictDetailInfoList = new List <DictDataInfo>();
                foreach (XmlNode xn1 in xmlNodeLst2)
                {
                    DictInfo dictInfo = new DictInfo();
                    // 将节点转换为元素,便于得到节点的属性值
                    XmlElement xe = (XmlElement)xn1;

                    // 得到DataTypeInfo节点的所有子节点
                    XmlNodeList xnl0 = xe.ChildNodes;
                    dictInfo.Id     = Convert.ToInt32(xnl0.Item(0).InnerText);
                    dictInfo.Pid    = Convert.ToInt32(xnl0.Item(1).InnerText);
                    dictInfo.Name   = xnl0.Item(2).InnerText;
                    dictInfo.Remark = xnl0.Item(3).InnerText;

                    if (!string.IsNullOrEmpty(xnl0.Item(4).InnerXml))
                    {
                        System.Xml.XmlDocument doc = new System.Xml.XmlDocument();  //新建对象
                        doc.LoadXml("<tmp>" + xnl0.Item(4).InnerXml + "</tmp>");    //符合xml格式的字符串
                        var nodes = doc.DocumentElement.ChildNodes;
                        foreach (var node in nodes)
                        {
                            DictDataInfo dicdetailInfo = new DictDataInfo();
                            var          dNode         = ((XmlElement)node).ChildNodes;
                            dicdetailInfo.DicttypeValue = dNode.Item(0).InnerText.ToInt32();
                            dicdetailInfo.Name          = dNode.Item(1).InnerText;
                            dicdetailInfo.Seq           = dNode.Item(2).InnerText;
                            dicdetailInfo.Remark        = dNode.Item(3).InnerText;
                            dicdetailInfo.DicttypeId    = dictInfo.Id;

                            dictDetailInfoList.Add(dicdetailInfo);
                        }
                    }

                    dictTypeInfoList2.Add(dictInfo);
                }

                // T_Basic_DictType
                // T_Basic_DictData
                FileUtil.AppendText(filePath + "\\Dict.sql", JCodes.Framework.Common.Proj.SqlOperate.initDictTypeInfo(dbType, tableGroup["DictType"] + "DictType", "数据字典类型", dictTypeInfoList2), Encoding.Default);

                backgroundWorker1.ReportProgress((Int32)(progressBar.Position + 1) / progressBar.Properties.Maximum, string.Format("{0} [{1}({2})]处理完成.\r\n", LogLevel.LOG_LEVEL_INFO, "数据字典类型", "DictType"));

                FileUtil.AppendText(filePath + "\\Dict.sql", JCodes.Framework.Common.Proj.SqlOperate.initDictDataInfo(dbType, tableGroup["DictData"] + "DictData", "数据字典明细", dictDetailInfoList), Encoding.Default);

                backgroundWorker1.ReportProgress((Int32)(progressBar.Position + 1) / progressBar.Properties.Maximum, string.Format("{0} [{1}({2})]处理完成.\r\n", LogLevel.LOG_LEVEL_INFO, "数据字典明细", "DictData"));

                #endregion

                break;

            case "MenuSql":
                //在线程中更新UI(通过ReportProgress方法)
                if (FileUtil.IsExistFile(filePath + "\\Menu.sql"))
                {
                    FileUtil.DeleteFile(filePath + "\\Menu.sql");
                }

                FileUtil.CreateFile(filePath + "\\Menu.sql");

                #region 处理每个Table脚本
                XmlHelper       xmlmenuhelper = new XmlHelper(@"XML\menu.xml");
                XmlNodeList     xmlNodeLst3   = xmlmenuhelper.Read("datatype/dataitem");
                List <MenuInfo> menuInfolst   = new List <MenuInfo>();
                foreach (XmlNode xn1 in xmlNodeLst3)
                {
                    MenuInfo menuinfo = new MenuInfo();
                    // 将节点转换为元素,便于得到节点的属性值
                    XmlElement xe = (XmlElement)xn1;

                    // 得到DataTypeInfo节点的所有子节点
                    XmlNodeList xnl0 = xe.ChildNodes;
                    menuinfo.Gid            = xnl0.Item(0).InnerText;
                    menuinfo.Pgid           = xnl0.Item(1).InnerText;
                    menuinfo.Name           = xnl0.Item(2).InnerText;
                    menuinfo.Icon           = xnl0.Item(3).InnerText;
                    menuinfo.Seq            = xnl0.Item(4).InnerText;
                    menuinfo.AuthGid        = xnl0.Item(5).InnerText;
                    menuinfo.IsVisable      = Convert.ToInt16(xnl0.Item(6).InnerText);
                    menuinfo.WinformClass   = xnl0.Item(7).InnerText;
                    menuinfo.Url            = xnl0.Item(8).InnerText;
                    menuinfo.WebIcon        = xnl0.Item(9).InnerText;
                    menuinfo.SystemtypeId   = xnl0.Item(10).InnerText;
                    menuinfo.CreatorId      = Convert.ToInt32(xnl0.Item(11).InnerText);
                    menuinfo.CreatorTime    = Convert.ToDateTime(xnl0.Item(12).InnerText);
                    menuinfo.EditorId       = Convert.ToInt32(xnl0.Item(13).InnerText);
                    menuinfo.LastUpdateTime = Convert.ToDateTime(xnl0.Item(14).InnerText);
                    menuinfo.IsDelete       = Convert.ToInt16(xnl0.Item(15).InnerText);
                    menuInfolst.Add(menuinfo);
                }

                FileUtil.AppendText(filePath + "\\Menu.sql", JCodes.Framework.Common.Proj.SqlOperate.initMenuInfo(dbType, tableGroup["Menu"] + "Menu", "系统菜单", menuInfolst), Encoding.Default);

                backgroundWorker1.ReportProgress((Int32)(progressBar.Position + 1) / progressBar.Properties.Maximum, string.Format("{0} [{1}({2})]处理完成.\r\n", LogLevel.LOG_LEVEL_INFO, "系统菜单", "Menu"));
                #endregion
                break;

            case "FunctionSql":
                //在线程中更新UI(通过ReportProgress方法)
                if (FileUtil.IsExistFile(filePath + "\\Function.sql"))
                {
                    FileUtil.DeleteFile(filePath + "\\Function.sql");
                }

                FileUtil.CreateFile(filePath + "\\Function.sql");

                #region 处理每个Table脚本
                XmlHelper   xmlfunctionhelper = new XmlHelper(@"XML\function.xml");
                XmlNodeList xmlNodeLst4       = xmlfunctionhelper.Read("datatype/dataitem");
                List <JCodes.Framework.Entity.FunctionInfo> functionInfolst = new List <JCodes.Framework.Entity.FunctionInfo>();
                foreach (XmlNode xn1 in xmlNodeLst4)
                {
                    JCodes.Framework.Entity.FunctionInfo functioninfo = new JCodes.Framework.Entity.FunctionInfo();
                    // 将节点转换为元素,便于得到节点的属性值
                    XmlElement xe = (XmlElement)xn1;

                    // 得到DataTypeInfo节点的所有子节点
                    XmlNodeList xnl0 = xe.ChildNodes;
                    functioninfo.Gid          = xnl0.Item(0).InnerText;
                    functioninfo.Pgid         = xnl0.Item(1).InnerText;
                    functioninfo.Name         = xnl0.Item(2).InnerText;
                    functioninfo.DllPath      = xnl0.Item(3).InnerText;
                    functioninfo.SystemtypeId = xnl0.Item(4).InnerText;
                    functioninfo.Seq          = xnl0.Item(5).InnerText;
                    functionInfolst.Add(functioninfo);
                }

                FileUtil.AppendText(filePath + "\\Function.sql", JCodes.Framework.Common.Proj.SqlOperate.initFunctionInfo(dbType, tableGroup["Function"] + "Function", "系统功能", functionInfolst), Encoding.Default);

                #endregion
                break;
            }
            //...执行线程其他任务

            backgroundWorker1.ReportProgress(100, string.Format("{0} 已全部生成完毕.\r\n", LogLevel.LOG_LEVEL_INFO));
        }
Exemplo n.º 40
0
        protected override Type GetSystemType(string dataType, string columnType, DataTypeInfo dataTypeInfo, long? length, int? precision, int? scale)
        {
            switch (dataType)
            {
                case "tinyint"     : return typeof(byte);
                case "hierarchyid" :
                case "geography"   :
                case "geometry"    : return SqlServerDataProvider.GetUdtType(dataType);
            }

            return base.GetSystemType(dataType, columnType, dataTypeInfo, length, precision, scale);
        }
Exemplo n.º 41
0
        public static void DeriveParameters(VirtuosoCommand command)
        {
            if (command == null)
            {
                throw new ArgumentNullException("command");
            }

            if (command.CommandType != CommandType.StoredProcedure)
            {
                throw new InvalidOperationException("DeriveParameters supports only stored procedures.");
            }

            VirtuosoConnection connection = (VirtuosoConnection)command.Connection;

            if (connection == null)
            {
                throw new InvalidOperationException("The Connection property is not set.");
            }
            if (connection.State == ConnectionState.Closed)
            {
                throw new InvalidOperationException("The connection is closed.");
            }

            IInnerCommand      innerCommand = null;
            VirtuosoDataReader reader       = null;

            try
            {
                innerCommand = connection.innerConnection.CreateInnerCommand(null);
                innerCommand.GetProcedureColumns(command.CommandText);
                reader = new VirtuosoDataReader(connection, innerCommand, null, CommandBehavior.Default, false);

                command.Parameters.Clear();
                while (reader.Read())
                {
                    CLI.InOutType iotype = (CLI.InOutType)reader.GetInt16(reader.GetOrdinal("COLUMN_TYPE"));

                    ParameterDirection direction;
                    switch (iotype)
                    {
                    case CLI.InOutType.SQL_PARAM_INPUT:
                        direction = ParameterDirection.Input;
                        break;

                    case CLI.InOutType.SQL_PARAM_OUTPUT:
                        direction = ParameterDirection.Output;
                        break;

                    case CLI.InOutType.SQL_PARAM_INPUT_OUTPUT:
                        direction = ParameterDirection.InputOutput;
                        break;

                    case CLI.InOutType.SQL_PARAM_RETURN_VALUE:
                        direction = ParameterDirection.ReturnValue;
                        break;

                    default:
#if MONO
                        direction = ParameterDirection.Input;
#endif
                        continue;
                    }

                    string name = reader.GetString(reader.GetOrdinal("COLUMN_NAME"));
                    if (name == "" && iotype == CLI.InOutType.SQL_PARAM_RETURN_VALUE)
                    {
                        name = "ReturnValue";
                    }

                    CLI.SqlType sqlType = (CLI.SqlType)reader.GetInt16(reader.GetOrdinal("DATA_TYPE"));
                    DataType    type    = DataTypeInfo.MapSqlType(sqlType);
                    if (type == null)
                    {
                        throw new SystemException("Unknown data type");
                    }

                    int sizeOrdinal = reader.GetOrdinal("COLUMN_SIZE");
                    if (sizeOrdinal < 0)
                    {
                        sizeOrdinal = reader.GetOrdinal("PRECISION");
                    }
                    int size = reader.IsDBNull(sizeOrdinal) ? 0 : reader.GetInt32(sizeOrdinal);

                    int scaleOrdinal = reader.GetOrdinal("DECIMAL_DIGITS");
                    if (scaleOrdinal < 0)
                    {
                        scaleOrdinal = reader.GetOrdinal("SCALE");
                    }
                    short scale = reader.IsDBNull(scaleOrdinal) ? (short)0 : reader.GetInt16(scaleOrdinal);

                    int          nullableOrdinal = reader.GetOrdinal("NULLABLE");
                    CLI.Nullable nullable        = (CLI.Nullable)reader.GetInt16(nullableOrdinal);
                    bool         isNullable      = (nullable != CLI.Nullable.SQL_NO_NULLS);

                    VirtuosoParameter parameter = (VirtuosoParameter)command.CreateParameter();
                    parameter.ParameterName = name;
                    parameter.Direction     = direction;
                    parameter.VirtDbType    = type.vdbType;
                    parameter.Size          = type.GetFieldSize(size);
                    parameter.Precision     = type.GetPrecision(size);
                    parameter.Scale         = (byte)scale;
                    parameter.IsNullable    = isNullable;
                    command.Parameters.Add(parameter);
                }
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
                if (innerCommand != null)
                {
                    innerCommand.Dispose();
                }
            }
        }