Esempio n. 1
0
        /// <summary>
        /// Updates the table's metadata as well as field's metadata
        /// </summary>
        protected override void Update()
        {
            bool hasDirtyFields = dirtyTableAttributes.Count() > 0 || base.dirtyRows.Count() > 0;
            // create meta fields
            bool hasNewMetaFields = InsertMetadataFields();

            // update: table metadata (!important, order matters)
            UpdateTableAttributes();
            // update: field metadata
            base.Update();
            // refresh metadata
            MetadataTable biz = new MetadataTable();

            biz.Get(tableId.Value);
            string tableName = biz[MetadataTable.TableName_Field].ToString();

            // when updating table attributes, refresh BO and cached items
            if (hasDirtyFields)
            {
                BOL.BusinessObject.RefreshMetadataFromDatabase(tableName);
                // updating table label causes PDE refresh ???
                if (dirtyTableAttributes.Contains(TableLabel.Field, StringComparer.OrdinalIgnoreCase))
                {
                    // CacheManager.RefreshPatientDataCache(QueryDiseaseName);
                }
            }

            // close modal, unless new meta fields added
            if (!hasNewMetaFields)
            {
                string updateScript = "if(top.reloadDataEntryFrame) { top.reloadDataEntryFrame(); top.hideModal(); }";
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OnUpdateScript", updateScript, true);
            }
        }
Esempio n. 2
0
        public RangedMemberCollection(TOwner owner, MetadataTable itemTable, int listColumnIndex, Func <TMember, TOwner> getOwner, Action <TMember, TOwner> setOwner)
            : base(owner, getOwner, setOwner)
        {
            if (itemTable == null)
            {
                throw new ArgumentNullException("itemTable");
            }
            if (getOwner == null)
            {
                throw new ArgumentNullException("getOwner");
            }
            if (setOwner == null)
            {
                throw new ArgumentNullException("setOwner");
            }

            _itemTable = itemTable;

            var ownerTable = owner.Image.Header.GetStream <TableStream>().GetTable(owner.MetadataToken.TokenType);
            var ownerRow   = ownerTable.GetRow((int)(owner.MetadataToken.Rid - 1));

            _start = Math.Min(Convert.ToInt32(ownerRow.GetAllColumns()[listColumnIndex]), _itemTable.Count + 1);

            if (owner.MetadataToken.Rid == ownerTable.Count)
            {
                _next = itemTable.Count + 1;
            }
            else
            {
                var nextRow = ownerTable.GetRow((int)owner.MetadataToken.Rid);
                _next = Math.Min(Convert.ToInt32(nextRow.GetAllColumns()[listColumnIndex]), _itemTable.Count + 1);
            }
        }
Esempio n. 3
0
 public IEnumerable <IntPtr> GetRowsSafe(MetadataTable table)
 {
     for (int i = 0; i < GetRowCount(table); ++i)
     {
         yield return(GetRowSafe(i.ToZB(), table));
     }
 }
Esempio n. 4
0
 public HasFieldMarshal(MetadataTable table, ZeroBasedIndex index)
 {
     if (table != MetadataTable.Field && table != MetadataTable.Param) {
         throw new ArgumentOutOfRangeException("table");
     }
     m_index = ((OneBasedIndex) index) | ((table == MetadataTable.Param ? 1u : 0u) << 1);
 }
