public ExtractorProgress(bool isSlave = false)
 {
     _currentTable = new TableDef();
     _currentTask = new TableDef();
     _overallTimer = new StopWatch(false, false);
     _tableTimer = new StopWatch(false, false);
     _taskTimer = new StopWatch(false, false);
     _abort = false;
     IsSlave = isSlave;
     IsMigrating = false;
     Reset();
 }
示例#2
0
 /// <summary>
 /// 修改数据库表
 /// </summary>
 /// <param name="tableDef"></param>
 /// <returns></returns>
 public abstract bool modifyTable(TableDef tableDef);
示例#3
0
 /// <summary>
 /// 创建数据库表
 /// </summary>
 /// <param name="tableDef"></param>
 /// <returns></returns>
 public abstract bool createTable(TableDef tableDef);
示例#4
0
文件: Sql.cs 项目: nQuantums/tips
        public InsertInto <TColumns, TColumnsOrder> InsertInto <TColumns, TColumnsOrder>(TableDef <TColumns> table, ISelect <TColumnsOrder> select) where TColumnsOrder : TColumns
        {
            var node = new InsertInto <TColumns, TColumnsOrder>(this, table, select);

            this.AddChild(node);
            return(node);
        }
        /// <summary>
        /// 创建数据库表
        /// </summary>
        /// <param name="tableDef"></param>
        /// <returns>成功返回true</returns>
        public override bool createTable(TableDef tableDef)
        {
            bool   bRet      = false;
            string tmpStr    = "";
            string attachStr = "";//约束信息

            //字段说明
            string    noteStr = "";
            DbCommand cmd;

            try
            {
                if (tableDef != null)
                {
                    if (isExistObject(tableDef.Name, "Tb"))
                    {
                        bRet = modifyTable(tableDef);
                    }
                    else
                    {
                        StringBuilder strSql        = new StringBuilder();
                        StringBuilder strConstrains = new StringBuilder();//约束
                        strSql.Append("CREATE  TABLE " + tableDef.Name);
                        strSql.Append("(  ");
                        foreach (FieldDef field in tableDef.FieldDefs)
                        {
                            tmpStr    = "";
                            attachStr = "";
                            noteStr   = "";
                            if (field.Name != "")
                            {
                                //字段说明
                                if (!string.IsNullOrEmpty(field.Alias))
                                {
                                    noteStr = " comment  '" + field.Alias + "' ";
                                }

                                if (!string.IsNullOrEmpty(field.Constrains))
                                {
                                    strConstrains.Append(field.Constrains + ";");
                                }

                                if (!string.IsNullOrEmpty(field.DefaultValue))
                                {
                                    attachStr += "  default  " + field.DefaultValue;
                                }
                                if (!field.NotNull)
                                {
                                    attachStr += "  not null ";
                                }

                                if (field.IsIdentity)
                                {
                                    attachStr += "  auto_increment ";
                                    //field.IsGuid = true;
                                }

                                if (field.IsUnique)
                                {
                                    attachStr += "  unique ";
                                }

                                //if (field.IsIdentity)
                                //{
                                //    attachStr += "  auto_increment ";
                                //}

                                if (field.Type.ToLower() == "decimal" || field.Type.ToLower() == "float")
                                {
                                    tmpStr = field.Name + " " + field.Type.ToLower() + "(" + field.Length + "," + field.Procesion + ")";
                                }
                                else if (field.Length > 0 && field.Type.ToLower() != "int" && field.Type.ToLower() != "blob" && field.Type.ToLower() != "enum" && field.Type.ToLower() != "datetime" && field.Type.ToLower() != "date" && field.Type.ToLower() != "time" && field.Type.ToLower() != "text")
                                {
                                    tmpStr = field.Name + " " + field.Type.ToLower() + "(" + field.Length + ")";
                                }
                                else
                                {
                                    tmpStr = field.Name + " " + field.Type.ToLower();
                                }
                                tmpStr += noteStr.ToString();
                                tmpStr += attachStr + ",";
                                strSql.Append(tmpStr);
                            }
                        }

                        if (tableDef.FieldDefs.Count > 0)
                        {
                            strSql.Remove(strSql.Length - 1, 1);
                            strSql.Append(")");
                        }


                        if (!string.IsNullOrEmpty(strSql.ToString()))
                        {
                            //创建表
                            cmd = database.GetSqlStringCommand(strSql.ToString());
                            database.ExecuteNonQuery(cmd);
                        }


                        //表主键
                        string strKeyName = "";
                        string strKeySql  = "";
                        foreach (FieldDef field in tableDef.MainKeys)
                        {
                            if (field.Name != "")
                            {
                                strKeyName += field.Name + ",";
                            }
                        }
                        strKeyName = strKeyName.TrimEnd(',');
                        if (strKeyName != "")
                        {
                            strKeySql = "ALTER TABLE " + tableDef.Name + "  WITH NOCHECK ADD CONSTRAINT PK_" + tableDef.Name + " PRIMARY KEY  NONCLUSTERED ( " + strKeyName + ")";
                            cmd       = database.GetSqlStringCommand(strKeySql);
                            database.ExecuteNonQuery(cmd);
                        }

                        if (!string.IsNullOrEmpty(strConstrains.ToString()))
                        {
                            cmd = database.GetSqlStringCommand(strConstrains.ToString());
                            database.ExecuteNonQuery(cmd);
                        }
                        bRet = true;
                    }
                }
                else
                {
                    bRet = false;
                }
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
            return(bRet);
        }
        protected override string GetSqlCreateTable(TableDef td)
        {
            StringBuilder strBuild = new StringBuilder();

            strBuild = strBuild.Append("CREATE TABLE ")
                       .Append(td.TableName).Append("(");
            foreach (FieldDef fd in td.KeyFields.Values)
            {
                strBuild.Append(fd.FieldName)
                .Append(SqlServerType(fd))
                .Append(" NOT NULL,");
            }
            foreach (FieldDef fd in td.NonKeyFields.Values)
            {
                if (fd.GetDTLSA() == null)
                {
                    if (fd.DataType == DataType.Image ||
                        fd.DataType == DataType.Binary)
                    {
                        strBuild.Append(fd.FieldName)
                        .Append(SqlServerType(fd))
                        .Append(",");
                    }
                    else
                    {
                        strBuild.Append(fd.FieldName)
                        .Append(SqlServerType(fd))
                        .Append(" NOT NULL,");
                    }
                }
            }
            if (td.KeyFields.Count > 0)
            {
                strBuild.Append("CONSTRAINT PK_").Append(td.TableName)
                .Append(" PRIMARY KEY CLUSTERED (");
                foreach (FieldDef fd in td.KeyFields.Values)
                {
                    strBuild.Append(fd.FieldName).Append(",");
                }

                strBuild.Remove(strBuild.Length - 1, 1).Append("))");
            }
            else
            {
                strBuild.Remove(strBuild.Length - 1, 1).Append(")");
            }

            int Ctr = 0;

            foreach (string index in td.IndexedFields)
            {
                int i = index.IndexOf('|');
                if (i == 6)
                {
                    strBuild.Append("\0CREATE UNIQUE NONCLUSTERED INDEX IX_");
                }
                else
                {
                    strBuild.Append("\0CREATE NONCLUSTERED INDEX IX_");
                }
                strBuild.Append(td.TableName).Append("_")
                .Append(Ctr.ToString()).Append(" ON ")
                .Append(td.TableName).Append("(").Append(
                    index.Substring(i + 1)).Append(")");
                Ctr++;
            }
            return(strBuild.ToString());
        }
        public TEntity ShowForm <TEntity>(IList <TEntity> ListSrc,
                                          string Caption, EntityColumnShow ecs)
            where TEntity : BaseEntity
        {
            if (ListSrc == null || ListSrc.Count == 0)
            {
                XtraMessageBox.Show("Data Tidak Ditemukan !",
                                    "Error Membaca Data " + typeof(TEntity).Name,
                                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                return(null);
            }

            td = MetaData.GetTableDef(typeof(TEntity));
            if (ecs == null)
            {
                ecs = new EntityColumnShow(string.Join(
                                               ",", td.GetListFieldNames(true).ToArray()));
            }

            this.ecs = ecs;
            gridControl1.BeginUpdate();
            try
            {
                gridControl1.DataSource =
                    new ReportGrid(td.ClassType, (IList)ListSrc, ecs);

                string[] cols;
                if (ecs.ColumnShow.Length > 0)
                {
                    cols = ecs.ColumnShow.Split(',');
                }
                else
                {
                    cols = td.GetListFieldNames(true).ToArray();
                }

                foreach (GridColumn gc in gridView1.Columns)
                {
                    gc.VisibleIndex = -1;
                }

                int i = 0;
                foreach (string col in cols)
                {
                    gridView1.Columns[col.Trim()].VisibleIndex = i++;
                }

                gridView1.FocusedColumn = gridView1.Columns[cols[0]];

                if (ecs.ListChild.Count > 0)
                {
                    gridControl1.ViewRegistered += new ViewOperationEventHandler(gridControl1_ViewRegistered);
                    int j = 0;
                    if (ecs.ListChild.Count == 1)
                    {
                        gridView1.OptionsDetail.ShowDetailTabs = false;
                    }

                    foreach (ChildColumnShow cs in ecs.ListChild)
                    {
                        GridView gv = new GridView(gridControl1);
                        gv.OptionsDetail.EnableMasterViewMode  = false;
                        gv.OptionsView.ColumnAutoWidth         = false;
                        gv.OptionsView.EnableAppearanceEvenRow = true;
                        gv.OptionsView.EnableAppearanceOddRow  = true;
                        gv.OptionsView.ShowGroupPanel          = false;
                        gv.BestFitMaxRowCount       = 15;
                        gv.OptionsBehavior.Editable = false;
                        gv.OptionsBehavior.AllowIncrementalSearch = true;

                        gridControl1.LevelTree.Nodes.Add(cs.ChildName, gv);
                        if (cs.ColumnShow.Length == 0 ||
                            cs.ColumnShow == "*")
                        {
                            cols = td.ChildEntities[j].GetTableDef()
                                   .GetListFieldNames(true).ToArray();
                        }
                        else
                        {
                            cols = cs.ColumnShow.Split(',');
                        }
                        i = 0;
                        foreach (string colName in cols)
                        {
                            GridColumn gc = gv.Columns.AddField(
                                colName.Trim());
                            gc.VisibleIndex = i++;
                            //gc.OptionsColumn.ReadOnly = true;
                        }

                        BaseWinFramework.WinForm.AutoFormat
                        .AutoFormatReadOnlyGridView(
                            td.ChildEntities[j++].GetChildType(), gv, true);
                    }
                }
                BaseWinFramework.WinForm.AutoFormat
                .AutoFormatReadOnlyGridView(td.ClassType,
                                            gridView1, true);
            }
            catch
            {
                XtraMessageBox.Show("Nama Kolom tidak ditemukan dalam Entity",
                                    "Error mengatur penampakan kolom",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally { gridControl1.EndUpdate(); }

            if (Caption.Length == 0)
            {
                Caption = "Pilih " + BaseUtility.SplitName(td.ClassType.Name);
            }
            Text = Caption;

            Index = -1;
            ShowDialog();
            return(Index < 0 ? null : ListSrc[Index]);
        }
示例#8
0
        private void SaveSelectedProperty()
        {
            var i = 0;
            if (selectedTable == null)
            {
                ++i;
                selectedTable = new TableDef<TreeNode>
                    {
                        DefaultAnalysisQuery = new List<string>(),
                        Data = new TreeNode { Text = txtTableName.Text.Trim() }
                    };
                selectedTable.Data.Tag = selectedTable;
            }
            else
            {
                if (!StringHelper.NullEmptyEquals(selectedTable.TableName, txtTableName.Text.Trim()))
                {
                    ++i;
                    selectedProperty.Table.Remove(selectedTable.TableName);
                    selectedTable.Data.Remove();
                }
            }

            selectedTable.Description = txtTableDesc.Text.Trim();
            selectedTable.TableName = txtTableName.Text.Trim();
            selectedProperty.Table[selectedTable.TableName] = selectedTable;
            if (i != 0)
                AdjustNodePlace();
            selectedTable.DefaultAnalysisQuery.Clear();
            for (i = 0; i < defaultAnalysisQuery.Count && defaultAnalysisQuery[i].Selected; i++)
            {
                selectedTable.DefaultAnalysisQuery.Add(defaultAnalysisQuery[i].Text);
            }
            ResetSelectionProperty();
            SaveRecorderProperties();
        }
示例#9
0
        private static void CheckChildRelation(RelationAttribute ra, TableDef tdParent, TableDef td)
        {
            if (!BaseUtility.IsDebugMode)
            {
                return;
            }
            if (ra._ParentFields.Length != ra._ChildFields.Length)
            {
                throw new ApplicationException(string.Format(
                                                   ErrorMetaData.RelationFieldCount,
                                                   ra._ParentType.Name, ra.ChildType.Name));
            }
            if (ra._ParentFields.Length != tdParent.KeyFields.Count)
            {
                throw new ApplicationException(string.Format(
                                                   ErrorMetaData.RelationParentField,
                                                   ra._ParentType.Name, ra.ChildType.Name));
            }
            for (int i = 0; i < ra._ParentFields.Length; i++)
            {
                FieldDef fldP;
                if (!tdParent.KeyFields.TryGetValue(
                        ra._ParentFields[i], out fldP))
                {
                    throw new ApplicationException(string.Format(
                                                       ErrorMetaData.RelParentFieldNotFound,
                                                       ra._ParentType.Name, ra.ChildType.Name,
                                                       ra._ParentFields[i]));
                }

                FieldDef fldC;
                if (!td.KeyFields.TryGetValue(ra._ChildFields[i],
                                              out fldC))
                {
                    if (!td.NonKeyFields.TryGetValue(ra._ChildFields[i],
                                                     out fldC))
                    {
                        throw new ApplicationException(string.Format(
                                                           ErrorMetaData.RelChildFieldNotFound,
                                                           ra._ParentType.Name, ra.ChildType.Name,
                                                           ra._ChildFields[i]));
                    }
                }
                if (fldP.DataType != fldC.DataType ||
                    fldP.Length < fldC.Length)
                {
                    throw new ApplicationException(string.Format(
                                                       ErrorMetaData.RelationFieldTypeNotMatch,
                                                       ra._ParentType.Name, ra.ChildType.Name,
                                                       ra._ParentFields[i], ra._ChildFields[i]));
                }
            }
        }
示例#10
0
        /// <summary>
        /// 修改数据库表
        /// </summary>
        /// <param name="tableDef"></param>
        /// <returns></returns>
        public override bool modifyTable(TableDef tableDef)
        {
            bool          bRet = false;
            TableDef      existTbDef;
            StringBuilder strConstrains = new StringBuilder(); //约束

            string attachStr = "";                             //约束信息
            //字段说明
            string noteStr;


            string tmpStr = "";


            DbCommand cmd;
            string    strSql = "";

            try
            {
                if (tableDef != null)
                {
                    if (isExistObject(tableDef.Name, "Table"))
                    {
                        existTbDef = getTableDef(tableDef.Name);
                        for (int i = 0; i < tableDef.FieldDefs.Count; i++)
                        {
                            if (tableDef.FieldDefs[i].Name != "")
                            {
                                for (int j = 0; j < existTbDef.FieldDefs.Count; j++)
                                {
                                    //字段说明
                                    if (!string.IsNullOrEmpty(tableDef.FieldDefs[i].Alias))
                                    {
                                        noteStr = "COMMENT ON COLUMN " + tableDef.Name + "." + tableDef.FieldDefs[i].Name + " IS '" + tableDef.FieldDefs[i].Alias + "'";
                                        cmd     = Database.GetSqlStringCommand(noteStr.ToUpper());
                                        Database.ExecuteNonQuery(cmd);
                                    }

                                    //修改列
                                    if (tableDef.FieldDefs[i].Name == existTbDef.FieldDefs[j].Name)
                                    {
                                        attachStr = "";
                                        if (tableDef.FieldDefs[i].Type.ToLower() == "number")
                                        {
                                            tmpStr = tableDef.FieldDefs[i].Name + " " + tableDef.FieldDefs[i].Type.ToLower() + "(" + tableDef.FieldDefs[i].Length + "," + tableDef.FieldDefs[i].Procesion + ")";
                                        }
                                        else if (tableDef.FieldDefs[i].Length > 0 && tableDef.FieldDefs[i].Type.ToLower() != "int" && tableDef.FieldDefs[i].Type.ToLower() != "blob" && tableDef.FieldDefs[i].Type.ToLower() != "clob" && tableDef.FieldDefs[i].Type.ToLower() != "nclob" && tableDef.FieldDefs[i].Type.ToLower() != "date" && tableDef.FieldDefs[i].Type.ToLower() != "timestamp")
                                        {
                                            tmpStr = tableDef.FieldDefs[i].Name + " " + tableDef.FieldDefs[i].Type.ToLower() + "(" + tableDef.FieldDefs[i].Length + ")";
                                        }
                                        else
                                        {
                                            tmpStr = tableDef.FieldDefs[i].Name + " " + tableDef.FieldDefs[i].Type.ToLower();
                                        }

                                        if (!string.IsNullOrEmpty(tableDef.FieldDefs[i].DefaultValue))
                                        {
                                            attachStr += "  default " + tableDef.FieldDefs[i].DefaultValue;
                                        }

                                        if (tableDef.FieldDefs[i].IsNull != existTbDef.FieldDefs[j].IsNull)
                                        {
                                            if (!tableDef.FieldDefs[i].IsNull)
                                            {
                                                attachStr += "  not null ";
                                            }
                                            else
                                            {
                                                attachStr += " null ";
                                            }
                                        }

                                        if (tableDef.FieldDefs[i].IsPriKey)
                                        {
                                            attachStr += "  not null ";
                                        }

                                        tmpStr += attachStr;
                                        try
                                        {
                                            strSql = "alter  table " + tableDef.Name + "  MODIFY   " + tmpStr + " ";
                                            cmd    = Database.GetSqlStringCommand(strSql.ToUpper());
                                            Database.ExecuteNonQuery(cmd);
                                            if (!string.IsNullOrEmpty(tableDef.FieldDefs[i].Constrains))
                                            {
                                                strConstrains.Append(tableDef.FieldDefs[i].Constrains.ToUpper() + ";");
                                            }
                                        }
                                        catch (System.Exception ex)
                                        {
                                        }


                                        existTbDef.FieldDefs.Remove(existTbDef.FieldDefs[j]);
                                        tableDef.FieldDefs.Remove(tableDef.FieldDefs[i]);

                                        j--;
                                        i--;

                                        break;
                                    }
                                }
                            }
                        }


                        //添加列
                        foreach (FieldDef fd in tableDef.FieldDefs)
                        {
                            tmpStr    = "";
                            attachStr = "";


                            if (!string.IsNullOrEmpty(fd.Constrains))
                            {
                                strConstrains.Append(fd.Constrains + " ;");
                            }
                            if (!string.IsNullOrEmpty(fd.DefaultValue))
                            {
                                attachStr += "  default '" + fd.DefaultValue + "'";
                            }

                            if (fd.Type.ToLower().ToLower() == "number")
                            {
                                tmpStr = fd.Name + " " + fd.Type.ToLower().ToLower() + "(" + fd.Length + "," + fd.Procesion + ")";
                            }
                            else if (fd.Length > 0)
                            {
                                tmpStr = fd.Name + " " + fd.Type.ToLower().ToLower() + "(" + fd.Length + ")";
                            }
                            else
                            {
                                tmpStr = fd.Name + " " + fd.Type.ToLower().ToLower();
                            }

                            if (!fd.IsNull)
                            {
                                attachStr += "  not null ";
                            }
                            else if (fd.IsPriKey)
                            {
                                attachStr += "  not null ";
                            }

                            if (fd.IsGuid)
                            {
                                attachStr += "  unique ";
                            }


                            if (fd.Type.ToLower().ToLower() == "number")
                            {
                                tmpStr = fd.Name + " " + fd.Type.ToLower().ToLower() + "(" + fd.Length + "," + fd.Procesion + ")";
                            }
                            else if (fd.Length > 0 && fd.Type.ToLower().ToLower() != "int" && fd.Type.ToLower().ToLower() != "blob" && fd.Type.ToLower().ToLower() != "clob" && fd.Type.ToLower().ToLower() != "nclob" && fd.Type.ToLower().ToLower() != "date" && fd.Type.ToLower().ToLower() != "timestamp")
                            {
                                tmpStr = fd.Name + " " + fd.Type.ToLower().ToLower() + "(" + fd.Length + ")";
                            }
                            else
                            {
                                tmpStr = fd.Name + " " + fd.Type.ToLower().ToLower();
                            }
                            tmpStr += attachStr;

                            strSql = "alter table " + tableDef.Name + " add  " + tmpStr + "";
                            cmd    = Database.GetSqlStringCommand(strSql.ToUpper());
                            Database.ExecuteNonQuery(cmd);


                            //字段说明
                            if (!string.IsNullOrEmpty(fd.Alias))
                            {
                                noteStr = "COMMENT ON COLUMN " + tableDef.Name + "." + fd.Name + " IS '" + fd.Alias + "'";
                                cmd     = Database.GetSqlStringCommand(noteStr.ToUpper());
                                Database.ExecuteNonQuery(cmd);
                            }
                        }

                        //删除列
                        foreach (FieldDef fd1 in existTbDef.FieldDefs)
                        {
                            strSql = "alter  table " + tableDef.Name + " DROP COLUMN " + fd1.Name + "";
                            cmd    = Database.GetSqlStringCommand(strSql.ToUpper());
                            Database.ExecuteNonQuery(cmd);
                        }



                        if (!string.IsNullOrEmpty(strConstrains.ToString()))
                        {
                            string[] strArr = strConstrains.ToString().Split(';');
                            foreach (string s in strArr)
                            {
                                cmd = Database.GetSqlStringCommand(s.ToUpper());
                                Database.ExecuteNonQuery(cmd);
                            }
                        }


                        //表主键
                        string strKeyName = "";
                        string strKeySql  = "";
                        foreach (FieldDef field in tableDef.MainKeys)
                        {
                            if (field.Name != "")
                            {
                                strKeyName += field.Name + ",";
                            }
                        }
                        strKeyName = strKeyName.TrimEnd(',');
                        if (strKeyName != "")
                        {
                            try
                            {
                                strKeySql = "ALTER TABLE " + tableDef.Name + " DROP CONSTRAINT PK_" + tableDef.Name + "";
                                cmd       = Database.GetSqlStringCommand(strKeySql.ToUpper());
                                Database.ExecuteNonQuery(cmd);
                            }
                            catch
                            {
                            }

                            strKeySql = "ALTER TABLE " + tableDef.Name + "  ADD CONSTRAINT PK_" + tableDef.Name + " PRIMARY KEY ( " + strKeyName + ")";
                            cmd       = Database.GetSqlStringCommand(strKeySql.ToUpper());
                            Database.ExecuteNonQuery(cmd);
                        }

                        bRet = true;
                    }
                    else
                    {
                        bRet = createTable(tableDef);
                    }
                }
                else
                {
                    bRet = false;
                }
            }
            catch
            {
                bRet = false;
            }

            return(bRet);
        }
示例#11
0
        /// <summary>
        /// 创建数据库表
        /// </summary>
        /// <param name="tableDef"></param>
        /// <returns>成功返回true</returns>
        public override bool createTable(TableDef tableDef)
        {
            bool   bRet      = false;
            string tmpStr    = "";
            string attachStr = "";//约束信息

            //字段说明
            StringBuilder noteStr = new StringBuilder();
            DbCommand     cmd;

            try
            {
                if (tableDef != null)
                {
                    if (isExistObject(tableDef.Name, "Table"))
                    {
                        bRet = modifyTable(tableDef);
                    }
                    else
                    {
                        StringBuilder strSql        = new StringBuilder();
                        StringBuilder strConstrains = new StringBuilder();//约束
                        strSql.Append("CREATE  TABLE " + tableDef.Name);
                        strSql.Append("(  ");
                        foreach (FieldDef field in tableDef.FieldDefs)
                        {
                            tmpStr    = "";
                            attachStr = "";
                            if (field.Name != "")
                            {
                                //字段说明
                                if (!string.IsNullOrEmpty(field.Alias))
                                {
                                    noteStr.Append("COMMENT ON COLUMN " + tableDef.Name + "." + field.Name + " IS '" + field.Alias + "';");
                                }

                                if (!string.IsNullOrEmpty(field.Constrains))
                                {
                                    strConstrains.Append(field.Constrains + ";");
                                }

                                if (!string.IsNullOrEmpty(field.DefaultValue))
                                {
                                    attachStr += "  default '" + field.DefaultValue + "'";
                                }
                                if (!field.IsNull)
                                {
                                    attachStr += "  not null ";
                                }
                                else if (field.IsPriKey)
                                {
                                    attachStr += "  not null ";
                                }

                                if (field.IsGuid)
                                {
                                    attachStr += "  unique ";
                                }

                                if (field.Type.ToLower().ToLower() == "number")
                                {
                                    tmpStr = field.Name + " " + field.Type.ToLower().ToLower() + "(" + field.Length + "," + field.Procesion + ")";
                                }
                                else if (field.Length > 0 && field.Type.ToLower().ToLower() != "int" && field.Type.ToLower().ToLower() != "blob" && field.Type.ToLower().ToLower() != "clob" && field.Type.ToLower().ToLower() != "nclob" && field.Type.ToLower().ToLower() != "date" && field.Type.ToLower().ToLower() != "timestamp")
                                {
                                    tmpStr = field.Name + " " + field.Type.ToLower().ToLower() + "(" + field.Length + ")";
                                }
                                else
                                {
                                    tmpStr = field.Name + " " + field.Type.ToLower().ToLower();
                                }
                                tmpStr += attachStr + ",";
                                strSql.Append(tmpStr);
                            }
                        }

                        if (tableDef.FieldDefs.Count > 0)
                        {
                            strSql.Remove(strSql.Length - 1, 1);
                            strSql.Append(")");
                        }


                        if (!string.IsNullOrEmpty(strSql.ToString()))
                        {
                            //创建表
                            cmd = Database.GetSqlStringCommand(strSql.ToString().ToUpper());
                            Database.ExecuteNonQuery(cmd);
                        }



                        if (!string.IsNullOrEmpty(noteStr.ToString()))
                        {
                            //字段说明
                            string[] strArr = noteStr.ToString().Split(';');
                            foreach (string s in strArr)
                            {
                                cmd = Database.GetSqlStringCommand(s.ToUpper());
                                Database.ExecuteNonQuery(cmd);
                            }
                        }

                        //表主键
                        string strKeyName = "";
                        string strKeySql  = "";
                        foreach (FieldDef field in tableDef.MainKeys)
                        {
                            if (field.Name != "")
                            {
                                strKeyName += field.Name + ",";
                            }
                        }
                        strKeyName = strKeyName.TrimEnd(',');
                        if (strKeyName != "")
                        {
                            strKeySql = "ALTER TABLE " + tableDef.Name + " ADD CONSTRAINT PK_" + tableDef.Name + " PRIMARY KEY ( " + strKeyName + ")";
                            cmd       = Database.GetSqlStringCommand(strKeySql.ToUpper());
                            Database.ExecuteNonQuery(cmd);
                        }

                        if (!string.IsNullOrEmpty(strConstrains.ToString()))
                        {
                            string[] strArr = strConstrains.ToString().Split(';');
                            foreach (string s in strArr)
                            {
                                cmd = Database.GetSqlStringCommand(s.ToUpper());
                                Database.ExecuteNonQuery(cmd);
                            }
                        }
                        bRet = true;
                    }
                }
                else
                {
                    bRet = false;
                }
            }
            catch
            {
                bRet = false;
            }
            return(bRet);
        }
示例#12
0
        /// <summary>
        /// 返回当前表
        /// </summary>
        /// <param name="tableName"></param>
        /// <returns>失败返回null</returns>
        public override TableDef getTableDef(string tableName)
        {
            TableDef tbDef = new TableDef();
            FieldDef fdDef;

            try
            {
                //返回当前表所有字段
                string strSql = "SELECT USER_TAB_COLS.COLUMN_NAME as colName ,USER_TAB_COLS.DATA_TYPE as colType, USER_TAB_COLS.DATA_LENGTH as colLength,DATA_PRECISION as intLength,DATA_SCALE as pointCount, USER_TAB_COLS.NULLABLE as colIsNull,USER_TAB_COLS.DATA_DEFAULT as colVal, " +
                                "case  when (SELECT col.column_name FROM user_constraints con, user_cons_columns col where con.constraint_name = col.constraint_name and con.constraint_type='P' and col.table_name = upper('" + tableName.ToUpper() + "') and col.column_name = USER_TAB_COLS.COLUMN_NAME) = USER_TAB_COLS.COLUMN_NAME THEN 'True'" +
                                "ELSE 'False'" +
                                " END " +
                                " as pkName, " +
                                "case when (SELECT col.column_name FROM user_constraints con, user_cons_columns col where con.constraint_name = col.constraint_name and con.constraint_type='U' and col.table_name = upper('" + tableName.ToUpper() + "') and col.column_name = USER_TAB_COLS.COLUMN_NAME) = USER_TAB_COLS.COLUMN_NAME THEN 'True'" +
                                "ELSE 'False'" +
                                " END " +
                                " as colIsUnique, " +
                                "case when (select count(*) from user_constraints con, user_cons_columns col, (select t2.table_name,t2.column_name,t1.r_constraint_name from user_constraints t1,user_cons_columns t2 where t1.r_constraint_name=t2.constraint_name and t1.table_name=upper('" + tableName.ToUpper() + "')) r where con.constraint_name=col.constraint_name and con.r_constraint_name=r.r_constraint_name and con.table_name=upper('" + tableName.ToUpper() + "') and col.column_name = USER_TAB_COLS.COLUMN_NAME) > 0 then 'True'" +
                                " else 'False'" +
                                " END " +
                                " as fkName, " +
                                "user_col_comments.comments as colNote FROM USER_TAB_COLS inner join user_col_comments on user_col_comments.TABLE_NAME = USER_TAB_COLS.TABLE_NAME and user_col_comments.COLUMN_NAME=USER_TAB_COLS.COLUMN_NAME and USER_TAB_COLS.TABLE_NAME = upper('" + tableName.ToUpper() + "') ORDER BY USER_TAB_COLS.COLUMN_ID";

                DataTable tb = getQueryTable(strSql, 0, null);
                if (tb != null)
                {
                    tbDef.Name = tableName;
                    foreach (DataRow row in tb.Rows)
                    {
                        fdDef      = new FieldDef();
                        fdDef.Name = row["COLNAME"].ToString();
                        fdDef.Type = row["COLTYPE"].ToString();
                        if (!string.IsNullOrEmpty(row["COLLENGTH"].ToString()))
                        {
                            fdDef.Length = int.Parse(row["COLLENGTH"].ToString());
                        }
                        else
                        {
                            fdDef.Length = 0;
                        }

                        if (!string.IsNullOrEmpty(row["POINTCOUNT"].ToString()))
                        {
                            fdDef.Procesion = int.Parse(row["POINTCOUNT"].ToString());
                        }

                        if (!string.IsNullOrEmpty(row["COLVAL"].ToString()))
                        {
                            fdDef.DefaultValue = row["COLVAL"].ToString();
                        }

                        if (!string.IsNullOrEmpty(row["COLNOTE"].ToString()))
                        {
                            fdDef.Alias = row["COLNOTE"].ToString();
                        }


                        if (!string.IsNullOrEmpty(row["COLISUNIQUE"].ToString()))
                        {
                            fdDef.IsGuid = bool.Parse(row["COLISUNIQUE"].ToString());
                        }
                        else
                        {
                            fdDef.IsGuid = false;
                        }

                        if (row["COLISNULL"].ToString() == "Y")
                        {
                            fdDef.IsNull = true;
                        }
                        else
                        {
                            fdDef.IsNull = false;
                        }

                        fdDef.Constrains = "";
                        tbDef.FieldDefs.Add(fdDef);
                        if (!string.IsNullOrEmpty(row["PKNAME"].ToString()) && row["PKNAME"].ToString() == "True")
                        {
                            fdDef.IsPriKey = true;
                            tbDef.MainKeys.Add(fdDef);
                        }
                        else
                        {
                            fdDef.IsPriKey = false;
                        }
                    }
                }
            }
            catch
            {
                tbDef = null;
            }

            return(tbDef);
        }
示例#13
0
        private bool FillRecordProperties()
        {
            try
            {
                var fInfo = new FileInfo(Path.Combine("info", "recorderProperties.json"));
                if (!fInfo.Exists)
                    throw new Exception(string.Format("Recorder sistem-tablo bilgilerinin bulunduğu {0} bulunamadı",
                                                      fInfo.FullName));
                var json =
                    new DataContractJsonSerializer(
                        typeof(Dictionary<string, RecordProperties<TreeNode>>));
                using (var fs = new StreamReader(fInfo.FullName, Encoding.GetEncoding(1254)))
                {
                    var o = json.ReadObject(fs.BaseStream);
                    if (o == null)
                        throw new Exception(string.Format("{0} dosyasında sistem-tablo bilgileri bulunamadı",
                                                          fInfo.FullName));
                    if (!(o is Dictionary<string, RecordProperties<TreeNode>>))
                        throw new Exception(
                            string.Format("{0} dosyasındaki {1} türü beklenen sistem-tablo bilgi sözlük türünde değil",
                                          fInfo.FullName, o.GetType().Name));
                    propertyLookup = (Dictionary<string, RecordProperties<TreeNode>>)o;

                    var ls = new List<RecordProperties<TreeNode>>();
                    foreach (var key in propertyLookup.Keys)
                    {
                        if (systemLookup.SystemLookup.ContainsKey(key))
                        {
                            var prop = propertyLookup[key];
                            ls.Add(prop);
                            if (prop.Table == null)
                                prop.Table = new Dictionary<string, TableDef<TreeNode>>();
                        }
                    }
                    foreach (var key in systemLookup.SystemLookup.Keys)
                    {
                        if (!propertyLookup.ContainsKey(key))
                        {
                            var prop = new RecordProperties<TreeNode>
                                {
                                    SystemName = key,
                                    Table = new Dictionary<string, TableDef<TreeNode>>()
                                };
                            ls.Add(prop);
                            propertyLookup[key] = prop;
                        }
                    }
                    ls.Sort(CompareByNameSys);
                    foreach (var r in ls)
                    {
                        var node = new TreeNode(r.SystemName);
                        r.Data = node;
                        node.Tag = r;
                        if (r.Table == null)
                            r.Table = new Dictionary<string, TableDef<TreeNode>>();
                        else
                        {
                            var tables = new TableDef<TreeNode>[r.Table.Values.Count];
                            r.Table.Values.CopyTo(tables, 0);

                            Array.Sort(tables, CompareByNameTable);
                            foreach (var t in r.Table.Values)
                            {
                                var nodeSub = new TreeNode { Text = t.Description, Tag = t };
                                t.Data = nodeSub;
                                node.Nodes.Add(nodeSub);
                            }
                        }
                        treeProperties.Nodes.Add(node);
                    }
                    return true;
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(string.Format("Recorder bilgileri yüklenirken hata oluştu: {0}", e.Message), "Hata",
                                MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                return false;
            }
        }
示例#14
0
 private void CheckPropertySaveStatus(RecordProperties<TreeNode> parent, TableDef<TreeNode> node)
 {
     if (propertyDirtyStatus > 0)
     {
         switch (
             MessageBox.Show("Değişiklikleri kaydetmek istiyor musunuz?", "Lütfen Cevaplayınız",
                             MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question,
                             MessageBoxDefaultButton.Button3))
         {
             case DialogResult.Yes:
                 SaveSelectedProperty();
                 break;
             case DialogResult.Cancel:
                 treeProperties.SelectedNode = null;
                 return;
         }
     }
     selectedProperty = parent;
     selectedTable = node;
     ResetSelectionProperty();
 }
示例#15
0
 protected virtual int CompareByNameTable(TableDef<TreeNode> l, TableDef<TreeNode> r)
 {
     if (l == null)
     {
         return r == null ? 0 : 1;
     }
     return r == null ? -1 : l.CompareTo(r);
 }
示例#16
0
 /// <summary>
 /// Checks whether a certain table exists physically in the connected underlying database
 /// </summary>
 public bool Exists(TableDef Tableobject)
 {
     return(Exists(Tableobject.TableName));
 }
示例#17
0
 public ReportSingleEntity(BaseEntity DataSource)
 {
     _DataSource = DataSource;
     tdSource    = MetaData.GetTableDef(DataSource);
 }
示例#18
0
        private static void UpdateTableDef(TableDef td, MemberInfo mi)
        {
            FieldDef fld            = null;
            bool     IsCounterField = false;

            #region Query Primary Key, AutoNumber, AutoNested
            bool isPk;
            PrimaryKeyAttribute[] pkas = (PrimaryKeyAttribute[])
                                         mi.GetCustomAttributes(typeof(PrimaryKeyAttribute), true);
            int FieldLen = 0;
            if (pkas.Length > 0)
            {
                isPk = true;
                AutoNumberKeyAttribute aka = pkas[0] as AutoNumberKeyAttribute;
                if (aka != null)
                {
                    aka._FieldName = mi.Name;
                    if (td._AutoNumberKeyAtr == null)
                    {
                        td._AutoNumberKeyAtr = new List <AutoNumberKeyAttribute>();
                    }
                    td._AutoNumberKeyAtr.Add(aka);
                    FieldLen = aka._Template.Length;
                }
                else
                {
                    AutoNestedKeyAttribute ank = pkas[0] as AutoNestedKeyAttribute;
                    if (ank != null)
                    {
                        ank._FieldName = mi.Name;
                        if (td._AutoNestedKeyAtr != null)
                        {
                            throw new ApplicationException(string.Format(
                                                               ErrorMetaData.MultiNestedKey, mi.Name));
                        }
                        td._AutoNestedKeyAtr = ank;
                    }
                    else
                    {
                        CounterKeyAttribute cka = pkas[0] as CounterKeyAttribute;
                        if (cka != null)
                        {
                            if (td._fldCounterField != null)
                            {
                                throw new ApplicationException(string.Format(
                                                                   ErrorMetaData.MultiCounter, mi.Name));
                            }
                            IsCounterField = true;
                        }
                    }
                }
            }
            else
            {
                isPk = false;
            }

            AutoNumberAttribute[] anas = (AutoNumberAttribute[])
                                         mi.GetCustomAttributes(typeof(AutoNumberAttribute), true);
            if (anas.Length > 0)
            {
                anas[0]._FieldName = mi.Name;
                if (td._AutoNumberAtr == null)
                {
                    td._AutoNumberAtr = new List <AutoNumberAttribute>();
                }
                td._AutoNumberAtr.Add(anas[0]);
                FieldLen = anas[0]._Template.Length;
            }
            #endregion

            DataTypeLoadSqlAttribute[] dtls = (DataTypeLoadSqlAttribute[])
                                              mi.GetCustomAttributes(typeof(DataTypeLoadSqlAttribute), true);
            if (dtls.Length > 0)
            {
                #region Query DataTypeLoadSql
                if (isPk)
                {
                    throw new ApplicationException(string.Format(
                                                       ErrorMetaData.DataTypeLoadSqlPk, mi.Name));
                }

                if (dtls[0].GetSqlQueryLen() == 0)
                {
                    TableDef tdP;

                    if (dtls[0]._ParentType != td._ClassType)
                    {
                        tdP = MetaData.GetTableDef(dtls[0]._ParentType);
                    }
                    else
                    {
                        tdP = td;
                    }
                    if (dtls[0].ParentFieldName.Length == 0)
                    {
                        dtls[0].ParentFieldName = mi.Name;
                    }

                    FieldDef fldP = tdP.GetFieldDef(dtls[0].ParentFieldName);
                    if (fldP == null && !object.ReferenceEquals(tdP, td))
                    {
                        throw new ApplicationException(string.Format(
                                                           ErrorMetaData.DataTypeLoadSqlParentNotFound,
                                                           mi.Name, td.TableName));
                    }
                    fld = new FieldDef(mi, td._TableName, fldP, dtls[0]);
                }
                else
                {
                    fld = new FieldDef(mi, td._TableName, null, dtls[0]);
                }
                td.NonKeyFields.Add(mi.Name, fld);
                #endregion
            }
            else
            {
                #region Query DataType
                DataTypeAttribute[] dtas = (DataTypeAttribute[])
                                           mi.GetCustomAttributes(typeof(DataTypeAttribute), true);
                if (dtas.Length == 1)
                {
                    if (isPk)
                    {
                        fld = new FieldDef(mi, dtas[0], true);
                        td.KeyFields.Add(mi.Name, fld);
                    }
                    else
                    {
                        fld = new FieldDef(mi, dtas[0], false);
                        td.NonKeyFields.Add(mi.Name, fld);
                    }
                }
                else if (dtas.Length > 1)
                {
                    throw new ApplicationException(string.Format(
                                                       ErrorMetaData.MultiDataType, mi.Name));
                }
                else if (isPk)
                {
                    // If Auto DataTypeAttribute :
                    if (IsCounterField)
                    {
                        fld = new FieldDef(mi,
                                           new DataTypeIntegerAttribute(), true);
                        td._fldCounterField = fld;
                    }
                    else if (td._AutoNestedKeyAtr != null &&
                             td._AutoNestedKeyAtr._FieldName == mi.Name)
                    {
                        fld = new FieldDef(mi,
                                           new DataTypeVarCharAttribute(0), true);
                    }
                    else if (mi.GetCustomAttributes(typeof(TransactionDateAttribute), true).Length > 0)
                    {
                        fld = new FieldDef(mi,
                                           new DataTypeDateAttribute(), true);
                        td.KeyFields.Add(mi.Name, fld);
                        td.fldTransactionDate = fld;
                        return;
                    }
                    else if (FieldLen > 0)
                    {
                        fld = new FieldDef(mi,
                                           new DataTypeVarCharAttribute(FieldLen), true);
                    }
                    else
                    {
                        throw new ApplicationException(string.Format(
                                                           ErrorMetaData.DataTypeNotFound, mi.Name));
                    }
                    td.KeyFields.Add(mi.Name, fld);
                }
                else if (mi.GetCustomAttributes(typeof(TransactionDateAttribute), true).Length > 0)
                {
                    fld = new FieldDef(mi,
                                       new DataTypeDateAttribute(), false);
                    td.NonKeyFields.Add(mi.Name, fld);
                }
                else if (FieldLen > 0)
                {
                    fld = new FieldDef(mi,
                                       new DataTypeVarCharAttribute(FieldLen), false);
                    td.NonKeyFields.Add(mi.Name, fld);
                }
                #endregion
            }

            if (fld != null)
            {
                #region Query EmptyError
                EmptyErrorAttribute[] eeas = (EmptyErrorAttribute[])
                                             mi.GetCustomAttributes(typeof(EmptyErrorAttribute), true);
                if (eeas.Length > 0)
                {
                    fld.EmptyErrorAtr = eeas[0];
                    if (fld.EmptyErrorAtr.ErrorMessage.Length == 0)
                    {
                        fld.EmptyErrorAtr.ErrorMessage = string.Concat("'",
                                                                       BaseUtility.SplitName(fld._FieldName), "' tidak boleh kosong");
                    }
                }
                #endregion

                DescriptionAttribute[] dsa = (DescriptionAttribute[])
                                             mi.GetCustomAttributes(typeof(DescriptionAttribute), true);
                if (dsa.Length > 0)
                {
                    fld.Description = dsa[0].Description;
                }

                PrintCounterAttribute[] pcas = (PrintCounterAttribute[])
                                               mi.GetCustomAttributes(typeof(PrintCounterAttribute), true);
                if (pcas.Length > 0)
                {
                    td.fldPrintCounter = fld;
                }

                if (mi.GetCustomAttributes(typeof(TransactionDateAttribute),
                                           true).Length > 0)
                {
                    td.fldTransactionDate = fld;
                }

                fld.CheckFieldType(td._TableName);
            }
        }
示例#19
0
        public void ShowForm(XtraForm MdiParent, Type FormType,
                             Type EntityType, DataPersistance dp,
                             Type FilterFormType, string DataFilter)
        {
            _Evaluator      = new Evaluator();
            Dp              = dp;
            this.DataFilter = DataFilter;
            comboBoxEdit1.Properties.Items.Add("(Layout Default)");

            if (EntityType != null)
            {
                _FormType   = FormType;
                _EntityType = EntityType;

                td = MetaData.GetTableDef(EntityType);
                Dp.ValidateTableDef(td);
                if (td.fldTransactionDate != null)
                {
                    dateEdit1.DateTime = DateTime.Today;
                    dateEdit2.DateTime = DateTime.Today;
                }
                else
                {
                    label3.Visible    = false;
                    label4.Visible    = false;
                    dateEdit1.Visible = false;
                    dateEdit2.Visible = false;
                }
                _ReportName = BaseUtility.SplitName(_EntityType.Name);
            }
            else
            {
                label3.Visible    = false;
                label4.Visible    = false;
                dateEdit1.Visible = false;
                dateEdit2.Visible = false;
                if (FilterFormType != null)
                {
                    _ReportName = FilterFormType.Name.Substring(0, 3).ToLower();
                    if (_ReportName == "frm" || _ReportName == "rpt")
                    {
                        _ReportName = BaseUtility.SplitName(
                            FilterFormType.Name.Substring(3));
                    }
                    else
                    {
                        _ReportName = BaseUtility.SplitName(FilterFormType.Name);
                    }
                }
                else
                {
                    _ReportName = "Bebas";
                }
            }
            Text = "Laporan " + _ReportName;

            comboBoxEdit1.Properties.Items.AddRange(
                DocBrowseLayout.GetListLayout(_ReportName));

            this.MdiParent = MdiParent;

            if (FilterFormType == null)
            {
                splitContainerControl1.PanelVisibility = SplitPanelVisibility.Panel2;
            }
            else
            {
                _FilterForm = BaseFactory.CreateInstance(FilterFormType) as IFilterForm;
                if (_FilterForm == null)
                {
                    XtraMessageBox.Show("Form Filter harus implement Interface IFilterForm !",
                                        "Error Filter", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    Close();
                    return;
                }
                XtraForm Frm = _FilterForm as XtraForm;
                if (Frm != null)
                {
                    Frm.FormBorderStyle = FormBorderStyle.None;
                    Frm.TopLevel        = false;
                    Frm.Parent          = xtraScrollableControl1;
                    splitContainerControl1.SplitterPosition = Frm.Height + 5;
                    Frm.KeyPreview = true;
                    Frm.KeyDown   += new KeyEventHandler(frmGridReport_KeyDown);
                    xtraScrollableControl1.BackColor = Frm.BackColor;
                    Frm.Show();
                }
                else
                {
                    splitContainerControl1.PanelVisibility = SplitPanelVisibility.Panel2;
                }
            }
            barButtonItem8_ItemClick(null, null);

            DefaultLayout = new MemoryStream();
            pivotGridControl1.SaveLayoutToStream(DefaultLayout);

            string CurrBrowseLayoutId = string.Empty;
            bool   Tmp;

            DocDefault.GetDefaultLayout(_ReportName,
                                        out CurrBrowseLayoutId, out CurrPrintLayoutId, out Tmp);
            Show();
            comboBoxEdit1.SelectedItem = CurrBrowseLayoutId;
            if (comboBoxEdit1.SelectedIndex < 0)
            {
                comboBoxEdit1.SelectedIndex = 0;
            }
            textEdit1.Focus();
        }
示例#20
0
        private static TableDef BuildEntityMetaData(Type EntityType)
        {
            if (EntityType.IsAbstract)
            {
                return(null);
            }

            TableDef td;

            TableDefs.TryGetValue(EntityType, out td);
            if (td != null)
            {
                return(td);
            }

            ViewEntityAttribute[] dvas = (ViewEntityAttribute[])EntityType.GetCustomAttributes(
                typeof(ViewEntityAttribute), true);
            bool dvaExist = dvas.Length > 0;

            if (dvaExist)
            {
                td = new TableDef(dvas[0], EntityType);
                Type[] tds = dvas[0].TypeDependends;
                if (tds != null && tds.Length > 0)
                {
                    ViewDependents.Add(EntityType, tds);
                }
            }
            else
            {
                td = new TableDef(EntityType);
            }

            string[] FKFields = null;

            #region Check Inheritance
            if (!EntityType.IsSubclassOf(typeof(ParentEntity)))
            {
                Type BaseType = EntityType.BaseType;

                while (BaseType != null && BaseType.Name != TChildName)
                {
                    BaseType = BaseType.BaseType;
                }
                if (BaseType != null)
                {
                    td._ParentClassType = BaseType.GetGenericArguments()[0];
                    TableDef entParent = GetTableDef(td._ParentClassType);
                    FKFields = new string[entParent.KeyFields.Count];
                    int i = 0;
                    foreach (FieldDef fd in entParent.KeyFields.Values)
                    {
                        td.KeyFields.Add(fd._FieldName, new FieldDef(fd));
                        FKFields[i++] = fd._FieldName;
                    }
                }
            }
            #endregion

            int FKCount = td.KeyFields.Count;

            #region Read TableName
            TableNameAttribute[] tnas = (TableNameAttribute[])EntityType.GetCustomAttributes(
                typeof(TableNameAttribute), true);
            if (tnas.Length > 0)
            {
                td.TableName = tnas[0]._TableName;
            }
            else
            {
                td.TableName = EntityType.Name;
            }
            #endregion

            #region Read Fields/ Properties
            foreach (MemberInfo mi in EntityType.FindMembers(
                         MemberTypes.Field | MemberTypes.Property,
                         BindingFlags.NonPublic | BindingFlags.Public |
                         BindingFlags.Instance, null, null))
            {
                if (mi.MemberType == MemberTypes.Property)
                {
                    if (((PropertyInfo)mi).PropertyType.Name == TColName)
                    {
                        td.ChildEntities.Add(new EntityCollDef(mi));
                    }
                    else
                    {
                        UpdateTableDef(td, mi);
                    }
                }
                else
                {
                    if (((FieldInfo)mi).FieldType.Name == TColName)
                    {
                        td.ChildEntities.Add(new EntityCollDef(mi));
                    }
                    else
                    {
                        UpdateTableDef(td, mi);
                    }
                }
            }
            #endregion

            if (!dvaExist)
            {
                if (FKCount == td.KeyFields.Count && (FKCount > 0 ||
                                                      td.NonKeyFields.Count > 0))
                {
                    NoKeyEntityAttribute[] nkeas = (NoKeyEntityAttribute[])EntityType.GetCustomAttributes(
                        typeof(NoKeyEntityAttribute), true);
                    if (nkeas.Length == 0)
                    {
                        throw new ApplicationException(ErrorMetaData.KeyNotFound);
                    }
                }
                if (td._AutoNestedKeyAtr != null)
                {
                    td.GetFieldDef(td._AutoNestedKeyAtr._FieldName)
                    ._DataTypeAtr._Length = td.GetFieldDef(
                        td._AutoNestedKeyAtr._ParentField)._DataTypeAtr._Length;
                }

                CheckAutoNumber(td, EntityType, td._AutoNumberKeyAtr);
                CheckAutoNumber(td, EntityType, td._AutoNumberAtr);

                #region Read Indexes
                IndexAttribute[] ias = (IndexAttribute[])EntityType.GetCustomAttributes(
                    typeof(IndexAttribute), true);

                foreach (IndexAttribute ia in ias)
                {
                    if (ia._Unique)
                    {
                        td.IndexedFields.Add("Unique|" + ia._IndexedFields);
                    }
                    else
                    {
                        td.IndexedFields.Add("NotUnique|" + ia._IndexedFields);
                    }
                }

                CheckIndexes(td, ias);
                #endregion

                #region Read ParentRelation
                //ParentRelationAttribute[] pras = (ParentRelationAttribute[])EntityType.GetCustomAttributes(
                //    TPRA, true);
                //foreach (ParentRelationAttribute pra in pras)
                //{
                //    pra._ParentType = EntityType;
                //    td.ParentRelations.Add(pra);

                //    if (pra._ParentFields == null)
                //    {
                //        string[] Fields = new string[td.KeyFields.Count];
                //        int i = 0;
                //        foreach (FieldDef fld in td.KeyFields.Values)
                //            Fields[i++] = fld._FieldName;
                //        pra._ParentFields = Fields;
                //        pra._ChildFields = Fields;
                //    }
                //}
                #endregion

                CheckFields(td, FKFields, FKCount);
                bool TSExist = false;
                foreach (FieldDef fd in td.NonKeyFields.Values)
                {
                    // Parent adalah diri sendiri...
                    if (fd._DataTypeAtr == null)
                    {
                        fd._DataTypeAtr = td.GetFieldDef(
                            fd._dtlsa.ParentFieldName)._DataTypeAtr;
                        fd.CheckFieldType(td._TableName);
                    }
                    if (fd.DataType == DataType.TimeStamp)
                    {
                        if (TSExist)
                        {
                            throw new ApplicationException(string.Format(
                                                               ErrorMetaData.DuplicateTimeStamp, td._TableName));
                        }
                        td.fldTimeStamp = fd;
                        TSExist         = true;
                    }
                }
            }

            EnableCancelEntityAttribute[] ddes = (EnableCancelEntityAttribute[])
                                                 EntityType.GetCustomAttributes(typeof(EnableCancelEntityAttribute), true);
            if (ddes.Length > 0)
            {
                Type tpi = EntityType.GetInterface("ICancelEntity");
                td.EnableCancelEntityAtr = ddes[0];

                #region Cek Cancel Field
                string   strFldName = td.EnableCancelEntityAtr.GetCancelDateTimeFieldName();
                FieldDef TmpFld     = td.GetFieldDef(strFldName);
                if (TmpFld == null)
                {
                    DataTypeDateTimeAttribute dta = new DataTypeDateTimeAttribute();
                    dta.Default = "1/1/1900";
                    td.NonKeyFields.Add(strFldName, new FieldDef(strFldName,
                                                                 tpi.GetProperty("CancelDateTime"), dta, false));
                }
                else
                if (TmpFld.DataType != DataType.DateTime)
                {
                    throw new ApplicationException(string.Format(
                                                       ErrorMetaData.DataTypeCancelDateTimeIsIncorrect, td._TableName,
                                                       strFldName));
                }

                strFldName = td.EnableCancelEntityAtr.GetCancelStatusFieldName();
                TmpFld     = td.GetFieldDef(strFldName);
                if (TmpFld == null)
                {
                    td.NonKeyFields.Add(strFldName, new FieldDef(strFldName,
                                                                 tpi.GetProperty("CancelStatus"),
                                                                 new DataTypeVarCharAttribute(10), false));
                }
                else
                if (TmpFld.DataType != DataType.VarChar)
                {
                    throw new ApplicationException(string.Format(
                                                       ErrorMetaData.DataTypeCancelStatusIsIncorrect, td._TableName,
                                                       strFldName));
                }

                strFldName = td.EnableCancelEntityAtr.GetCancelNotesFieldName();
                TmpFld     = td.GetFieldDef(strFldName);
                if (TmpFld == null)
                {
                    td.NonKeyFields.Add(strFldName, new FieldDef(strFldName,
                                                                 tpi.GetProperty("CancelNotes"),
                                                                 new DataTypeVarCharAttribute(100), false));
                }
                else
                if (TmpFld.DataType != DataType.VarChar)
                {
                    throw new ApplicationException(string.Format(
                                                       ErrorMetaData.DataTypeCancelNotesIsIncorrect, td._TableName,
                                                       strFldName));
                }

                strFldName = td.EnableCancelEntityAtr.GetCancelUserFieldName();
                TmpFld     = td.GetFieldDef(strFldName);
                if (TmpFld == null)
                {
                    td.NonKeyFields.Add(strFldName, new FieldDef(strFldName,
                                                                 tpi.GetProperty("CancelUser"),
                                                                 new DataTypeVarCharAttribute(20), false));
                }
                else
                if (TmpFld.DataType != DataType.VarChar)
                {
                    throw new ApplicationException(string.Format(
                                                       ErrorMetaData.DataTypeCancelUserIsIncorrect, td._TableName,
                                                       strFldName));
                }
                #endregion
            }
            return(td);
        }
示例#21
0
        public IList ShowForm(IList ListSrc,
                              string Caption, EntityColumnShow ecs)
        {
            if (ListSrc == null || ListSrc.Count == 0)
            {
                XtraMessageBox.Show("Data Tidak Ditemukan !",
                                    "Error Membaca Data " + Caption,
                                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                return(null);
            }

            td = MetaData.GetTableDef(ListSrc[0].GetType());
            if (ecs == null)
            {
                ecs = new EntityColumnShow(string.Join(
                                               ",", td.GetListFieldNames(true).ToArray()));
            }

            this.ecs = ecs;
            gridControl1.BeginUpdate();
            try
            {
                gridControl1.DataSource =
                    new ReportGrid(td.ClassType, ListSrc, ecs);
                string[] cols;
                bool     FromECS;
                if (ecs.ColumnShow.Length > 0)
                {
                    cols    = ecs.ColumnShow.Split(',');
                    FromECS = true;
                }
                else
                {
                    cols    = td.GetListFieldNames(true).ToArray();
                    FromECS = false;
                }

                foreach (GridColumn gc in gridView1.Columns)
                {
                    gc.VisibleIndex = -1;
                }

                int        i        = 0;
                GridColumn FirstCol = null;
                foreach (string col in cols)
                {
                    int        idx = FromECS ? col.IndexOf(" AS ", StringComparison.OrdinalIgnoreCase) : -1;
                    GridColumn gc;
                    if (idx < 0)
                    {
                        gc = gridView1.Columns[col.Trim()];
                    }
                    else
                    {
                        gc         = gridView1.Columns[col.Substring(0, idx).Trim()];
                        gc.Caption = BaseUtility.SplitName(col.Substring(idx + 4).Trim());
                    }
                    if (i == 0)
                    {
                        FirstCol = gc;
                    }
                    gc.VisibleIndex = i++;
                }

                gridView1.FocusedColumn = FirstCol;

                if (ecs.ListChild.Count > 0)
                {
                    gridControl1.ViewRegistered += new ViewOperationEventHandler(gridControl1_ViewRegistered);
                    int j = 0;
                    if (ecs.ListChild.Count == 1)
                    {
                        gridView1.OptionsDetail.ShowDetailTabs = false;
                    }

                    foreach (ChildColumnShow cs in ecs.ListChild)
                    {
                        GridView gv = new GridView(gridControl1);
                        gv.OptionsDetail.EnableMasterViewMode  = false;
                        gv.OptionsView.ColumnAutoWidth         = false;
                        gv.OptionsView.EnableAppearanceEvenRow = true;
                        gv.OptionsView.EnableAppearanceOddRow  = true;
                        gv.OptionsView.ShowGroupPanel          = false;
                        gv.BestFitMaxRowCount = 15;

                        gridControl1.LevelTree.Nodes.Add(cs.ChildName, gv);

                        if (cs.ColumnShow.Length == 0)
                        {
                            cols = td.ChildEntities[j].GetTableDef()
                                   .GetListFieldNames(true).ToArray();
                            FromECS = false;
                        }
                        else
                        {
                            cols    = cs.ColumnShow.Split(',');
                            FromECS = true;
                        }

                        i = 0;
                        foreach (string colName in cols)
                        {
                            int idx = FromECS ? colName.IndexOf(" AS ",
                                                                StringComparison.OrdinalIgnoreCase) : -1;
                            GridColumn gc;
                            if (idx < 0)
                            {
                                gc = gv.Columns.AddField(colName.Trim());
                            }
                            else
                            {
                                gc         = gv.Columns.AddField(colName.Substring(0, idx).Trim());
                                gc.Caption = BaseUtility.SplitName(colName.Substring(idx + 4).Trim());
                            }
                            gc.VisibleIndex           = i++;
                            gc.OptionsColumn.ReadOnly = true;
                        }

                        BaseWinFramework.WinForm.AutoFormat
                        .AutoFormatReadOnlyGridView(
                            td.ChildEntities[j++].GetChildType(), gv, true);
                    }
                }
                BaseWinFramework.WinForm.AutoFormat
                .AutoFormatReadOnlyGridView(td.ClassType,
                                            gridView1, true);
            }
            catch
            {
                XtraMessageBox.Show("Nama Kolom tidak ditemukan dalam Entity",
                                    "Error mengatur penampakan kolom",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally { gridControl1.EndUpdate(); }

            Pilih = new List <bool>(ListSrc.Count);

            for (int i = 0; i < ListSrc.Count; i++)
            {
                Pilih.Add(false);
            }

            if (Caption.Length == 0)
            {
                Caption = "Pilih " + BaseUtility.SplitName(td.ClassType.Name);
            }
            Text = Caption;
            gridView1.BeginDataUpdate();
            try
            {
                foreach (GridColumn gcol in gridView1.Columns)
                {
                    gcol.OptionsColumn.ReadOnly = true;
                }

                GridColumn gc = gridView1.Columns.Add();
                gc.FieldName   = "xPilih";
                gc.UnboundType = UnboundColumnType.Boolean;
                gc.Caption     = "Pilih";
                gc.AppearanceHeader.TextOptions
                .HAlignment = HorzAlignment.Center;
                gc.OptionsFilter.AllowFilter = false;
                gc.VisibleIndex = 0;
                BaseWinFramework.WinForm.AutoFormat.AutoFormatGridControl(gridControl1, true);
                gridView1.BestFitColumns();
                gc.Width = 50;
                gridView1.FocusedColumn = gc;
            }
            finally
            {
                gridView1.EndDataUpdate();
            }
            IsOk   = false;
            RetVal = ListSrc;
            ShowDialog();
            return(IsOk ? ListSrc : null);
        }
示例#22
0
        public static TableDef GetTableDef(Type EntityType)
        {
            EntityType = BaseFactory.GetObjType(EntityType);

            TableDef newTd;

            if (TableDefs.TryGetValue(EntityType, out newTd))
            {
                return(newTd);
            }

            try
            {
                newTd = BuildEntityMetaData(EntityType);
                if (TableDefs.ContainsKey(EntityType))
                {
                    return(newTd);
                }
                else
                {
                    TableDefs.Add(EntityType, newTd);
                    if (!NameTableDefs.ContainsKey(newTd._TableName))
                    {
                        NameTableDefs.Add(newTd._TableName, newTd);
                    }

                    CheckTableDef(newTd);

                    foreach (RelationAttribute ra in (RelationAttribute[])
                             EntityType.GetCustomAttributes(typeof(RelationAttribute), true))
                    {
                        if (ra.ChildType == null)
                        {
                            ra.ChildType = EntityType;
                        }
                        newTd.ChildRelations.Add(ra);

                        TableDef tdParent = MetaData.GetTableDef(ra._ParentType);
                        tdParent.ParentRelations.Add(ra);

                        if (ra._ParentFields == null)
                        {
                            string[] Fields = new string[tdParent.KeyFields.Count];
                            int      i      = 0;
                            foreach (FieldDef fld in tdParent.KeyFields.Values)
                            {
                                Fields[i++] = fld._FieldName;
                            }
                            ra._ParentFields = Fields;
                            ra._ChildFields  = Fields;
                            ra._ParentFields = Fields;
                            ra._ChildFields  = Fields;
                        }

                        CheckChildRelation(ra, tdParent, newTd);
                    }

                    return(newTd);
                }
            }
            catch (Exception ex)
            {
                throw new ApplicationException(string.Format(
                                                   ErrorMetaData.BuildMetaData, EntityType.Name,
                                                   ex.Message));
            }
        }
        protected override string GetSqlUpdateTable(TableDef MetaTd,
                                                    TableDef dbTd)
        {
            string        TableName     = MetaTd.TableName;
            StringBuilder strDropIndex  = new StringBuilder();
            StringBuilder strAddIndex   = new StringBuilder();
            StringBuilder strDropColumn = new StringBuilder();
            StringBuilder strAddColumn  = new StringBuilder();

            int i, j;

            j = MetaTd.IndexedFields.Count;
            if (dbTd.IndexedFields.Count < j)
            {
                j = dbTd.IndexedFields.Count;
            }

            #region Check updated Indexes
            for (i = 0; i < j; i++)
            {
                string index = MetaTd.IndexedFields[i];
                if (index.ToLower() != dbTd.IndexedFields[i].ToLower())
                {
                    strDropIndex.Append("\0DROP INDEX ").Append(TableName)
                    .Append(".IX_").Append(TableName)
                    .Append("_").Append(i);

                    int idx = index.IndexOf('|');
                    if (idx == 6)
                    {
                        strAddIndex.Append("\0CREATE UNIQUE NONCLUSTERED INDEX IX_");
                    }
                    else
                    {
                        strAddIndex.Append("\0CREATE NONCLUSTERED INDEX IX_");
                    }
                    strAddIndex.Append(TableName).Append("_")
                    .Append(i).Append(" ON ")
                    .Append(TableName).Append("(").Append(
                        index.Substring(idx + 1)).Append(")");
                }
            }
            #endregion

            #region Check Dropped Indexes
            j = dbTd.IndexedFields.Count;
            for (; i < j; i++)
            {
                strDropIndex.Append("\0DROP INDEX ").Append(TableName)
                .Append(".IX_").Append(TableName).Append("_")
                .Append(i);
            }
            #endregion

            #region Check Inserted Indexes
            j = MetaTd.IndexedFields.Count;
            for (; i < j; i++)
            {
                string index = MetaTd.IndexedFields[i];
                int    idx   = index.IndexOf('|');
                if (idx == 6)
                {
                    strAddIndex.Append("\0CREATE UNIQUE NONCLUSTERED INDEX IX_");
                }
                else
                {
                    strAddIndex.Append("\0CREATE NONCLUSTERED INDEX IX_");
                }
                strAddIndex.Append(TableName).Append("_")
                .Append(i).Append(" ON ")
                .Append(TableName).Append("(").Append(
                    index.Substring(idx + 1)).Append(")");
            }
            #endregion

            #region Check Fields
            bool PKChanged = false;
            #region Check Deleted Fields & Updated Fields
            foreach (FieldDef dbFd in dbTd.KeyFields.Values)
            {
                string   FieldName = dbFd.FieldName;
                FieldDef MtFd;
                if (!MetaTd.KeyFields.TryGetValue(FieldName, out MtFd))
                {
                    if (!MetaTd.NonKeyFields.TryGetValue(FieldName, out MtFd) ||
                        MtFd.GetDTLSA() != null)
                    {
                        strDropColumn.Append("\0ALTER TABLE ").Append(TableName)
                        .Append(" DROP COLUMN ").Append(FieldName);
                        PKChanged = true;
                        continue;
                    }
                    else
                    {
                        PKChanged = true;
                    }
                }

                if (!IsFieldEqual(MtFd, dbFd))
                {
                    PKChanged = true;
                    strAddColumn.Append("\0ALTER TABLE ").Append(TableName)
                    .Append(" ALTER COLUMN ").Append(FieldName)
                    .Append(SqlServerType(MtFd))
                    .Append(" NOT NULL");
                }
            }
            foreach (FieldDef dbFd in dbTd.NonKeyFields.Values)
            {
                string   FieldName = dbFd.FieldName;
                FieldDef MtFd;
                if (!MetaTd.NonKeyFields.TryGetValue(FieldName, out MtFd) ||
                    MtFd.GetDTLSA() != null)
                {
                    if (!MetaTd.KeyFields.TryGetValue(FieldName, out MtFd))
                    {
                        strDropColumn.Append("\0ALTER TABLE ").Append(TableName)
                        .Append(" DROP COLUMN ")
                        .Append(FieldName);
                        continue;
                    }
                    else
                    {
                        PKChanged = true;
                    }
                }

                if (!IsFieldEqual(MtFd, dbFd))
                {
                    if (MtFd.DataType == DataType.Image || MtFd.DataType == DataType.Binary)
                    {
                        strAddColumn.Append("\0ALTER TABLE ").Append(TableName)
                        .Append(" ALTER COLUMN ").Append(FieldName)
                        .Append(SqlServerType(MtFd));
                    }
                    else
                    {
                        strAddColumn.Append("\0ALTER TABLE ").Append(TableName)
                        .Append(" ALTER COLUMN ").Append(FieldName)
                        .Append(SqlServerType(MtFd))
                        .Append(" NOT NULL");
                    }
                }
            }
            #endregion

            #region Check Inserted Fields
            foreach (FieldDef MtFd in MetaTd.KeyFields.Values)
            {
                FieldDef dbFd;
                if (!dbTd.KeyFields.TryGetValue(MtFd.FieldName, out dbFd))
                {
                    if (!dbTd.NonKeyFields.TryGetValue(MtFd.FieldName,
                                                       out dbFd))
                    {
                        strAddColumn.Append("\0ALTER TABLE ")
                        .Append(TableName).Append(" ADD ")
                        .Append(MtFd.FieldName)
                        .Append(SqlServerType(MtFd));
                        strAddColumn.Append("\0UPDATE ")
                        .Append(TableName)
                        .Append(" SET ").Append(MtFd.FieldName)
                        .Append("=").Append(FormatSqlValue(
                                                MtFd.GetDefaultValue(), MtFd.DataType));

                        strAddColumn.Append("\0ALTER TABLE ")
                        .Append(TableName).Append(" ALTER COLUMN ")
                        .Append(MtFd.FieldName)
                        .Append(SqlServerType(MtFd))
                        .Append(" NOT NULL");
                    }
                    PKChanged = true;
                }
            }
            foreach (FieldDef MtFd in MetaTd.NonKeyFields.Values)
            {
                if (MtFd.GetDTLSA() != null)
                {
                    continue;
                }
                FieldDef dbFd;
                if (!dbTd.NonKeyFields.TryGetValue(MtFd.FieldName, out dbFd))
                {
                    if (!dbTd.KeyFields.TryGetValue(MtFd.FieldName, out dbFd))
                    {
                        strAddColumn.Append("\0ALTER TABLE ")
                        .Append(TableName).Append(" ADD ")
                        .Append(MtFd.FieldName)
                        .Append(SqlServerType(MtFd));

                        if (MtFd.DataType != DataType.Image &&
                            MtFd.DataType != DataType.Binary)
                        {
                            strAddColumn.Append("\0UPDATE ")
                            .Append(TableName).Append(" SET ")
                            .Append(MtFd.FieldName).Append("=")
                            .Append(FormatSqlValue(
                                        MtFd.GetDefaultValue(), MtFd.DataType));

                            strAddColumn.Append("\0ALTER TABLE ")
                            .Append(TableName)
                            .Append(" ALTER COLUMN ")
                            .Append(MtFd.FieldName)
                            .Append(SqlServerType(MtFd))
                            .Append(" NOT NULL");
                        }
                    }
                    else
                    {
                        PKChanged = true;
                    }
                }
            }
            #endregion

            if (PKChanged)
            {
                strDropIndex.Append("\0ALTER TABLE ").Append(TableName)
                .Append(" DROP CONSTRAINT PK_")
                .Append(TableName);
                if (MetaTd.KeyFields.Count > 0)
                {
                    strAddIndex.Append("\0ALTER TABLE ").Append(TableName)
                    .Append(" ADD CONSTRAINT PK_").Append(TableName)
                    .Append(" PRIMARY KEY(");
                    foreach (FieldDef fld in MetaTd.KeyFields.Values)
                    {
                        strAddIndex.Append(fld.FieldName).Append(",");
                    }
                    strAddIndex.Remove(strAddIndex.Length - 1, 1).Append(")");
                }
            }
            #endregion

            if (strDropColumn.Length > 0)
            {
                strDropIndex.Append(strDropColumn.ToString());
            }
            if (strAddColumn.Length > 0)
            {
                strDropIndex.Append(strAddColumn.ToString());
            }
            if (strAddIndex.Length > 0)
            {
                strDropIndex.Append(strAddIndex.ToString());
            }
            if (strDropIndex.Length > 0)
            {
                strDropIndex.Remove(0, 1);
            }
            return(strDropIndex.ToString());
        }
示例#24
0
        public static BaseEntity Clone(BaseEntity SourceObj)
        {
            TableDef       td      = GetTableDef(SourceObj.GetType());
            BusinessEntity DestObj = (BusinessEntity)BaseFactory
                                     .CreateInstance(td._ClassType);
            IRuleInitUI px = DestObj as IRuleInitUI;

            //CallLoadRule = CallLoadRule && px != null;

            DestObj.EntityOnLoad = true;
            try
            {
                foreach (FieldDef fd in td.KeyFields.Values)
                {
                    fd.SetLoadValue(DestObj, fd.GetValue(SourceObj));
                }
                foreach (FieldDef fd in td.NonKeyFields.Values)
                {
                    fd.SetLoadValue(DestObj, fd.GetValue(SourceObj));
                }

                if (td.ChildEntities.Count > 0)
                {
                    foreach (EntityCollDef ecd in td.ChildEntities)
                    {
                        IList SrcCols  = ecd.GetValue(SourceObj);
                        IList DestCols = ecd.GetValue(DestObj);
                        int   NumDest  = DestCols.Count;
                        ((IEntityCollection)DestCols).OnLoad = true;
                        int i = 0;
                        foreach (BaseEntity obj in SrcCols)
                        {
                            if (i < NumDest)
                            {
                                Clone((BaseEntity)DestCols[i++], obj);
                            }
                            else
                            {
                                DestCols.Add(Clone(obj));
                            }
                        }
                        ((IEntityCollection)DestCols).OnLoad = false;
                    }
                }

                //if (CallLoadRule)
                //{
                //px.AfterLoadFound();
                //BaseFramework.DoEntityAction(DestObj, enEntityActionMode.AfterLoadFound);
                //}
                BusinessEntity be = DestObj as BusinessEntity;
                if (be != null)
                {
                    be.AfterClone((BusinessEntity)SourceObj);
                }
            }
            finally
            {
                DestObj.EntityOnLoad = false;
                DestObj.DataChanged();
            }
            return(DestObj);
        }
示例#25
0
        /// <summary>
        /// 修改数据库表
        /// </summary>
        /// <param name="tableDef"></param>
        /// <returns></returns>
        public override bool modifyTable(TableDef tableDef)
        {
            bool          bRet = false;
            TableDef      oldTbDef;
            StringBuilder strConstrains = new StringBuilder(); //约束

            string attachStr = "";                             //约束信息
            //字段说明
            string noteStr = "";

            string tmpStr = "";


            DbCommand cmd;
            string    strSql = "";

            try
            {
                if (tableDef != null)
                {
                    if (isExistObject(tableDef.Name, "Tb"))
                    {
                        oldTbDef = getTableDef(tableDef.Name);
                        for (int i = 0; i < tableDef.FieldDefs.Count; i++)
                        {
                            if (tableDef.FieldDefs[i].Name != "")
                            {
                                for (int j = 0; j < oldTbDef.FieldDefs.Count; j++)
                                {
                                    //字段说明
                                    if (!string.IsNullOrEmpty(tableDef.FieldDefs[i].Alias))
                                    {
                                        noteStr = " comment  '" + tableDef.FieldDefs[i].Alias + "' ";
                                    }

                                    //修改列
                                    if (tableDef.FieldDefs[i].Name == oldTbDef.FieldDefs[j].Name)
                                    {
                                        attachStr = "";
                                        if (tableDef.FieldDefs[i].Type == "decimal")
                                        {
                                            tmpStr = tableDef.FieldDefs[i].Name + " " + tableDef.FieldDefs[i].Type + "(" + tableDef.FieldDefs[i].Length + "," + tableDef.FieldDefs[i].Procesion + ")";
                                        }
                                        else if (tableDef.FieldDefs[i].Length > 0 && tableDef.FieldDefs[i].Type.ToLower() != "int" && tableDef.FieldDefs[i].Type.ToLower() != "blob" && tableDef.FieldDefs[i].Type.ToLower() != "enum" && tableDef.FieldDefs[i].Type.ToLower() != "datetime" && tableDef.FieldDefs[i].Type.ToLower() != "date" && tableDef.FieldDefs[i].Type.ToLower() != "time" && tableDef.FieldDefs[i].Type.ToLower() != "text")
                                        {
                                            tmpStr = tableDef.FieldDefs[i].Name + " " + tableDef.FieldDefs[i].Type + "(" + tableDef.FieldDefs[i].Length + ")";
                                        }
                                        else
                                        {
                                            tmpStr = tableDef.FieldDefs[i].Name + " " + tableDef.FieldDefs[i].Type;
                                        }

                                        if (tableDef.FieldDefs[i].NotNull != oldTbDef.FieldDefs[j].NotNull)
                                        {
                                            if (!tableDef.FieldDefs[i].NotNull)
                                            {
                                                attachStr += "  not null ";
                                            }
                                            else
                                            {
                                                attachStr += "  null ";
                                            }
                                        }

                                        if (tableDef.FieldDefs[i].IsPriKey)
                                        {
                                            attachStr += "  not null ";
                                        }

                                        if (tableDef.FieldDefs[i].IsIdentity)
                                        {
                                            attachStr += "  auto_increment ";
                                            tableDef.FieldDefs[i].IsGuid = true;
                                        }

                                        if (tableDef.FieldDefs[i].IsGuid)
                                        {
                                            attachStr += "  unique ";
                                        }
                                        if (!string.IsNullOrEmpty(tableDef.FieldDefs[i].DefaultValue))
                                        {
                                            attachStr += "  default " + tableDef.FieldDefs[i].DefaultValue + "  ";
                                        }


                                        tmpStr += attachStr;
                                        tmpStr += " " + noteStr + " ";


                                        if (!string.IsNullOrEmpty(tableDef.FieldDefs[i].DefaultValue))
                                        {
                                            setDefaultContraint(tableDef.Name, tableDef.FieldDefs[i].Name, tmpStr);
                                        }
                                        else
                                        {
                                            try
                                            {
                                                strSql = "alter  table " + tableDef.Name + "  modify column " + tmpStr + " ";
                                                cmd    = database.GetSqlStringCommand(strSql);
                                                database.ExecuteNonQuery(cmd);
                                                if (!string.IsNullOrEmpty(tableDef.FieldDefs[i].Constrains))
                                                {
                                                    strConstrains.Append(tableDef.FieldDefs[i].Constrains);
                                                    strConstrains.Append(";");
                                                }
                                            }
                                            catch (System.Exception ex)
                                            {
                                                throw ex;
                                            }
                                        }


                                        oldTbDef.FieldDefs.Remove(oldTbDef.FieldDefs[j]);
                                        tableDef.FieldDefs.Remove(tableDef.FieldDefs[i]);

                                        j--;
                                        i--;

                                        break;
                                    }
                                }
                            }
                        }


                        //添加列
                        foreach (FieldDef fd in tableDef.FieldDefs)
                        {
                            tmpStr    = "";
                            attachStr = "";
                            noteStr   = "";

                            //字段说明
                            if (!string.IsNullOrEmpty(fd.Alias))
                            {
                                noteStr = " comment  '" + fd.Alias + "' ";
                            }

                            if (!string.IsNullOrEmpty(fd.Constrains))
                            {
                                strConstrains.Append(fd.Constrains);
                                strConstrains.Append(";");
                            }
                            if (!string.IsNullOrEmpty(fd.DefaultValue))
                            {
                                attachStr += "  default " + fd.DefaultValue + " ";
                            }

                            if (fd.Type.ToLower() == "decimal")
                            {
                                tmpStr = fd.Name + " " + fd.Type.ToLower() + "(" + fd.Length + "," + fd.Procesion + ")";
                            }
                            else if (fd.Length > 0)
                            {
                                tmpStr = fd.Name + " " + fd.Type.ToLower() + "(" + fd.Length + ")";
                            }
                            else
                            {
                                tmpStr = fd.Name + " " + fd.Type.ToLower();
                            }

                            if (!fd.NotNull)
                            {
                                attachStr += "  not null ";
                            }
                            else if (fd.IsPriKey)
                            {
                                attachStr += "  not null ";
                            }

                            if (fd.IsIdentity)
                            {
                                attachStr += "  auto_increment ";
                                fd.IsGuid  = true;
                            }

                            if (fd.IsGuid)
                            {
                                attachStr += "  unique ";
                            }


                            if (fd.Type.ToLower() == "decimal" || fd.Type.ToLower() == "float")
                            {
                                tmpStr = fd.Name + " " + fd.Type.ToLower() + "(" + fd.Length + "," + fd.Procesion + ")";
                            }
                            else if (fd.Length > 0 && fd.Type.ToLower() != "int" && fd.Type.ToLower() != "blob" && fd.Type.ToLower() != "enum" && fd.Type.ToLower() != "datetime" && fd.Type.ToLower() != "date" && fd.Type.ToLower() != "time" && fd.Type.ToLower() != "text")
                            {
                                tmpStr = fd.Name + " " + fd.Type.ToLower() + "(" + fd.Length + ")";
                            }
                            else
                            {
                                tmpStr = fd.Name + " " + fd.Type.ToLower();
                            }
                            tmpStr += attachStr;
                            tmpStr += noteStr;

                            strSql = "alter table " + tableDef.Name + " add  " + tmpStr + "";
                            cmd    = database.GetSqlStringCommand(strSql);
                            database.ExecuteNonQuery(cmd);
                        }

                        //删除列
                        foreach (FieldDef fd1 in oldTbDef.FieldDefs)
                        {
                            strSql = "alter  table " + tableDef.Name + " DROP COLUMN " + fd1.Name + "";
                            cmd    = database.GetSqlStringCommand(strSql);
                            database.ExecuteNonQuery(cmd);
                        }


                        if (!string.IsNullOrEmpty(strConstrains.ToString()))
                        {
                            cmd = database.GetSqlStringCommand(strConstrains.ToString());
                            database.ExecuteNonQuery(cmd);
                        }

                        //表主键
                        string strKeyName = "";
                        string strKeySql  = "";
                        foreach (FieldDef field in tableDef.MainKeys)
                        {
                            if (field.Name != "")
                            {
                                strKeyName += field.Name + ",";
                            }
                        }
                        strKeyName = strKeyName.TrimEnd(',');
                        if (strKeyName != "")
                        {
                            try
                            {
                                strKeySql = "ALTER TABLE " + tableDef.Name + " drop primary key";
                                cmd       = database.GetSqlStringCommand(strKeySql.ToUpper());
                                database.ExecuteNonQuery(cmd);
                            }
                            catch
                            {
                            }

                            strKeySql = "ALTER TABLE " + tableDef.Name + " ADD CONSTRAINT PK_" + tableDef.Name + " PRIMARY KEY  ( " + strKeyName + ")";
                            cmd       = database.GetSqlStringCommand(strKeySql.ToUpper());
                            database.ExecuteNonQuery(cmd);
                        }

                        bRet = true;
                    }
                    else
                    {
                        bRet = createTable(tableDef);
                    }
                }
                else
                {
                    bRet = false;
                }
            }
            catch (System.Exception ex)
            {
                throw ex;
            }

            return(bRet);
        }
示例#26
0
        public static void Clone(BaseEntity DestObj,
                                 BaseEntity SourceObj)
        {
            if (DestObj == null)
            {
                throw new ApplicationException("DestObj tidak boleh null");
            }
            TableDef td = GetTableDef(SourceObj.GetType());

            //IRuleInitUI px = DestObj as IRuleInitUI;
            //CallLoadRule = CallLoadRule && px != null;

            DestObj.EntityOnLoad = true;
            try
            {
                foreach (FieldDef fd in td.KeyFields.Values)
                {
                    fd.SetLoadValue(DestObj, fd.GetValue(SourceObj));
                }
                foreach (FieldDef fd in td.NonKeyFields.Values)
                {
                    fd.SetLoadValue(DestObj, fd.GetValue(SourceObj));
                }

                if (td.ChildEntities.Count > 0)
                {
                    foreach (EntityCollDef ecd in td.ChildEntities)
                    {
                        IList SrcCols  = ecd.GetValue(SourceObj);
                        IList DestCols = ecd.GetValue(DestObj);
                        int   NumDest  = DestCols.Count;
                        ((IEntityCollection)DestCols).OnLoad = true;

                        int i = 0;
                        while (DestCols.Count > SrcCols.Count)
                        {
                            DestCols.RemoveAt(0);
                        }
                        foreach (BaseEntity obj in SrcCols)
                        {
                            if (i < NumDest)
                            {
                                Clone((BaseEntity)DestCols[i++], obj);
                            }
                            else
                            {
                                DestCols.Add(Clone(obj));
                            }
                        }
                        ((IEntityCollection)DestCols).OnLoad = false;
                    }
                }
                //if (CallLoadRule)
                //{
                //    px.AfterLoadFound();
                //    BaseFramework.DoEntityAction(DestObj, enEntityActionMode.AfterLoadFound);
                //}
                BusinessEntity be = DestObj as BusinessEntity;
                if (be != null)
                {
                    be.AfterClone((BusinessEntity)SourceObj);
                }
            }
            finally
            {
                DestObj.EntityOnLoad = false;
                DestObj.DataChanged();
            }
        }
示例#27
0
        private void btnCreateTables_Click(object sender, EventArgs e)
        {
            TableDef     mytdef = null;
            Field        myfield = null, indexfield;
            Index        myInd = null;
            int          j     = 0;
            List <Field> flist = new List <Field>();

            try
            {
                // Delete all the tables from DB to avoid Table's conflicts
                //DeleteAllTables(mydb);

                foreach (TabPage tbtemp in tabcontFields.TabPages)
                {
                    // check if Table exist in DB
                    if (tableExist(mydb, tbtemp.Text) == false)
                    {
                        ////////////////////////////
                        // Table and Fields Creation
                        ////////////////////////////

                        mytdef = mydb.CreateTableDef(tbtemp.Text);

                        for (int i = 0; i < dgridList[j].RowCount - 1; i++)
                        {
                            myfield = mytdef.CreateField(dgridList[j].Rows[i].Cells["colField"].Value, (DataTypeEnum)Enum.Parse(typeof(DataTypeEnum), dgridList[j].Rows[i].Cells["colDataType"].Value.ToString()));

                            if (i == 0)
                            {
                                // Add autoincrement attribute to first field "ID"
                                myfield.Attributes = (Int32)DAO.FieldAttributeEnum.dbAutoIncrField;
                            }

                            // Add Field to TableDef
                            mytdef.Fields.Append(myfield);
                            flist.Add(myfield);
                        }

                        /////////////////////////////////////
                        ////Create an Index and Primary Key
                        /////////////////////////////////////
                        myInd         = mytdef.CreateIndex(dgridList[j].Rows[0].Cells["colField"].Value.ToString());
                        myInd.Primary = true;

                        //////////////////////////////////
                        // Add field ID to index as ass Primary Key by default
                        //Creation of indexed fields
                        indexfield = myInd.CreateField(dgridList[j].Rows[0].Cells["colField"].Value);
                        //Add field in index
                        ((IndexFields)(myInd.Fields)).Append(indexfield);

                        // Creation of associated PK and indexes defined by the user
                        for (int i = 1; i < dgridList[j].RowCount - 1; i++)
                        {
                            // Verify if PK check Box is checked to create an index and Primary Key
                            if ((string)(dgridList[j].Rows[i].Cells["Key"]).Value == "true")
                            {
                                //Creation of indexed fields
                                indexfield = myInd.CreateField(dgridList[j].Rows[i].Cells["colField"].Value);

                                //Add field in index
                                ((IndexFields)(myInd.Fields)).Append(indexfield);
                            }
                        }
                        //Add index in the table
                        mytdef.Indexes.Append(myInd);

                        //Add table into DB
                        mydb.TableDefs.Append(mytdef);


                        // Add the Field's description to each field adding a new property to each cell
                        Property prt = null;
                        int      rindex;
                        rindex = 0;
                        foreach (Field ftemp in flist)
                        {
                            if (dgridList[j].Rows[rindex].Cells["colDescription"].Value != null)
                            {
                                //Cretion of new porperty called Description in each Cell
                                prt = ftemp.CreateProperty("Description", DataTypeEnum.dbText, dgridList[j].Rows[rindex].Cells["colDescription"].Value);
                                ftemp.Properties.Append(prt);
                            }
                            rindex++;
                        }

                        flist.Clear();
                        j++;
                    }
                    else
                    {
                        j++;
                    }
                }
                MessageBox.Show("Tables have been Created in DB " + mydb.Name, "Tables Created", MessageBoxButtons.OK, MessageBoxIcon.Information);
                btnGoRelations.Show();
            }
            catch (NullReferenceException)
            {
                MessageBox.Show("All fields must have a Data type selected in the table " + mytdef.Name, "Required Fields", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (System.Runtime.InteropServices.COMException daoErr)
            {
                if (daoErr.ErrorCode == FieldExistErrorCode) // Field exist Error Code
                {
                    MessageBox.Show("There are repeated fields in table " + mytdef.Name + "\nField's name must be unique", "Repeated Field", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                if (daoErr.ErrorCode == FieldUnamedErrorCode) // Field unamed Error Code
                {
                    MessageBox.Show("All Fields must have a name in table " + mytdef.Name, "Unnamed Field", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else // Other Errors related to Interpot Services
                {
                    MessageBox.Show(daoErr.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)  // General Exceptions
            {
                MessageBox.Show(ex.ToString(), "Table Creation Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
示例#28
0
        //Чтение списка расчетных параметров
        private void ReadCalcParams()
        {
            CalcParamsCode.Clear();
            CalcParamsId.Clear();
            CalcSubParamsId.Clear();
            Grafics.Clear();
            AddEvent("Загрузка графиков");
            using (var db = new DaoDb(File))
            {
                try
                {
                    const string stSql =
                        "SELECT GraficsList.Code, GraficsList.Dimension, GraficsList.GraficType, GraficsValues.X1, GraficsValues.X2, GraficsValues.X3, GraficsValues.X4, GraficsValues.X5, GraficsValues.X6, GraficsValues.X7, GraficsValues.X8 " +
                        "FROM GraficsList INNER JOIN GraficsValues ON GraficsList.GraficId = GraficsValues.GraficId " +
                        "ORDER BY GraficsList.Code, GraficsValues.X8, GraficsValues.X7, GraficsValues.X6, GraficsValues.X5, GraficsValues.X4, GraficsValues.X3, GraficsValues.X2, GraficsValues.X1;";
                    using (var recg = new ReaderAdo(db, stSql))
                    {
                        //Считывание графиков
                        recg.Read();
                        while (!recg.EOF)
                        {
                            var gr = new Grafic(recg, ThreadCalc);
                            Grafics.Add(gr.Code, gr);
                        }
                    }
                }
                catch (Exception ex)
                {
                    AddError("Ошибка загрузки графика", ex);
                }
                Procent = 10;

                AddEvent("Загрузка параметров");
                try
                {
                    const string stSql = "SELECT * FROM CalcParams WHERE (TaskOn = True) AND (CalcOn = True)";
                    using (var rec = new ReaderAdo(db, stSql))
                        while (rec.Read())
                        {
                            var calc = new CalcParam(this, rec, false);
                            calc.FullCode = calc.Code;
                            CalcParamsId.Add(calc.Id, calc);
                            CalcParamsCode.Add(calc.Code, calc);
                            if (IsError)
                            {
                                return;
                            }
                        }
                }
                catch (Exception ex)
                {
                    AddError("Список расчетных параметров загружен с ошибками, необходима повторная компиляция расчета", ex);
                }
                Procent = 40;

                AddEvent("Загрузка подпараметров");
                try
                {
                    const string stSql =
                        "SELECT CalcSubParams.* FROM CalcParams INNER JOIN CalcSubParams ON CalcParams.CalcParamId = CalcSubParams.OwnerId" +
                        " WHERE (CalcParams.TaskOn=True) AND (CalcParams.CalcOn=True) AND (CalcSubParams.CalcOn=True)";
                    using (var recp = new ReaderAdo(db, stSql))
                        while (recp.Read())
                        {
                            var calc = new CalcParam(this, recp, true);
                            CalcSubParamsId.Add(calc.Id, calc);
                            calc.Owner = CalcParamsId[recp.GetInt("OwnerId")];
                            calc.Owner.Methods.Add(calc.Code, calc);
                            calc.FullCode = calc.Owner.FullCode + "." + calc.Code;
                            if (IsError)
                            {
                                return;
                            }
                        }
                }
                catch (Exception ex)
                {
                    AddError("Список расчетных параметров загружен с ошибками, необходима повторная компиляция расчета", ex);
                }
                Procent = 60;
            }

            AddEvent("Загрузка справочных таблиц");
            Tabls.Clear();
            using (var db = new DaoDb(File).ConnectDao())
                foreach (TableDef t in db.Database.TableDefs)
                {
                    if (t.Name.StartsWith("Tabl_"))
                    {
                        var tabl = new Tabl(int.Parse(t.Name.Substring(5)));
                        Tabls.Add(tabl.Num, tabl);
                        tabl.FieldsCount = 0;
                        foreach (Field f in t.Fields)
                        {
                            if (f.Name.StartsWith("Val_"))
                            {
                                int fnum = int.Parse(f.Name.Substring(4));
                                if (fnum >= tabl.FieldsCount)
                                {
                                    tabl.FieldsCount = fnum + 1;
                                }
                            }
                        }
                        TableDef st = db.Database.TableDefs["Sub" + t.Name];
                        tabl.SubFieldsCount = 0;
                        foreach (Field f in st.Fields)
                        {
                            if (f.Name.StartsWith("SubVal_"))
                            {
                                int fnum = int.Parse(f.Name.Substring(7));
                                if (fnum >= tabl.SubFieldsCount)
                                {
                                    tabl.SubFieldsCount = fnum + 1;
                                }
                            }
                        }
                    }
                }

            if (Tabls.Count > 0)
            {
                using (var db = new DaoDb(File))
                    foreach (var t in Tabls.Values)
                    {
                        using (var rect = new ReaderAdo(db, "SELECT * FROM Tabl_" + t.Num))
                            while (rect.Read())
                            {
                                new TablParam().ParamFromRec(t, rect);
                            }
                        using (var rect = new ReaderAdo(db, "SELECT * FROM SubTabl_" + t.Num))
                            while (rect.Read())
                            {
                                new TablParam().SubParamFromRec(t, rect);
                            }
                    }
            }
            Procent = 75;

            AddEvent("Разбор выражений");
            try
            {
                foreach (var cp in CalcParamsId.Values)
                {
                    if (!Start(cp.Parse))
                    {
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                ThreadCalc.AddError("Список расчетных параметров загружен с ошибками, необходима повторная компиляция расчета", ex);
            }
        }
示例#29
0
        /// <summary>
        /// 返回当前表
        /// </summary>
        /// <param name="tableName"></param>
        /// <returns></returns>
        public TableDef getTableDef(string tableName)
        {
            TableDef ret = new TableDef();

            ret.Name        = tableName;
            ret.OldName     = tableName;
            ret.Description = getTableDescription(tableName);
            ret.Title       = getTableTitle(tableName);
            DataTable tb = getFieldDefsToTable(tableName);

            if (tb.Rows == null || tb.Rows.Count == 0)
            {
                return(null);
            }

            if (tb == null || tb.Rows.Count < 1)
            {
                ret.FieldDefs = new List <FieldDef>()
                {
                    new FieldDef()
                };
                return(ret);
            }

            foreach (DataRow row in tb.Rows)
            {
                FieldDef fldDef = new FieldDef();

                fldDef.Name    = row["colName"].ToString();
                fldDef.Type    = row["colType"].ToString();
                fldDef.OldName = fldDef.Name;
                if (!string.IsNullOrEmpty(row["colLength"].ToString()))
                {
                    fldDef.Length = int.Parse(row["colLength"].ToString());
                }
                else
                {
                    fldDef.Length = 0;
                }

                if (!string.IsNullOrEmpty(row["growMark"].ToString()))
                {
                    fldDef.IsIdentity = bool.Parse(row["growMark"].ToString());
                }
                else
                {
                    fldDef.IsIdentity = false;
                }

                if (!string.IsNullOrEmpty(row["pointCount"].ToString()))
                {
                    fldDef.Procesion = int.Parse(row["pointCount"].ToString());
                }



                if (!string.IsNullOrEmpty(row["colVal"].ToString()))
                {
                    fldDef.DefaultValue = row["colVal"].ToString();
                }


                if (!string.IsNullOrEmpty(row["colNote"].ToString()))
                {
                    fldDef.Description = row["colNote"].ToString();
                }

                if (!string.IsNullOrEmpty(row["title"].ToString()))
                {
                    fldDef.Title = row["title"].ToString();
                }

                if (!string.IsNullOrEmpty(row["alias"].ToString()))
                {
                    fldDef.Alias = row["alias"].ToString();
                }


                if (!string.IsNullOrEmpty(row["colIsUnique"].ToString()))
                {
                    fldDef.IsUnique = bool.Parse(row["colIsUnique"].ToString());
                }
                else
                {
                    fldDef.IsUnique = false;
                }

                if (!string.IsNullOrEmpty(row["colIsNull"].ToString()))
                {
                    fldDef.NotNull = !bool.Parse(row["colIsNull"].ToString());
                }
                else
                {
                    fldDef.NotNull = false;
                }

                if (!string.IsNullOrEmpty(row["pkName"].ToString()))
                {
                    fldDef.IsPriKey = bool.Parse(row["pkName"].ToString());
                }

                if (fldDef.IsPriKey)
                {
                    ret.MainKeys.Add(fldDef);
                }

                ret.FieldDefs.Add(fldDef);


                //if (!string.IsNullOrEmpty(row["pkName"].ToString()) && row["pkName"].ToString() == "True")
                //{
                //    ret.MainKeys.Add(fldDef);
                //    fldDef.IsPriKey = true;
                //}
                //else
                //{
                //    fldDef.IsPriKey = false;
                //}
            }
            return(ret);
        }
示例#30
0
        private void btnCreate_Click(object sender, EventArgs e) //triggers the creation of a new field
        {
            bool error = false;

            foreach (TableDef oneTable in clsDataStorage.db.TableDefs) //loops through the tabledefinitions
            {
                if (oneTable.Attributes == 0)
                {
                    foreach (Field abcd in oneTable.Fields)
                    {
                        if (abcd.Name == txtFieldName.Text) //check if table already contains a field with the same name
                        {
                            MetroMessageBox.Show(this, "This table already contains a field with the name " + abcd.Name + ".\nField names have to be unique!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            error = true;
                        }
                    }
                    if (cmbFieldProperty.Text == "Primary" || cmbFieldProperty.Text == "Unique") //check if table contains primary or unique elements
                    {
                        foreach (Index inx in oneTable.Indexes)
                        {
                            if (inx.Primary == true && !error)
                            {
                                MetroMessageBox.Show(this, "This table already contains a field with the property INDEX.\nA table can only contain one index.", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                error = true;
                                break;
                            }
                            if (inx.Unique == true && !error)
                            {
                                MetroMessageBox.Show(this, "This table already contains a field with the property UNIQUE.\nA table can only contain one UNIQUE.", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                error = true;
                                break;
                            }
                        }
                    }
                }
            }
            if (!error) //if no primary or unique, then create a new field
            {
                table = clsDataStorage.db.TableDefs[cmbListTable.Text];
                string name;
                name = txtFieldName.Text;
                int   size;
                Field field = new Field();
                //creates the field according to the type chosen by the user
                if (cmbFieldType.Text == "Long")
                {
                    size  = Convert.ToInt32(txtFieldSize.Text);
                    field = table.CreateField(name, DAO.DataTypeEnum.dbLong, size);
                    if (chkAuto.Checked)
                    {
                        field.Attributes = (int)DAO.FieldAttributeEnum.dbAutoIncrField;
                    }
                }

                else if (cmbFieldType.Text == "Double")
                {
                    size  = Convert.ToInt32(txtFieldSize.Text);
                    field = table.CreateField(name, DAO.DataTypeEnum.dbDouble, size);
                }

                else if (cmbFieldType.Text == "Text")
                {
                    size  = Convert.ToInt32(txtFieldSize.Text);
                    field = table.CreateField(name, DAO.DataTypeEnum.dbText, size);
                }
                else if (cmbFieldType.Text == "Currency")
                {
                    size  = Convert.ToInt32(txtFieldSize.Text);
                    field = table.CreateField(name, DAO.DataTypeEnum.dbCurrency, size);
                }
                else if (cmbFieldType.Text == "Boolean")
                {
                    size  = Convert.ToInt32(txtFieldSize.Text);
                    field = table.CreateField(name, DAO.DataTypeEnum.dbBoolean, size);
                }
                else
                {
                    field = table.CreateField(name, DAO.DataTypeEnum.dbDate);
                }

                table.Fields.Append(field);             //appends the field to the table

                if (cmbFieldProperty.Text == "Primary") //check if field is primary, then append the property
                {
                    Index index = table.CreateIndex("pk_" + name);
                    field             = index.CreateField(name);
                    index.Primary     = true;
                    index.Required    = true;
                    index.IgnoreNulls = false;
                    ((IndexFields)index.Fields).Append(field);
                    table.Indexes.Append(index);
                }

                else if (cmbFieldProperty.Text == "Unique") //check if field is unique, then append the property
                {
                    Index index = table.CreateIndex("unq_" + name);
                    field             = index.CreateField(name);
                    index.Required    = true;
                    index.Unique      = true;
                    index.IgnoreNulls = false;
                    ((IndexFields)index.Fields).Append(field);
                    table.Indexes.Append(index);
                }
                else if (cmbFieldProperty.Text == "Index") //check if field is index, then append the property
                {
                    Index index = table.CreateIndex("idx_" + name);
                    field             = index.CreateField(name);
                    index.Required    = true;
                    index.Unique      = true;
                    index.IgnoreNulls = false;
                    ((IndexFields)index.Fields).Append(field);
                    table.Indexes.Append(index);
                }
                MetroMessageBox.Show(this, "The new field was included successfully.", "New field", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.Close(); //after the field being added, closes the form
            }
        }
        private void readResponse(List <object[]> rstObjects, DataRequest dataRequest, List <int> tagsPos, TableDef tabledef)
        {
            int           rstPos = 0, buffPos = 0;
            List <double> vals_agreg = new List <double>();
            long          time, startTime, endTime, low_buff_time, high_buff_time;

            startTime = dataRequest.beginTime;
            endTime   = dataRequest.beginTime + dataRequest.timeAxisLength;

            for (int i = 1; i < rstObjects[0].Length; i++)
            {
                double[] vals_buffer = new double[(dataRequest.timeAxisLength) / dataRequest.tags[tagsPos[i - 1]].period]; //prepare values buffer
                for (int j = 0; j < rstObjects.Count; j++)
                {
                    object[] objectsArray = rstObjects[j];
                    low_buff_time  = (startTime + (rstPos * dataRequest.tags[tagsPos[i - 1]].period));
                    high_buff_time = (startTime + ((rstPos + 1) * dataRequest.tags[tagsPos[i - 1]].period));
                    time           = utcToPkTime(objectsArray[0].ToString());
                    if (low_buff_time <= time && high_buff_time >= time)
                    {
                        vals_agreg.Add(Convert.ToDouble(objectsArray[i]));
                        if ((time + dataRequest.tags[tagsPos[i - 1]].period) >= high_buff_time)
                        {
                            if (vals_agreg.Count != 0)
                            {
                                vals_agreg.Reverse();
                                vals_buffer[buffPos] = vals_agreg[0];
                                buffPos++;
                                vals_agreg.Clear();
                            }
                            else
                            {
                                if (buffPos < vals_buffer.Length)
                                {
                                    vals_buffer[buffPos] = double.NaN;
                                    buffPos++;
                                }
                            }
                        }
                        rstPos++;
                    }
                    else
                    {
                        if (low_buff_time > time && time > startTime)
                        {
                            rstPos--;
                        }
                        if (high_buff_time < time)
                        {
                            if (vals_agreg.Count != 0)
                            {
                                vals_agreg.Reverse();
                                vals_buffer[buffPos] = vals_agreg[0];
                                buffPos++;
                                vals_agreg.Clear();
                            }
                            else
                            {
                                if (buffPos < vals_buffer.Length)
                                {
                                    vals_buffer[buffPos] = double.NaN;
                                    buffPos++;
                                    rstPos++;
                                }
                            }
                        }
                    }
                }
                buffPos = 0;
                // dataRequest.tags[tagsPos[i-1]].vals = vals_buffer;
            }
        }
示例#32
0
        public bool IsExists(Type EntityType, string Conditions,
                             params FieldParam[] Parameters)
        {
            TableDef        td = MetaData.GetTableDef(EntityType);
            DataPersistance Dp = td.GetDataPersistance(this.Dp);

            Dp.ValidateTableDef(td);

            string FieldName = string.Empty;

            foreach (FieldDef fd in td.KeyFields.Values)
            {
                FieldName = fd._FieldName;
                break;
            }

            string SqlSelectBld = string.Empty;

            foreach (FieldDef fd in td.NonKeyFields.Values)
            {
                if (fd._dtlsa == null)
                {
                    if (FieldName.Length == 0)
                    {
                        FieldName = fd._FieldName;
                    }
                }
                else
                {
                    SqlSelectBld = string.Concat(SqlSelectBld, ",(",
                                                 fd._dtlsa.GetSqlQuery(), ") AS ", fd._FieldName);
                }
            }

            string SqlSelect = SqlSelectBld.Length == 0 ? string.Concat("SELECT ",
                                                                        FieldName, " FROM ", td.GetSqlHeaderView(Dp)) : string.Concat(
                "SELECT ", FieldName, " FROM (SELECT *", SqlSelectBld, " FROM ",
                td.GetSqlHeaderView(Dp), ") AS ", td._TableName);

            if (Conditions.Length > 0)
            {
                SqlSelect = string.Concat(SqlSelect, " WHERE ", Conditions);
            }
            SqlSelect = Dp.GetSqlSelectTopN(SqlSelect, 1, string.Empty);
            IDbCommand Cmd = Dp.CreateCommand(SqlSelect, CommandType.Text,
                                              Parameters);

            bool MustClose;

            if (Dp.Connection.State != ConnectionState.Open)
            {
                Dp.Connection.Open();
                MustClose = true;
            }
            else
            {
                MustClose = false;
            }

            IDataReader rdr = null;

            try
            {
                Dp.WriteLog(Cmd.CommandText);
                rdr = Dp._ExecuteReader(Cmd);
                return(rdr.Read());
            }
            finally
            {
                if (rdr != null)
                {
                    rdr.Close();
                }
                if (MustClose)
                {
                    Dp.Connection.Close();
                }
            }
        }
示例#33
0
        public void Copy(string provider1, string server1, string catalog1, string login1, string cred1, string provider2, string server2, string catalog2, string login2, string cred2, string table_cue_after, string single_table, bool no_utc)
        {
            string bintablename = new doc02Binary().TableName.ToLower();
            /* 0. define exclusions */
            var exclusions = new List <string>()
            {
                new sys02Installation().TableName,
                new doc02FT().TableName, /* [dlatikay 20110920] now the table name will resolve properly, was before: "doc02FT"; -!- until better solution, currently not included in schema! */
                new doc02Binary().TableName,
                new doc02BinaryL().TableName,
                new log02OrgSync().TableName,
                new log02OrgSyncItem().TableName,
                new msg02EventA().TableName,
                new nav02PickupStorage().TableName, /* it fails with a strange error in the RAW field (SessionID). we just omit it as it is transient and therefore not needed in systemcopy anyway */
                new nav02Menu().TableName,          /* [dlatikay 20101012] added */
                new nav02MenuL().TableName,         /* [dlatikay 20101012] added */
                new nav02MenuLocation().TableName,  /* [dlatikay 20151002] added */
                new nav02MenuLocationL().TableName, /* [dlatikay 20151002] added */
                new per02TaskA().TableName,
                new rpt02Link().TableName,
                new rpt02LinkL().TableName,
                new rpt02Destination().TableName, /* [dlatikay 20101012] added */
                new sys02Computer().TableName,
                new sys02GroupAccount().TableName,
                new sys02JobA().TableName,
                new sys02Useraccount().TableName,
                new tpi02CredentialStore().TableName,
                new tpi02FunclocImp().TableName,
                new tpi02HRImpAcceptor().TableName
            };

            /* except the single table from the exception */
            if (!String.IsNullOrWhiteSpace(single_table))
            {
                string exex = exclusions.Find((x) => { return(x.ToLower().Equals(single_table.ToLower())); }); /* [dlatikay 20090824] for genuine case insensitivity */
                if (!String.IsNullOrWhiteSpace(exex))
                {
                    exclusions.Remove(exex);
                }
            }
            /* 1. open both connections */
            ddl db1 = new ddlfactory((DbProvider)Enum.Parse(typeof(DbProvider), provider1)).Generate;
            ddl db2 = new ddlfactory((DbProvider)Enum.Parse(typeof(DbProvider), provider2)).Generate;

            try
            {
                db1.Connect(server1, catalog1, login1, cred1, null, no_utc);
                db2.Connect(server2, catalog2, login2, cred2, null, no_utc);
                /* 2. enumerate the tables in source and target */
                List <string> tables1 = db1.ListAllTables();
                List <string> tables2 = db2.ListAllTables();

                /* 3. for each table in the source, attempt to truncate
                 * the table in the destination and re-fill it using bulk insert
                 * approach */
                /* 3a. for each table */
                bool     keep_skipping           = (table_cue_after != null && table_cue_after.Length > 0) || (single_table != null && single_table.Length > 0);
                bool     stop_after_single_table = false;
                Assembly assy = Assembly.GetExecutingAssembly();
                foreach (string table in tables1)
                {
                    string tablename = table.ToLower();
                    if (single_table == null || single_table.Length <= 0)
                    {
                        log(864, tablename); /* Transferring table \"{0}\"... */
                    }
                    if (keep_skipping)
                    {
                        if (table_cue_after != null && table_cue_after.Length > 0)
                        {
                            log(1173, table_cue_after); /* --> skipped, precedes continuation point "{0}" */
                            keep_skipping = tablename != table_cue_after.ToLower();
                        }
                        else if (single_table != null && single_table.Length > 0)
                        {
                            keep_skipping = (!single_table.ToLower().Equals(tablename));
                            if (!keep_skipping)
                            {
                                log(864, tablename); /* Transferring table \"{0}\"... */
                                stop_after_single_table = true;
                            }
                        }
                    }
                    /* take this one? */
                    if (!keep_skipping)
                    {
                        /* must not be in the exclusion list. if the single table is in the exclusion list, we excluded it from the exclusion list already :) */
                        if (!exclusions.Exists(delegate(string x) { return(x.ToLower().Equals(tablename)); }))
                        {
                            /* must exist in source and target (otherwise installations do not match in schema version probably) */
                            if (tables2.Exists(delegate(string x) { return(x.ToLower().Equals(tablename)); }))
                            {
                                //if (tablename.StartsWith(bintablename))
                                //    /* the "doc02Binary" table gets special treatment because it contains huge binary chunks. so does the doc02BinaryL. */
                                //    CopyBinRowwise(db1, db2, tablename);
                                //else
                                //{
                                /* got the singular, need the plural */
                                TableDef   element = (TableDef)assy.CreateInstance("dal.schema." + tablename, true);
                                string     plural  = db1.ObtainPlural(assy, tablename);
                                ITableList list    = (ITableList)assy.CreateInstance("dal.schema." + plural, true);
                                /* generic-dynamically invoke the dbselectall statement on the source */
                                GenericInvoker invoker = clsDynamicGenerics.GenericMethodInvokerMethod(
                                    element.GetType(),
                                    "DbSelectAll",
                                    new Type[] { list.GetType(), element.GetType() },
                                    new Type[] { typeof(ddl) }
                                    );
                                list = invoker(element, db1) as ITableList;
                                /* truncate the target */
                                element.DbTruncate(db2);
                                if (list.Rowcount > 0)
                                {
                                    log(1157, list.Rowcount.ToString()); /* --> number of records to be transferred: {0} */
                                    /* now for the dbinsertall statement on the target - who's able to fully understand this, must be drugged */
                                    try
                                    {
                                        element.InsertAllGeneric(db2, list);
                                    }
                                    catch (Exception ex)
                                    {
                                        throw new DALException(String.Format("Failed to copy table \"{0}\".", element.TableName), ex);
                                    }
                                    log(870, list.Rowcount.ToString()); /* --> number of records transferred: {0} */
                                }
                                else
                                {
                                    log(869); /* --> deletion only, no data in source table */
                                }
                            }
                            else
                            {
                                /* table does not exist in destination */
                                log(866); /* --> skipped because not existing in target database. */
                            }
                        }
                        else
                        {
                            /* table skipped because of exclusion rule */
                            log(865); /* --> skipped because in exclusion list. */
                        }
                    }
                    /* if we wanted only a single table we might now abort */
                    if (stop_after_single_table)
                    {
                        break;
                    }
                }
                /* succeeded */
            }
            finally
            {
                /* cleanup */
                if (db2 != null)
                {
                    db2.Disconnect();
                }
                if (db1 != null)
                {
                    db1.Disconnect();
                }
            }
        }
示例#34
0
        // Real Find
        public bool TryFindFirstValues <TEntity>(string FieldNames,
                                                 string Conditions, string OrderFields, out object[] Values,
                                                 params FieldParam[] Parameters)
            where TEntity : BaseEntity
        {
            TableDef        td = MetaData.GetTableDef(typeof(TEntity));
            DataPersistance Dp = td.GetDataPersistance(this.Dp);

            Dp.ValidateTableDef(td);
            string[] FName     = FieldNames.Split(',');
            string   SqlSelect = string.Empty;

            bool IsLSQLExist = false;

            for (int i = 0; i < FName.Length; i++)
            {
                FieldDef fld = td.GetFieldDef(FName[i]);
                if (fld != null)
                {
                    if (fld._dtlsa == null)
                    {
                        SqlSelect = string.Concat(SqlSelect, ",",
                                                  fld._FieldName);
                    }
                    else
                    {
                        SqlSelect = string.Concat(SqlSelect, ",(",
                                                  fld._dtlsa.GetSqlQuery(), ") AS ",
                                                  fld._FieldName);
                        IsLSQLExist = true;
                    }
                }
                else
                {
                    SqlSelect = string.Concat(SqlSelect, ",", FName[i].Trim());
                }
            }
            SqlSelect = string.Concat("SELECT ", SqlSelect.Remove(0, 1),
                                      " FROM ", td.GetSqlHeaderView(Dp));
            if (IsLSQLExist)
            {
                SqlSelect = string.Concat("SELECT * FROM (", SqlSelect, ") AS ", td._TableName);
            }
            if (Conditions.Length > 0)
            {
                SqlSelect = string.Concat(SqlSelect, " WHERE ", Conditions);
            }
            IDbCommand Cmd = Dp.CreateCommand(
                Dp.GetSqlSelectTopN(SqlSelect, 1, OrderFields),
                CommandType.Text, Parameters);

            bool MustClose;

            if (Dp.Connection.State != ConnectionState.Open)
            {
                Dp.Connection.Open();
                MustClose = true;
            }
            else
            {
                MustClose = false;
            }

            IDataReader rdr = null;

            try
            {
                Dp.WriteLog(Cmd.CommandText);
                rdr = Dp._ExecuteReader(Cmd);
                if (rdr.Read())
                {
                    Values = new object[rdr.FieldCount];
                    for (int i = 0; i < rdr.FieldCount; i++)
                    {
                        Values[i] = NormalizeVarType(rdr[i]);
                    }
                    return(true);
                }
                Values = null;
                return(false);
            }
            finally
            {
                if (rdr != null)
                {
                    rdr.Close();
                }
                if (MustClose)
                {
                    Dp.Connection.Close();
                }
            }
        }
示例#35
0
        public MdiForm()
        {
            using (new WaitCursor())
            {
                InitializeComponent();

                BaseWinFramework.ShowProgressBar(Text);

                BaseSecurity.LoginWithRole = false;

                BaseFramework.DpEngine
                .RegisterEngine <SqlServerPersistance>();
                BaseFramework.DpEngine
                .RegisterEngine <AccessPersistance>();

                //BaseFramework.EnableWriteLog = true;

                ribbonControl1.SelectedPage = ribbonPage4;

                BaseWinSecurity.Init(this, null, null,
                                     true, pgAksesSistem);

                BaseGL.SetingPerusahaan.OnEntityAction +=
                    new EntityAction(SetingPerusahaan_OnEntityAction);

                TableDef td  = MetaData.GetTableDef <Departemen>();
                FieldDef fld = td.GetFieldDef("DepartemenProduksi");
                fld.IsHidden = true;

                BaseWinSecurity.ListAdminButton.Add(mnPenguncianTgl);

                BaseWinSecurity.ListLoginButton.Add(mnNeraca);
                BaseWinSecurity.ListLoginButton.Add(mnLabaRugi);
                BaseWinSecurity.ListLoginButton.Add(mnMutasiAkun);
                BaseWinSecurity.ListLoginButton.Add(mnRingkasanAkun);

                string FolderName;

                #region Menu Keuangan
                FolderName = "Keuangan\\Transaksi";
                BaseWinSecurity.RegisterDocumentModule
                <DocPenerimaanKasUmum>(PenerimaanKasUmum.ModuleName,
                                       FolderName, mnPenerimaanKasUmum);
                BaseWinSecurity.RegisterDocumentModule
                <DocPengeluaranKasUmum>("Pengeluaran Kas Umum", FolderName,
                                        mnPengeluaranKasUmum);
                BaseWinSecurity.RegisterDocumentModule
                <DocTransferAntarKas>("Transfer Antar Kas", FolderName,
                                      mnTransferKas);
                BaseWinSecurity.RegisterDocumentModule
                <DocPerintahBayar>("Perintah Bayar", FolderName,
                                   mnPerintahBayar);
                BaseWinSecurity.RegisterDocumentModule
                <DocPengeluaranPerintahBayar>(
                    "Pengeluaran Uang dari Perintah Bayar", FolderName,
                    mnPengeluaranDariPerintahBayar);

                FolderName = "Keuangan\\Master";
                BaseWinSecurity.RegisterDocumentModule
                <DocJenisPenerimaanKas>("Jenis Penerimaan Kas", FolderName,
                                        mnJenisPenerimaanKas);
                BaseWinSecurity.RegisterDocumentModule
                <DocJenisPengeluaranKas>("Jenis Pengeluaran Kas", FolderName,
                                         mnJenisPengeluaranKas);
                #endregion

                #region Menu Buku Besar
                FolderName = "Buku Besar\\Transaksi";
                BaseWinSecurity.RegisterDocumentModule
                <DocJurnal>("Jurnal Umum", FolderName, mnJurnalUmum);
                BaseWinSecurity.RegisterDocumentModule
                <DocKursHarian>("Kurs Harian", FolderName, mnKursHarian);

                FolderName = "Buku Besar\\Laporan";
                BaseWinGL.RegisterPopNeraca(FolderName, mnNeraca);
                BaseWinGL.RegisterPopLabaRugi(FolderName, mnLabaRugi);
                BaseWinGL.RegisterPosisiAkun(FolderName, mnPosisiAkun);
                BaseWinGL.RegisterPopMutasiAkun(FolderName, mnMutasiAkun);
                BaseWinGL.RegisterPopRingkasanAkun(FolderName, mnRingkasanAkun);

                FolderName = "Buku Besar\\Master";
                BaseWinSecurity.RegisterDocumentModule
                <DocAkun>("Akun", FolderName, mnAkun);
                BaseWinSecurity.RegisterDocumentModule
                <DocAturanJurnal>("Aturan Jurnal", FolderName, mnAturanJurnal);
                BaseWinSecurity.RegisterDocumentModule
                <DocJenisDokSumberJurnal>("Jenis Dok. Sumber",
                                          FolderName, mnJenisDokSumberJurnal);
                BaseWinSecurity.RegisterDocumentModule
                <DocDepartemen>("Departemen", FolderName, mnDepartemen);
                BaseWinSecurity.RegisterDocumentModule
                <DocProyek>("Proyek", FolderName, mnProyek);
                BaseWinSecurity.RegisterDocumentModule
                <DocMataUang>("Mata Uang", FolderName, mnMataUang);

                BaseWinSecurity.RegisterDocumentModule
                <DocSaldoAwalAkun>("Saldo Awal Akun",
                                   "Sistem\\Saldo Awal", mnSaldoAwalAkun);
                BaseWinSecurity.RegisterDocumentModule
                <DocNilaiTukarSaldoAwal>("Nilai Tukar Saldo Awal",
                                         "Sistem\\Saldo Awal", mnNilaiTukarSaldoAwal);
                #endregion

                BaseWinSecurity.RegisterSingleDocumentModule <frmSetingPerusahaan>(
                    "Seting Perusahaan", "Sistem", mnSetingPerusahaan);
            }
        }
示例#36
0
        private void CreateField(TableDef tblName, String strFieldName, Boolean booAllowZeroLength, DataTypeEnum fieldType,
                                int lngAttributes, int intMaxLength, Object defaultValue)
        {
            Field tmpNewField = tblName.CreateField(strFieldName, fieldType, intMaxLength);

            if (fieldType == DataTypeEnum.dbText || fieldType == DataTypeEnum.dbMemo)
                tmpNewField.AllowZeroLength = booAllowZeroLength;

            tmpNewField.Attributes = lngAttributes;

            if (defaultValue != null)
                tmpNewField.DefaultValue = defaultValue;

            tblName.Fields.Append(tmpNewField);
        }