Esempio n. 5
0
        bool LoadMetadataTables()
        {
            var pStreamHeader = (StreamHeader *)m_streams[(int)StreamID.MetadataTables];

            if (pStreamHeader == null)
            {
                return(false);
            }
            m_metadataTableHeader = (MetadataTableHeader *)checked ((byte *)m_metadataRoot + pStreamHeader->Offset);
            if (!m_metadataTableHeader->Verify())
            {
                return(false);
            }
            ComputeCodedIndexSizes();
            m_tables = new byte *[(int)MetadataTable.MAX_TABLE_ID + 1];
            var pCurrent = (byte *)m_metadataTableHeader + m_metadataTableHeader->Size;

            for (MetadataTable i = 0; i <= MetadataTable.MAX_TABLE_ID; ++i)
            {
                if (GetRowCount(i) != 0)
                {
                    m_tables[(int)i] = pCurrent;
                    pCurrent        += GetRowSize(i) * GetRowCount(i);
                }
            }
            return(true);
        }
 internal Enumerator(ref MetadataTable table)
 {
     _base        = table._blob;
     _elementSize = table._elementSize;
     _current     = _base - _elementSize;
     _limit       = _base + (_elementSize * table.ElementCount);
 }
        public static SqlBuilder ToSqlBuilder(this MetadataColumn ForeignKeyColumn)
        {
            MetadataForeignKey FK      = ForeignKeyColumn.Parent.FindForeignKeys(ForeignKeyColumn).First();
            MetadataTable      PK      = SqlBuilder.DefaultMetadata.FindTable(FK.ReferencedSchema + "." + FK.ReferencedTable);
            string             namecol = PK.GuessTitleColumn();

            string[] valuecols = FK.ColumnReferences.Where(x => !x.Column.IsComputed).Select(x => x.ReferencedColumn.Name).ToArray();

            SqlBuilder Builder = SqlBuilder.Select()
                                 .From(PK.Name, null, PK.Schema)
                                 .Column(namecol)
                                 .Columns(valuecols)
                                 .Builder();
            List <MetadataColumnReference> mcrs = FK.ColumnReferences.Where(x => x.Column.IsComputed).ToList();

            if (mcrs.Count > 0)
            {
                MetadataColumnReference first = mcrs.First();
                Builder.From(PK.Name, null, PK.Schema)
                .Where(PK.Name, first.ReferencedColumn.Name, SqlOperators.Equal, (object)first.Column.Name.Trim('\"'))
                .Builder();
                foreach (MetadataColumnReference mcr in mcrs.Skip(1))
                {
                    Builder.From(PK.Name, null, PK.Schema)
                    .Where(PK.Name, mcr.ReferencedColumn.Name, SqlOperators.Equal, (object)mcr.Column.Name.Trim('\"'))
                    .Builder();
                }
            }


            return(Builder);
        }
        public static SqlBuilder ToSqlBuilder(this MetadataTable table, string ListName)
        {
            List <string>         columns   = new List <string>(table.PrimaryKey.Columns.Select(x => x.Name));
            List <string>         columnDef = null;
            List <MetadataColumn> mcs       = new List <MetadataColumn>();

            if (table.ListDefinitions.TryGetValue(ListName, out columnDef))
            {
                mcs = table.Columns.Values.Where(x => columnDef.Contains(x.Name)).ToList();
            }
            else
            {
                mcs = table.Columns.Values.Where(x => x.IsRowGuid == false && x.IsPrimaryKey == false).ToList();
            }
            columns.AddRange(mcs.Select(x => x.Name));

            SqlBuilder Builder = SqlBuilder.Select()
                                 .From(table.Name, null, table.Schema).Builder();

            foreach (MetadataColumn mc in mcs.Where(x => x.IsForeignKey))
            {
                Builder.BaseTable().WithMetadata().AutoJoin(mc.Name);
            }

            Builder.From(table.Name, null, table.Schema).Columns(columns.ToArray());



            return(Builder);
        }
Esempio n. 9
0
        public LiftedList <T> LoadDirectChildren <T>(
            MetadataTable childTable,
            GetTokenDelegate tokenSelector,
            CreateObjectDelegateEX <T> factory,
            MetadataTable parentTable,
            void *parentRow
            ) where T : class
        {
            var            firstMemberIndex = (ZeroBasedIndex)tokenSelector(parentRow);
            ZeroBasedIndex lastMemberIndex;
            var            tableIndex = GetRowIndex(parentTable, parentRow);

            if (tableIndex == GetRowCount(parentTable) - 1)
            {
                lastMemberIndex = new ZeroBasedIndex(GetRowCount(childTable));
            }
            else
            {
                lastMemberIndex = (ZeroBasedIndex)tokenSelector(GetRow(tableIndex + 1, parentTable));
            }
            var ret = new LiftedList <T>(
                (lastMemberIndex - firstMemberIndex).Value,
                index => GetRow(firstMemberIndex + index, childTable),
                factory,
                () => IsDisposed
                );

            return(ret);
        }
Esempio n. 10
0
        public async Task <IPhysicalOperator <RowHolder> > BuildStatement(Sql.sqlStatement statement, ITransaction tran, IPhysicalOperator <RowHolder> source, InputStringNormalizer stringNormalizer)
        {
            if (statement.Joins.Any())
            {
                IPhysicalOperator <RowHolder> currJoinSource = source;
                for (int i = 0; i < statement.Joins.Length; i++)
                {
                    if (!statement.Joins[i].Item2.IsInner)
                    {
                        throw new NotSupportedException("Only inner join is supported at this point.");
                    }

                    MetadataTable joinRightTable = await this.metadataManager.GetTableManager().GetByName(statement.Joins[i].Item1, tran).ConfigureAwait(false);

                    PhyOpScan scanOpRight = new PhyOpScan(joinRightTable.Collection, tran, joinRightTable.Columns, joinRightTable.TableName);

                    Func <RowHolder, bool> filter = (_) => true;
                    if (FSharpOption <Sql.where> .get_IsSome(statement.Joins[i].Item3))
                    {
                        filter = FilterStatementBuilder.EvalWhere(
                            statement.Joins[i].Item3.Value,
                            QueryProcessingAccessors.MergeColumns(currJoinSource.GetOutputColumns(), scanOpRight.GetOutputColumns()),
                            stringNormalizer);
                    }

                    currJoinSource = new PhyOpLoopInnerJoin(currJoinSource, scanOpRight, filter);
                }

                return(currJoinSource);
            }
            else
            {
                return(source);
            }
        }
Esempio n. 11
0
        public ZeroBasedIndex GetRowIndex(MetadataTable table, void *pRow)
        {
            CheckDisposed();
            table.CheckDefined("table");
            FluentAsserts.CheckNotNull((void *)pRow, "pRow");

            var pFirst = GetRow(0.ToZB(), table);

            if (
                pRow < pFirst ||
                (((byte *)pRow - (byte *)pFirst) % GetRowSize(table)) != 0
                )
            {
                throw new ArgumentException(string.Format("Not a valid row in {0}", table), "pRow");
            }

            var index = ((byte *)pRow - (byte *)pFirst) / GetRowSize(table);

            if (index >= GetRowCount(table))
            {
                throw new ArgumentException(string.Format("Not a valid row in {0}", table), "pRow");
            }

            return(((int)index).ToZB());
        }
Esempio n. 12
0
        public LiftedList <TChild> LoadIndirectChildren <TChild, TParentField>(
            TParentField parent,
            MetadataTable childTable,
            UnsafeSelector <TParentField> parentSelector,
            CreateObjectDelegate <TChild> factory
            ) where TChild : class
        {
            CheckDisposed();
            //It is valid for the child table to not be sorted, but I don't expect such a case to occur in practice.
            //I imagine that this could maybe happen with ENC, but we don't need to be able to decompile enc assemblies.
            //In either case, if we do end up needing to support assemblies with unsorted meta-data tables, then we should probably
            //add our best attempt at an efficent fallback in that case. For now we just throw.
            IsSorted(childTable).Assume("The generic param constraint table is not sorted.");

            var glb = GreatestLowerBound(
                childTable,
                parent,
                parentSelector
                );
            var lub = LeastUpperBound(
                childTable,
                parent,
                parentSelector
                );

            var ret = new LiftedList <TChild>(
                (glb - lub - 1).Value,
                index => GetRow(index.ToZB() + lub + 1, childTable),
                factory,
                () => IsDisposed
                );

            return(ret);
        }
Esempio n. 13
0
        public Form GetForm(MetadataTable Table, FormTypes FormType, FormLayouts FormLayout = FormLayouts.Vertical, SectionLayouts SectionLayout = SectionLayouts.VerticalTwoColumns)
        {
            if (FormType == FormTypes.Mobile)
            {
                throw new NotSupportedException("Mobile forms are not supported");
            }
            Form f;

            if (PrimaryForms.TryGetValue(Table.Fullname, out f))
            {
                return(f);
            }
            else
            {
                f = BuildForm(Table, FormType, FormLayout, SectionLayout);
                if (PrimaryForms.TryAdd(Table.Fullname, f))
                {
                    return(f);
                }
                else
                {
                    throw new InvalidOperationException("The default form for " + Table.Fullname + " could not be cached");
                }
            }
        }
Esempio n. 14
0
 public TypeOrMethodDef(MetadataTable table, ZeroBasedIndex index)
 {
     if (table != MetadataTable.TypeDef && table != MetadataTable.MethodDef) {
         throw new ArgumentException("Expected TypeDef or MethodDef", "table");
     }
     var tableId = (table == MetadataTable.TypeDef) ? 0u : 1u;
     m_index = ((OneBasedIndex) index << 1) | tableId;
 }
Esempio n. 15
0
 public HasFieldMarshal(MetadataTable table, ZeroBasedIndex index)
 {
     if (table != MetadataTable.Field && table != MetadataTable.Param)
     {
         throw new ArgumentOutOfRangeException("table");
     }
     m_index = ((OneBasedIndex)index) | ((table == MetadataTable.Param ? 1u : 0u) << 1);
 }
Esempio n. 16
0
 public HasCustomAttribute(MetadataTable table, ZeroBasedIndex index)
 {
     uint value;
     if (! s_inverseTables.TryGetValue(table, out value)) {
         throw new ArgumentException("HasCustomAttributes does not support the provided meta-data table", "table");
     }
     m_index = (OneBasedIndex) index | (value << 5);
 }
Esempio n. 17
0
 public uint GetTableIndexSize(MetadataTable table)
 {
     CheckDisposed();
     if (GetRowCount(table) >= (1 << 17))
     {
         return(4);
     }
     return(2);
 }
        public ContentResult Rows(string TableName, ListTypes ListType, string ListName)
        {
            MetadataTable mt      = SqlBuilder.DefaultMetadata.FindTable(TableName);
            SqlBuilder    Builder = mt.ToSqlBuilder(ListType != ListTypes.Custom ? ListType.ToString() : ListName);

            ResultTable result = Builder.Execute(30, false, ResultTable.DateHandlingEnum.ConvertToDate);

            return(Content(SerializationExtensions.ToJson <dynamic>(result), "application/json"));
        }
Esempio n. 19
0
 public LiftedList <CustomAttribute> LoadCustomAttributes(MetadataTable parentTable, void *parentRow)
 {
     return(Module.PEFile.LoadIndirectChildren(
                new HasCustomAttribute(parentTable, GetRowIndex(parentTable, parentRow)),
                MetadataTable.CustomAttribute,
                pRow => ((CustomAttributeRow *)pRow)->GetParent(this),
                pRow => new CustomAttribute((CustomAttributeRow *)pRow, this)
                ));
 }
Esempio n. 20
0
        public TypeOrMethodDef(MetadataTable table, ZeroBasedIndex index)
        {
            if (table != MetadataTable.TypeDef && table != MetadataTable.MethodDef)
            {
                throw new ArgumentException("Expected TypeDef or MethodDef", "table");
            }
            var tableId = (table == MetadataTable.TypeDef) ? 0u : 1u;

            m_index = ((OneBasedIndex)index << 1) | tableId;
        }
Esempio n. 21
0
        private void PersistQueryTable(IEnumerable <TwitterSearchRow> queries)
        {
            var batchOperation = new TableBatchOperation();

            foreach (var query in queries)
            {
                batchOperation.InsertOrReplace(query);
            }
            MetadataTable.ExecuteBatch(batchOperation);
        }
Esempio n. 22
0
        public MetadataRow ResolveRow()
        {
            MetadataTable tbl = (Container as TablesHeap)[(TableType)Token.Type];

            if (tbl == null) // table type not found
            {
                return(null);
            }
            return(tbl.Rows[(int)Token.Index]);
        }
Esempio n. 23
0
        private int GetTableLength(Table table)
        {
            MetadataTable metadataTable = this.tables[(int)table];

            if (metadataTable == null)
            {
                return(0);
            }
            return(metadataTable.Length);
        }
Esempio n. 24
0
 public void Scenario_repeatable_migration_executed_everytime()
 {
     for (int i = 1; i <= 3; i++)
     {
         Evolve.Migrate();
         Assert.True(Evolve.AppliedMigrations.Count == 1, $"This repeat always migration should be executed each time.");
         Assert.True(MetadataTable.GetAllAppliedRepeatableMigration().Count() == i);
         Assert.False(MetadataTable.GetAllAppliedMigration().Any());
     }
 }
Esempio n. 25
0
        public HasCustomAttribute(MetadataTable table, ZeroBasedIndex index)
        {
            uint value;

            if (!s_inverseTables.TryGetValue(table, out value))
            {
                throw new ArgumentException("HasCustomAttributes does not support the provided meta-data table", "table");
            }
            m_index = (OneBasedIndex)index | (value << 5);
        }
Esempio n. 26
0
 private void WriteTables()
 {
     for (int i = 0; i < this.tables.Length; i++)
     {
         MetadataTable metadataTable = this.tables[i];
         if (metadataTable != null && metadataTable.Length != 0)
         {
             metadataTable.Write(this);
         }
     }
 }
Esempio n. 27
0
 private void WriteRowCount()
 {
     for (int i = 0; i < this.tables.Length; i++)
     {
         MetadataTable metadataTable = this.tables[i];
         if (metadataTable != null && metadataTable.Length != 0)
         {
             base.WriteUInt32((uint)metadataTable.Length);
         }
     }
 }
Esempio n. 28
0
 public LiftedList <T> LoadDirectChildren <T>(
     MetadataTable childTable,
     GetTokenDelegate tokenSelector,
     CreateObjectDelegate <T> factory,
     MetadataTable parentTable,
     void *parentRow
     ) where T : class
 {
     factory.CheckNotNull("factory");
     return(LoadDirectChildren(childTable, tokenSelector, (pRow, index) => factory(pRow), parentTable, parentRow));
 }
        private static Table JoinInternal(MetadataHelper helper, string Totable, string ToSchema, Join.JoinTypes JoinType)
        {
            if (helper.Model.PrimaryKey.Columns.Count != 1)
            {
                throw new InvalidOperationException("Only tables with one primary key field is supported");
            }
            MetadataColumn     FromField = helper.Model.PrimaryKey.Columns.First();
            MetadataTable      mt        = helper.Table.Builder.Metadata.FindTable(ToSchema + "." + Totable);
            JoinConditionGroup jcg       = To(helper.Table.Builder, helper.Table, helper.Model, FromField, mt, JoinType, false);

            return(jcg.ToTable());
        }
Esempio n. 30
0
 private void ComputeTableInformations(TableHeapBuffer table_heap)
 {
     MetadataTable[] tables = table_heap.tables;
     for (int i = 0; i < tables.Length; i++)
     {
         MetadataTable table = tables[i];
         if (table != null && table.Length > 0)
         {
             table_infos[i].Length = (uint)table.Length;
         }
     }
 }
        /// <summary>
        /// Initialize a new instance of the RecoveryStoreComponent class.
        /// </summary>
        /// <param name="metadataTable"></param>
        /// <param name="workDirectory"></param>
        /// <param name="traceType"></param>
        /// <param name="keyConverter"></param>
        /// <param name="isValueReferenceType"></param>
        public RecoveryStoreComponent(MetadataTable metadataTable, string workDirectory, string traceType, IStateSerializer <TKey> keyConverter, bool isValueReferenceType)
        {
            this.metadataTable = metadataTable;
            this.workDirectory = workDirectory;
            this.traceType     = traceType;
            this.keyConverter  = keyConverter;

            this.fileId = InvalidFileId;
            this.logicalCheckpointFileTimeStamp = InvalidTimeStamp;
            this.component            = new PartitionedSortedList <TKey, TVersionedItem <TValue> >(KeyComparer);
            this.isValueReferenceType = isValueReferenceType;
        }
Esempio n. 32
0
        private void WriteTables()
        {
            for (int i = 0; i < tables.Length; i++)
            {
                MetadataTable table = tables[i];
                if (table == null || table.Length == 0)
                {
                    continue;
                }

                table.Write(this);
            }
        }
Esempio n. 33
0
        public void *GetRow(ZeroBasedIndex index, MetadataTable table)
        {
            CheckDisposed();
            table.CheckDefined("table");
            index.CheckGTE(0, "index");
            index.CheckLT(GetRowCount(table), "index");

            if (m_tables == null || m_tables[(int)table] == null)
            {
                throw new InvalidOperationException("Missing meta-data table.");
            }
            return(checked (m_tables[(int)table] + index.Value * GetRowSize(table)));
        }
Esempio n. 34
0
        private static StringBuilder CreateTable(MetadataTable mt)
        {
            StringBuilder sb = new StringBuilder();
            foreach (string u in ClassCreationOptions.Usings)
            {
                sb.AppendFormat("using {0};\r\n", u);
            }
            sb.AppendLine("");
            sb.AppendFormat("namespace {0}\r\n{{", ClassCreationOptions.Namespace);

            
            sb.AppendFormat("\tpublic{0} class {1}\r\n{{\r\n", ClassCreationOptions.PartialClass ? " partial" : "", mt.Name);
            foreach (MetadataColumn mc in mt.Columns.Values.OrderBy(x => x.Name).OrderByDescending(x => x.IsPrimaryKey))
            {
                CreateColumn(mc, mt, sb);
            }
            sb.AppendLine("\t}\r\n}");
            return sb;
        }
Esempio n. 35
0
        private static void CreateColumn(MetadataColumn mc, MetadataTable mt, StringBuilder sb)
        {
            string format = "\t\tpublic {0}{1}{2} {3}{4}\r\n\r\n";
            string FKformat = "\t\t[FK(\"{0}\",\"{1}\",\"{2}\",\"{3}\")]\r\n";

            if (mc.IsForeignKey)
            {
                List<MetadataForeignKey> FKs = new List<MetadataForeignKey>();
                try
                {
                    IEnumerable<MetadataForeignKey> fks = mt.FindForeignKeys(mc);
                    FKs.AddRange(fks);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                
                if (FKs.Count == 0)
                {
                    throw new InvalidOperationException(string.Format("The foreign key for Column {0} in table {1} cannot be resolved to one key", mc.Name, mt.Fullname));
                }
                MetadataForeignKey FK = FKs.First();
                sb.AppendFormat(FKformat, FK.ReferencedTable,FK.ColumnReferences.First().ReferencedColumn.Name, FK.ReferencedSchema, FK.Name);
            }
            if (mc.IsPrimaryKey)
            {
                sb.AppendLine("\t\t[PK]");
            }
            bool nullable = mc.Nullable && (mc.DataType != typeof(string) && !mc.DataType.IsByRef && !mc.DataType.IsArray);
            if (ClassCreationOptions.ColumnAsProperty)
            {
                sb.AppendFormat(format, (nullable ? "Nullable<" : ""),mc.DataType.Name, nullable ? "> " : " ", mc.Name, " { get; set; }");
            }
            else
            {
                sb.AppendFormat(format, nullable ? "Nullable<" : "", mc.DataType.Name, nullable ? "> " : " ", mc.Name, ";");
            }
        }
Esempio n. 36
0
 public Form GetForm(MetadataTable Table, FormTypes FormType, FormLayouts FormLayout = FormLayouts.Vertical, SectionLayouts SectionLayout = SectionLayouts.VerticalTwoColumns)
 {
     if (FormType == FormTypes.Mobile)
     {
         throw new NotSupportedException("Mobile forms are not supported");
     }
     Form f;
     if (PrimaryForms.TryGetValue(Table.Fullname, out f))
     {
         return f;
     }
     else
     {
         f = BuildForm(Table, FormType, FormLayout, SectionLayout);
         if (PrimaryForms.TryAdd(Table.Fullname, f))
         {
             return f;
         }
         else
         {
             throw new InvalidOperationException("The default form for " + Table.Fullname + " could not be cached");
         }
     }
 }
Esempio n. 37
0
 private void BuildVirtualKeys(List<VirtualForeignKey> keys, MetadataTable mt, MetadataDatabase mdb, bool PrimaryKeyIndexOnly)
 {
     foreach (VirtualForeignKey vfk in keys)
     {
         MetadataForeignKey mfk = new MetadataForeignKey()
         {
             ID = 0,
             Name = vfk.values[0].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)[0],
             ReferencedKey = "",
             ReferencedTable = vfk.values[0].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)[1],
             ReferencedSchema = vfk.values[0].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)[2],
             Parent = mt,
             IsVirtual = true
         };
         MetadataTable mtref = null;
         if (!mdb.Tables.TryGetValue(mfk.ReferencedSchema + "." + mfk.ReferencedTable, out mtref))
         {
             bool self = false;
             if (mfk.ReferencedSchema == mt.Schema && mfk.ReferencedTable == mt.Name)
             {
                 self = true;
             }
             mtref = BuildMetadata(mdb, mfk.ReferencedTable, mfk.ReferencedSchema, PrimaryKeyIndexOnly, self);
         }
         for (int i = 1; i < vfk.values.Length; i++)
         {
             MetadataColumnReference mcf = new MetadataColumnReference()
             {
                 ReferencedColumn = mtref[vfk.values[i].Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries)[1]],
             };
             string from = vfk.values[i].Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries)[0];
             if (from.StartsWith("\""))
             {
                 MetadataColumn mcVirtual = new MetadataColumn()
                 {
                     Name = from,
                     IsForeignKey = true,
                     ID = 0,
                     SqlDataType = SqlDbType.NVarChar,
                     Nullable = false,
                     Length = 0,
                     IsComputed = true,
                     DataType = typeof(string),
                 };
                 mcf.Column = mcVirtual;
                 mcf.Name = from;
             }
             else
             {
                 mcf.Column = mt[from];
                 mcf.Name = mcf.Column.Name;
             }
             mfk.ColumnReferences.Add(mcf);
         }
         mt.ForeignKeys.AddOrUpdate(mfk.Name, mfk, (k, v) => { return mfk; });
     }
 }
Esempio n. 38
0
        private MetadataTable BuildMetadata(MetadataDatabase mdb, Microsoft.SqlServer.Management.Smo.Table table, bool PrimaryKeyIndexOnly = true, bool SelfJoin = false)
        {
            MetadataTable mt = null;
            List<VirtualForeignKey> VirtualKeys = new List<VirtualForeignKey>();
            table.Refresh();
            if (mdb.Tables.TryGetValue(table.Name, out mt))
            {
                return mt;
            }

            mt = new MetadataTable()
            {
                ID = table.ID,
                Schema = table.Schema,
                Name = table.Name,
                //Parent = mdb
            };
            mt.TitleColumn = GetExtendedProperty("TitleColumn", table.ExtendedProperties);
            string[] values = GetExtendedProperty("DisplayName", table.ExtendedProperties, new char[] { '\r', '\n' });
            if (values != null)
            {
                foreach (string value in values)
                {
                    string[] v = value.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
                    mt.DisplayNames.TryAdd(Convert.ToInt32(v[0]), v[1]);
                }
            }

            values = GetExtendedProperty("Lists", table.ExtendedProperties, new char[] { '\r', '\n' });
            if (values != null)
            {
                foreach (string value in values)
                {
                    string[] v = value.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
                    List<string> v2 = v[1].Split(',').ToList();
                    if (!mt.ListDefinitions.TryAdd(v[0].Trim(), v2))
                    {
                        throw new InvalidOperationException(string.Format("The TinySql.Lists extended property is invalid for the table '{0}'", table.Name));
                    }
                }
            }






            foreach (Microsoft.SqlServer.Management.Smo.Column column in table.Columns)
            {
                try
                {
                    MetadataColumn col = new MetadataColumn()
                    {
                        ID = column.ID,
                        Parent = mt,
                        //Database = mdb,
                        Name = column.Name,
                        Collation = column.Collation,
                        Default = column.Default,
                        IsComputed = column.Computed,
                        ComputedText = column.ComputedText,
                        IsPrimaryKey = column.InPrimaryKey,
                        IsIdentity = column.Identity,
                        IsForeignKey = column.IsForeignKey,
                        IdentityIncrement = column.IdentityIncrement,
                        IdentitySeed = column.IdentitySeed,
                        Nullable = column.Nullable,
                        IsRowGuid = column.RowGuidCol
                    };
                    BuildColumnDataType(col, column);

                    values = GetExtendedProperty("DisplayName", column.ExtendedProperties, new char[] { '\r', '\n' });
                    if (values != null)
                    {
                        foreach (string value in values)
                        {
                            if (!value.Contains("="))
                            {
                                col.DisplayNames.TryAdd(SqlBuilder.DefaultCulture.LCID, value);
                            }
                            else
                            {
                                string[] v = value.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
                                col.DisplayNames.TryAdd(Convert.ToInt32(v[0]), v[1]);
                            }

                        }
                    }





                    col.IncludeColumns = GetExtendedProperty("IncludeColumns", column.ExtendedProperties, new char[] { ',' });

                    values = GetExtendedProperty("FK", column.ExtendedProperties, new char[] { '\r', '\n' });
                    if (values != null)
                    {
                        VirtualKeys.Add(new VirtualForeignKey() { Column = col, values = values });
                        col.IsForeignKey = true;
                    }



                    mt.Columns.AddOrUpdate(col.Name, col, (k, v) => { return col; });


                }
                catch (Exception exColumn)
                {
                    throw new InvalidOperationException(string.Format("Unable to generate the column {0}", column.Name), exColumn);
                }
            }



            foreach (Index idx in table.Indexes)
            {
                if (!PrimaryKeyIndexOnly || idx.IndexKeyType == IndexKeyType.DriPrimaryKey)
                {
                    Key key = new Key()
                    {
                        ID = idx.ID,
                        Parent = mt,
                        Database = mdb,
                        Name = idx.Name,
                        IsUnique = idx.IsUnique,
                        IsPrimaryKey = idx.IndexKeyType == IndexKeyType.DriPrimaryKey
                    };
                    foreach (IndexedColumn c in idx.IndexedColumns)
                    {
                        key.Columns.Add(mt[c.Name]);
                    }
                    mt.Indexes.AddOrUpdate(key.Name, key, (k, v) => { return key; });
                }
            }
            if (!SelfJoin)
            {
                foreach (ForeignKey FK in table.ForeignKeys)
                {
                    MetadataForeignKey mfk = new MetadataForeignKey()
                    {
                        ID = FK.ID,
                        Parent = mt,
                        Database = mdb,
                        Name = FK.Name,
                        ReferencedKey = FK.ReferencedKey,
                        ReferencedSchema = FK.ReferencedTableSchema,
                        ReferencedTable = FK.ReferencedTable
                    };
                    MetadataTable mtref = null;
                    if (!mdb.Tables.TryGetValue(mfk.ReferencedSchema + "." + mfk.ReferencedTable, out mtref))
                    {
                        bool self = false;
                        if ((mfk.ReferencedSchema == mt.Schema && mfk.ReferencedTable == mt.Name) || TablesInProgress.Contains(mfk.ReferencedSchema + "." + mfk.ReferencedTable))
                        {
                            self = true;
                        }
                        TablesInProgress.Add(mfk.ReferencedSchema + "." + mfk.ReferencedTable);
                        mtref = BuildMetadata(mdb, mfk.ReferencedTable, mfk.ReferencedSchema, PrimaryKeyIndexOnly, self);
                    }
                    foreach (ForeignKeyColumn cc in FK.Columns)
                    {
                        mfk.ColumnReferences.Add(new MetadataColumnReference()
                        {
                            Name = cc.Name,
                            Column = mt[cc.Name],
                            ReferencedColumn = mtref[cc.ReferencedColumn]
                        });
                    }
                    mt.ForeignKeys.AddOrUpdate(mfk.Name, mfk, (key, existing) =>
                    {
                        return mfk;
                    });
                }
            }

            if (VirtualKeys.Count > 0)
            {
                BuildVirtualKeys(VirtualKeys, mt, mdb, PrimaryKeyIndexOnly);
            }

            mdb.Tables.AddOrUpdate(mt.Schema + "." + mt.Name, mt, (key, existing) =>
            {
                return mt;
            });
            return mt;
        }
Esempio n. 39
0
 public Form BuildForm(MetadataTable Table, FormTypes FormType, FormLayouts FormLayout = FormLayouts.Vertical, SectionLayouts SectionLayout = SectionLayouts.VerticalTwoColumns)
 {
     Form form = new Form();
     form.FormLayout = FormLayout;
     form.TitleColumn = Table.GuessTitleColumn();
     if (form.TitleColumn == null)
     {
         form.TitleColumn = Table.PrimaryKey.Columns.First().Name;
     }
     FormSection section = new FormSection() { SectionLayout = SectionLayout };
     string TableName = Table.Fullname;
     foreach (MetadataColumn col in Table.Columns.Values)
     {
         BuildField(col, TableName, null, section, null, false);
     }
     form.Sections.Add(section);
     return form;
 }
Esempio n. 40
0
        public Form BuildForm(RowData Data, FormLayouts FormLayout = FormLayouts.Vertical, SectionLayouts SectionLayout = SectionLayouts.Vertical, MetadataTable Table = null)
        {
            if (Table == null)
            {
                Table = Data.Metadata;
                if (Table == null)
                {
                    throw new ArgumentException("The Metadata Table argument is null, and metadata cannot be retrieved from the RowData object", "Table");
                }
            }
            Form form = new Form();
            form.FormLayout = FormLayout;
            form.TitleColumn = Table.GuessTitleColumn();

            FormSection section = new FormSection();
            section.SectionLayout = SectionLayout;
            List<string> Columns = Data.Columns;
            string TableName = Table.Fullname;
            foreach (string s in Columns)
            {
                MetadataColumn mc;
                if (Table.Columns.TryGetValue(s, out mc))
                {
                    BuildField(mc, TableName, null, section, null, false);
                }
            }
            form.Sections.Add(section);
            form.Initialize(Data, Table);
            return form;
        }
Esempio n. 41
0
 public void Initialize(RowData data, MetadataTable table = null)
 {
     this.data = data;
     this._Metadata = table;
 }
Esempio n. 42
0
        public FieldModel GetFieldModel(FormField Field, MetadataTable Model, RowData Data)
        {
            MetadataColumn mc = null;
            MetadataTable mt = Model;
            if (Field.ID.StartsWith("__"))
            {
                return new FieldModel(Field, null, Data.Column(Field.Name), SectionLayout);
            }
            if (Field.TableName != Model.Fullname)
            {
                mt = SqlBuilder.DefaultMetadata.FindTable(Field.TableName);
            }
            if (!mt.Columns.TryGetValue(Field.Name, out mc))
            {
                throw new InvalidOperationException("Cannot get a model for " + Field.Name);
            }

            return new FieldModel(Field, mc, Data.Column(Field.Alias ?? Field.Name), SectionLayout);

        }
Esempio n. 43
0
 internal SectionModel(FormSection formSection, MetadataTable model, RowData data)
 {
     this.Section = formSection;
     this.Model = model;
     this.Data = data;
 }
Esempio n. 44
0
        //# Returns the number of rows for the given meta-data table. If a table is not present, 0 will be returned.
        //# throws: ArgumentOutOfRangeException - If [table] is not valid.
        public int GetRowCount(MetadataTable table)
        {
            if ((byte)table >= (sizeof(ulong)*8)) {
                throw new ArgumentOutOfRangeException("table", "Invalid meta-data table.");
            }
            if (((1ul << (int)table) & ValidTables) == 0) {
                return 0;
            }

            fixed (MetadataTableHeader* pThis = &this) {
                var pRows = (uint *)((byte*) pThis + 24);

                //The index of the row n is the number of 1 bits that preceed position n in the
                //valid tables bit mask. So we mask out all bits at or above position n in the valid mask
                //and then compute it's bit count.
                var index = (((1ul << (int) table) - 1) & ValidTables).BitCount();
                return checked((int)pRows[index]);
            }
        }