コード例 #1
0
        public void can_ensure_schema_info()
        {
            var si = new SchemaInfo(Driver);
            si.EnsureSchemaTable();

            Assert.IsTrue(Driver.Inspect<ITableExistsOperation>(op => op.TableName = "SchemaInfo"));
        }
コード例 #2
0
        private SchemaInfo FromPropertyInfo(PropertyInfo pi)
        {
            if (!this.IsMapped(pi))
                return null;

            Type propertyType = pi.PropertyType;

            bool nullableTypeDetected = propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == CachedTypes.PureNullableType;

            SchemaInfo schema = new SchemaInfo(pi.Name, nullableTypeDetected ? propertyType.GetGenericArguments()[0] : propertyType);

            //NotMapped gibi bir standart
            KeyAttribute keyAtt = pi.GetCustomAttribute<KeyAttribute>();
            if (null != keyAtt)
                schema.IsKey = true;

            if (nullableTypeDetected)
                schema.IsNullable = true;
            else
            {
                if (propertyType.IsClass)
                    schema.IsNullable = true;
                else if (propertyType.IsValueType)
                    schema.IsNullable = false;
            }

            bool hasSetMethod = pi.GetSetMethod() != null;
            if (!hasSetMethod)
                schema.ReadOnly = true;

            this.SetExtendedSchema(schema, pi);

            return schema;
        }
コード例 #3
0
ファイル: Schema.cs プロジェクト: prepare/deveeldb
        public Schema(SchemaInfo schemaInfo)
        {
            if (schemaInfo == null)
                throw new ArgumentNullException("schemaInfo");

            SchemaInfo = schemaInfo;
        }
コード例 #4
0
        public void can_get_most_recent_version()
        {
            var si = new SchemaInfo(Driver);
            si.EnsureSchemaTable();

            si.InsertSchemaVersion(10, "assembly", "foo");
            si.InsertSchemaVersion(100, "assembly", "bar");
            si.InsertSchemaVersion(1, "assembly", "baz");

            Assert.AreEqual(100, si.CurrentSchemaVersion("assembly"));
        }
コード例 #5
0
            private static IEntityMetaData FromEdmx(IObjectContextAdapter contextAdapter, Type entityType)
            {
                List<SchemaInfo> schemas = new List<SchemaInfo>();

                MetadataWorkspace mw = contextAdapter.ObjectContext.MetadataWorkspace;

                EntityType et = mw.GetItems<EntityType>(DataSpace.CSpace).FirstOrDefault(e => String.Equals(e.Name, entityType.Name));
                if (null != et)
                {
                    foreach (EdmProperty edmProperty in et.Properties)
                    {
                        SchemaInfo schema = new SchemaInfo(edmProperty.Name);
                        schema.DataType = Type.GetType("System." + edmProperty.TypeUsage.EdmType.Name);

                        ReadOnlyMetadataCollection<Facet> facets = edmProperty.TypeUsage.Facets;
                        Facet facet;
                        if (facets.TryGetValue("Nullable", true, out facet))
                        {
                            schema.IsNullable = (bool)facet.Value;
                        }
                        if (facets.TryGetValue("MaxLength", true, out facet))
                        {
                            schema.MaxLength = (int)facet.Value;
                        }

                        schemas.Add(schema);
                    }

                    foreach (EdmMember keyInfo in et.KeyMembers)
                    {
                        schemas.First(s => s.ColumnName == keyInfo.Name).IsKey = true;
                    }

                    if (et.KeyMembers.Count == 1)
                    {
                        SchemaInfo key = schemas.First(s => s.IsKey);
                        if (key.DataType != CachedTypes.Guid)
                            key.DatabaseGeneratedOption = Data.StoreGeneratedPattern.Identity;
                    }

                    if (schemas.Count != 0)
                    {
                        EntityMetaData ret = new EntityMetaData(entityType, entityType.Name);
                        foreach (SchemaInfo schema in schemas)
                        {
                            ret.Add(schema, entityType.GetProperty(schema.ColumnName));
                        }
                        return ret;
                    }
                }

                return null;
            }
コード例 #6
0
        public void can_get_all_version()
        {
            var si = new SchemaInfo(Driver);
            si.EnsureSchemaTable();

            si.InsertSchemaVersion(10, "assembly", "foo");
            si.InsertSchemaVersion(100, "assembly", "bar");
            si.InsertSchemaVersion(1, "assembly", "baz");

            IList<long> versions = si.AppliedMigrations("assembly");
            Assert.AreEqual(3, versions.Count);
            Assert.AreEqual(1, versions[0]);
            Assert.AreEqual(100, versions[2]);
        }
コード例 #7
0
        static void Main(string[] args)
        {
            SchemaInfo schema = new SchemaInfo("Id", CachedTypes.Int32);

            schema.DatabaseGeneratedOption = StoreGeneratedPattern.Identity; ;
            schema.DefaultValue = "1";
            schema.IsKey = true;
            schema.IsNullable = false;
            schema.MaxLength = 12;
            schema.Order = 1;
            schema.ReadOnly = true;
            schema.SqlValueType = SqlValueType.Parameterized;


            string xml = schema.XmlSerialize();

            SchemaInfo copy = SchemaInfo.FromXml(xml);


           // ExtTestAsync().Wait();
            ExtTest();
            ExtTestAsync().Wait();
            SelectTest();
            SelectSingleTest();

            Update_NonIdentity();
            Insert_NonIdentity();
            UpsertUpdate_NonIdentity();
            UpsertInsert_NonIdentity();
            Update_Identity();
            Insert_Identity();
            UpsertUpdate_Identity();
            UpsertInsert_Identity();
            Delete();
            Batch_Update_NonIdentity();
            Batch_Insert_NonIdentity();
            Batch_Upsert_Update_NonIdentity();
            Batch_Upsert_Insert_NonIdentity();
            Batch_Update_Identity();
            Batch_Insert_Identity();
            Batch_Upsert_Update_Identity();
            Batch_Upsert_Insert_Identity();


        }
コード例 #8
0
ファイル: SchemaManager.cs プロジェクト: prepare/deveeldb
        public void CreateSchema(SchemaInfo schemaInfo)
        {
            if (schemaInfo == null)
                throw new ArgumentNullException("schemaInfo");

            var tableName = SystemSchema.SchemaInfoTableName;
            var t = Transaction.GetMutableTable(tableName);

            var nameObj = DataObject.String(schemaInfo.Name);

            if (t.Exists(1, nameObj))
                throw new DatabaseSystemException(String.Format("Schema '{0}' already defined in the database.", schemaInfo.Name));

            var row = t.NewRow();
            var uniqueId = Transaction.NextTableId(tableName);
            row.SetValue(0, DataObject.Number(uniqueId));
            row.SetValue(1, DataObject.String(schemaInfo.Name));
            row.SetValue(2, DataObject.String(schemaInfo.Type));
            row.SetValue(3, DataObject.String(schemaInfo.Culture));

            t.AddRow(row);
        }
コード例 #9
0
ファイル: SchemaInfo.cs プロジェクト: ionixNet/ionix.Data
        public void XmlTest()
        {
            SchemaInfo schema = new SchemaInfo("Id", CachedTypes.Guid);
            schema.DatabaseGeneratedOption = StoreGeneratedPattern.None;
            schema.DefaultValue = Guid.Empty.ToString();
            schema.IsKey = true;
            schema.IsNullable = false;
            schema.MaxLength = 32;
            schema.ReadOnly = false;
            schema.SqlValueType = SqlValueType.Parameterized;;

            string xml = schema.XmlSerialize();

            SchemaInfo copy = schema.Copy();

            Stopwatch bench = Stopwatch.StartNew();
            for (int j = 0; j < 100; ++j)
                copy = schema.Copy();
            bench.Stop();

            Debug.WriteLine("Schema Xml Copy: " +  bench.ElapsedMilliseconds);

            Assert.IsNotNull(copy);
        }
コード例 #10
0
 public async Task <string> GenerateDataScriptsAsync(SchemaInfo schemaInfo)
 {
     return(await this.dbScriptGenerator.GenerateDataScriptsAsync(schemaInfo));
 }
コード例 #11
0
        public void can_insert_schema_version()
        {
            var si = new SchemaInfo(Driver);
            si.EnsureSchemaTable();

            si.InsertSchemaVersion(10, "assembly", "foo");

            using (var reader = Driver.Read<IGenericReaderOperation>(op => op.Sql = "SELECT * FROM SchemaInfo WHERE Version=10"))
            {
                Assert.IsTrue(reader.Read());
            }
        }
コード例 #12
0
        public static List <SqlWord> FindWords(DatabaseType databaseType, string search, SqlWordTokenType tokenType = SqlWordTokenType.None, string parentName = null)
        {
            List <SqlWord> words = new List <SqlWord>();

            //if (IsTypeMatched(tokenType, SqlWordTokenType.Keyword))
            //{
            //    var keywords = KeywordManager.GetKeywords(databaseType).Where(item => Contains(item, search));

            //    words.AddRange(keywords.Select(item => new SqlWord() { Type = SqlWordTokenType.Keyword, Text = item }));
            //}

            if (IsTypeMatched(tokenType, SqlWordTokenType.BuiltinFunction))
            {
                var builtinFunctions = FunctionManager.GetFunctionSpecifications(databaseType).Where(item => ContainsWithNull(item.Name, search));

                words.AddRange(builtinFunctions.Select(item => new SqlWord()
                {
                    Type = SqlWordTokenType.BuiltinFunction, Text = item.Name, Source = item
                }));
            }

            SchemaInfo schemaInfo = DataStore.GetSchemaInfo(databaseType);

            if (schemaInfo != null)
            {
                if (IsTypeMatched(tokenType, SqlWordTokenType.Owner))
                {
                    var owners = schemaInfo.Tables.Where(item => ContainsWithNull(item.Owner, search)).Select(item => item.Owner).Distinct();

                    words.AddRange(owners.Select(item => new SqlWord()
                    {
                        Type = SqlWordTokenType.Owner, Text = item, Source = item
                    }));
                }

                FilterDbObjects(words, schemaInfo.Functions, SqlWordTokenType.Function, tokenType, search, parentName);

                FilterDbObjects(words, schemaInfo.Tables, SqlWordTokenType.Table, tokenType, search, parentName);

                FilterDbObjects(words, schemaInfo.Views, SqlWordTokenType.View, tokenType, search, parentName);

                if (tokenType == SqlWordTokenType.TableColumn)
                {
                    IEnumerable <TableColumn> columns = schemaInfo.TableColumns;

                    if (!string.IsNullOrEmpty(parentName))
                    {
                        columns = schemaInfo.TableColumns.Where(item => item.TableName.ToUpper() == parentName.ToUpper());
                    }

                    if (!string.IsNullOrEmpty(search))
                    {
                        columns = columns.Where(item => ContainsWithNull(item.Name, search));
                    }

                    words.AddRange(columns.Select(item => new SqlWord()
                    {
                        Type = SqlWordTokenType.TableColumn, Text = item.Name, Source = item
                    }));
                }
            }

            return(words);
        }
コード例 #13
0
 public IObjectGraphType GetContentResultType(SchemaInfo schemaId)
 {
     return(contentResultTypes.GetOrDefault(schemaId));
 }
コード例 #14
0
        public void TestAddAndLookupAndDeleteSchemaInfo()
        {
            ShardMapManagerFactory.CreateSqlShardMapManager(
                Globals.ShardMapManagerConnectionString,
                ShardMapManagerCreateMode.ReplaceExisting);

            ShardMapManager shardMapManager = ShardMapManagerFactory.GetSqlShardMapManager(
                Globals.ShardMapManagerConnectionString,
                ShardMapManagerLoadPolicy.Lazy);

            #region TestAddAndLookup

            SchemaInfoCollection siCollection = shardMapManager.GetSchemaInfoCollection();

            SchemaInfo si = new SchemaInfo();

            ShardedTableInfo stmd1 = new ShardedTableInfo("ShardedTableName1", "ColumnName");
            ShardedTableInfo stmd2 = new ShardedTableInfo("dbo", "ShardedTableName2", "ColumnName");

            si.Add(stmd1);
            si.Add(stmd2);

            Assert.AreEqual(2, si.ShardedTables.Count);

            ReferenceTableInfo rtmd1 = new ReferenceTableInfo("ReferenceTableName1");
            ReferenceTableInfo rtmd2 = new ReferenceTableInfo("dbo", "ReferenceTableName2");

            si.Add(rtmd1);
            si.Add(rtmd2);

            Assert.AreEqual(2, si.ReferenceTables.Count);
            // Add an existing sharded table again. Make sure it doesn't create duplicate entries.
            SchemaInfoException siex = AssertExtensions.AssertThrows <SchemaInfoException>(
                () => si.Add(new ShardedTableInfo("ShardedTableName1", "ColumnName")));
            Assert.AreEqual(SchemaInfoErrorCode.TableInfoAlreadyPresent, siex.ErrorCode);

            // Add an existing sharded table with a different key column name. This should fail too.
            siex = AssertExtensions.AssertThrows <SchemaInfoException>(
                () => si.Add(new ShardedTableInfo("ShardedTableName1", "ColumnName_Different")));
            Assert.AreEqual(SchemaInfoErrorCode.TableInfoAlreadyPresent, siex.ErrorCode);

            siex = AssertExtensions.AssertThrows <SchemaInfoException>(
                () => si.Add(new ShardedTableInfo("dbo", "ShardedTableName2", "ColumnName_Different")));
            Assert.AreEqual(SchemaInfoErrorCode.TableInfoAlreadyPresent, siex.ErrorCode);

            Assert.AreEqual(2, si.ShardedTables.Count);

            // Add an existing reference tables again. Make sure it doesn't create duplicate entries.
            siex = AssertExtensions.AssertThrows <SchemaInfoException>(
                () => si.Add(new ReferenceTableInfo("dbo", "ReferenceTableName2")));
            Assert.AreEqual(SchemaInfoErrorCode.TableInfoAlreadyPresent, siex.ErrorCode);

            Assert.AreEqual(2, si.ReferenceTables.Count);

            // Now trying adding a reference table as a sharded table and vice versa. Both operations should fail.
            siex = AssertExtensions.AssertThrows <SchemaInfoException>(
                () => si.Add(new ShardedTableInfo("ReferenceTableName1", "ColumnName")));
            Assert.AreEqual(SchemaInfoErrorCode.TableInfoAlreadyPresent, siex.ErrorCode);

            Assert.AreEqual(2, si.ShardedTables.Count);

            siex = AssertExtensions.AssertThrows <SchemaInfoException>(
                () => si.Add(new ReferenceTableInfo("dbo", "ShardedTableName2")));
            Assert.AreEqual(SchemaInfoErrorCode.TableInfoAlreadyPresent, siex.ErrorCode);

            Assert.AreEqual(2, si.ReferenceTables.Count);

            // Try removing an existing table info and adding it back.
            si.Remove(stmd1);
            si.Add(stmd1);
            Assert.AreEqual(2, si.ShardedTables.Count);

            si.Remove(rtmd2);
            si.Add(rtmd2);
            Assert.AreEqual(2, si.ReferenceTables.Count);

            // Test with NULL inputs.
            ArgumentException arex = AssertExtensions.AssertThrows <ArgumentException>(
                () => si.Add((ShardedTableInfo)null));

            arex = AssertExtensions.AssertThrows <ArgumentException>(
                () => si.Add((ReferenceTableInfo)null));

            string mdName = String.Format("TestSI_{0}", Guid.NewGuid());
            siCollection.Add(mdName, si);

            SchemaInfo sdmdRead = siCollection.Get(mdName);

            AssertEqual(si, sdmdRead);

            // Trying to add schema info with the same name again will result in a 'name conflict' exception.
            siex = AssertExtensions.AssertThrows <SchemaInfoException>(
                () => siCollection.Add(mdName, si));
            Assert.AreEqual(SchemaInfoErrorCode.SchemaInfoNameConflict, siex.ErrorCode);

            #endregion

            #region TestLookup

            // Try looking up schema info with a non-existent name.
            siex = AssertExtensions.AssertThrows <SchemaInfoException>(
                () => siCollection.Get(mdName + "Fail"));
            Assert.AreEqual(SchemaInfoErrorCode.SchemaInfoNameDoesNotExist, siex.ErrorCode);


            #endregion

            #region TestDelete

            // Try removing any of the recently created schema info.
            siCollection.Remove(mdName);

            // Lookup should fail on removed data.
            siex = AssertExtensions.AssertThrows <SchemaInfoException>(
                () => siCollection.Get(mdName));
            Assert.AreEqual(SchemaInfoErrorCode.SchemaInfoNameDoesNotExist, siex.ErrorCode);

            #endregion
        }
コード例 #15
0
        public void TestGetAll()
        {
            ShardMapManagerFactory.CreateSqlShardMapManager(
                Globals.ShardMapManagerConnectionString,
                ShardMapManagerCreateMode.ReplaceExisting);

            ShardMapManager shardMapManager = ShardMapManagerFactory.GetSqlShardMapManager(
                Globals.ShardMapManagerConnectionString,
                ShardMapManagerLoadPolicy.Lazy);


            SchemaInfoCollection siCollection = shardMapManager.GetSchemaInfoCollection();

            SchemaInfo[] si = new SchemaInfo[3]
            {
                new SchemaInfo(),
                new SchemaInfo(),
                new SchemaInfo()
            };

            si[0].Add(new ShardedTableInfo("ShardedTableName1", "ColumnName1"));
            si[0].Add(new ShardedTableInfo("dbo", "ShardedTableName2", "ColumnName1"));

            si[0].Add(new ReferenceTableInfo("ReferenceTableName1"));
            si[0].Add(new ReferenceTableInfo("dbo", "ReferenceTableName2"));

            si[1].Add(new ShardedTableInfo("ShardedTableName3", "ColumnName2"));
            si[1].Add(new ShardedTableInfo("dbo", "ShardedTableName4", "ColumnName2"));

            si[1].Add(new ReferenceTableInfo("ReferenceTableName3"));

            si[2].Add(new ShardedTableInfo("dbo", "ShardedTableName3", "ColumnName2"));

            si[2].Add(new ReferenceTableInfo("ReferenceTableName4"));
            si[2].Add(new ReferenceTableInfo("dbo", "ReferenceTableName5"));

            string[] siNames = new string[3]
            {
                String.Format("TestSI_{0}", Guid.NewGuid()),
                String.Format("TestSI_{0}", Guid.NewGuid()),
                String.Format("TestSI_{0}", Guid.NewGuid())
            };

            siCollection.Add(siNames[0], si[0]);
            siCollection.Add(siNames[1], si[1]);
            siCollection.Add(siNames[2], si[2]);

            int  i       = 0;
            bool success = true;

            foreach (KeyValuePair <string, SchemaInfo> kvp in siCollection)
            {
                SchemaInfo sdmdOriginal;
                try
                {
                    sdmdOriginal = si[Array.IndexOf(siNames, kvp.Key)];
                }
                catch
                {
                    success = false;
                    break;
                }

                AssertEqual(sdmdOriginal, kvp.Value);
                i++;
            }

            Assert.IsTrue(success);
            Assert.AreEqual(3, i);
        }
コード例 #16
0
 public static void CreateSchema(this ITransaction transaction, SchemaInfo schemaInfo)
 {
     transaction.CreateObject(schemaInfo);
 }
コード例 #17
0
 protected void Page_Init(object sender, EventArgs e)
 {
     schemaInfo = Application["SchemaInfo"] as SchemaInfo;
 }
コード例 #18
0
 // FIXME: this class should actually be reimplemented to be one
 // of the derived classes of DbDataRecord, which should become
 // almost abstract.
 internal DbDataRecordImpl(SchemaInfo[] schema, object[] values)
 {
     this.schema = schema;
     this.values = values;
     this.fieldCount = values.Length;
 }
コード例 #19
0
 public override async Task <string> GenerateDataScriptsAsync(SchemaInfo schemaInfo)
 {
     return(await base.GenerateDataScriptsAsync(schemaInfo));
 }
コード例 #20
0
        public override ScriptBuilder GenerateSchemaScripts(SchemaInfo schemaInfo)
        {
            ScriptBuilder sb = new ScriptBuilder();

            string dbOwner = this.GetDbOwner();

            //#region User Defined Type

            //List<string> userTypeNames = schemaInfo.UserDefinedTypes.Select(item => item.Name).Distinct().ToList();

            //foreach (string userTypeName in userTypeNames)
            //{
            //    IEnumerable<UserDefinedType> userTypes = schemaInfo.UserDefinedTypes.Where(item => item.Name == userTypeName);

            //    this.FeedbackInfo(OperationState.Begin, userTypes.First());

            //    string dataTypes = string.Join(",", userTypes.Select(item => $"{item.AttrName} {this.dbInterpreter.ParseDataType(new TableColumn() { MaxLength = item.MaxLength, DataType = item.Type, Precision = item.Precision, Scale = item.Scale })}"));

            //    string script = $"CREATE TYPE {this.GetQuotedString(userTypeName)} AS OBJECT ({dataTypes})" + this.dbInterpreter.ScriptsDelimiter;

            //    sb.AppendLine(new CreateDbObjectScript<UserDefinedType>(script));

            //    this.FeedbackInfo(OperationState.End, userTypes.First());
            //}

            //#endregion

            #region Function
            sb.AppendRange(this.GenerateScriptDbObjectScripts <Function>(schemaInfo.Functions));
            #endregion

            #region Table
            foreach (Table table in schemaInfo.Tables)
            {
                this.FeedbackInfo(OperationState.Begin, table);

                IEnumerable <TableColumn>     columns     = schemaInfo.TableColumns.Where(item => item.TableName == table.Name).OrderBy(item => item.Order);
                TablePrimaryKey               primaryKey  = schemaInfo.TablePrimaryKeys.FirstOrDefault(item => item.TableName == table.Name);
                IEnumerable <TableForeignKey> foreignKeys = schemaInfo.TableForeignKeys.Where(item => item.TableName == table.Name);
                IEnumerable <TableIndex>      indexes     = schemaInfo.TableIndexes.Where(item => item.TableName == table.Name).OrderBy(item => item.Order);
                IEnumerable <TableConstraint> constraints = schemaInfo.TableConstraints.Where(item => item.Owner == table.Owner && item.TableName == table.Name);

                ScriptBuilder sbTable = this.AddTable(table, columns, primaryKey, foreignKeys, indexes, constraints);

                sb.AppendRange(sbTable.Scripts);

                this.FeedbackInfo(OperationState.End, table);
            }
            #endregion

            #region View
            sb.AppendRange(this.GenerateScriptDbObjectScripts <View>(schemaInfo.Views));
            #endregion

            #region Trigger
            sb.AppendRange(this.GenerateScriptDbObjectScripts <TableTrigger>(schemaInfo.TableTriggers));
            #endregion

            #region Procedure
            sb.AppendRange(this.GenerateScriptDbObjectScripts <Procedure>(schemaInfo.Procedures));
            #endregion

            if (this.option.ScriptOutputMode.HasFlag(GenerateScriptOutputMode.WriteToFile))
            {
                this.AppendScriptsToFile(sb.ToString(), GenerateScriptMode.Schema, true);
            }

            return(sb);
        }
コード例 #21
0
        public void can_remove_schema_version()
        {
            can_insert_schema_version();

            var si = new SchemaInfo(Driver);
            si.DeleteSchemaVersion(10, "assembly");

            using (var reader = Driver.Read<IGenericReaderOperation>(op => op.Sql = "SELECT * FROM SchemaInfo WHERE Version=10"))
            {
                Assert.IsFalse(reader.Read());
            }
        }
コード例 #22
0
 protected abstract void SetExtendedSchema(SchemaInfo schema, PropertyInfo pi);
コード例 #23
0
 protected override void SetExtendedSchema(SchemaInfo schema, PropertyInfo pi)
 {
     DbSchemaAttribute att = pi.GetCustomAttribute<DbSchemaAttribute>();
     if (null != att)
     {
         if (!String.IsNullOrEmpty(att.ColumnName))
             schema.ColumnName = att.ColumnName;
         schema.DatabaseGeneratedOption = att.DatabaseGeneratedOption;
         schema.DefaultValue = att.DefaultValue;
         schema.IsKey = att.IsKey;
         schema.MaxLength = att.MaxLength;
         schema.Order = att.Order;
         schema.IsNullable = att.IsNullable;
         schema.ReadOnly = att.ReadOnly;
     }
 }
コード例 #24
0
ファイル: XmlSchema.cs プロジェクト: uQr/referencesource
 public void Compile(ValidationEventHandler validationEventHandler, XmlResolver resolver) {
     SchemaInfo sInfo = new SchemaInfo();
     sInfo.SchemaType = SchemaType.XSD;
     CompileSchema(null, resolver, sInfo, null, validationEventHandler, NameTable, false);
 }
コード例 #25
0
ファイル: XmlSchema.cs プロジェクト: uQr/referencesource
 internal void AddCompiledInfo(SchemaInfo schemaInfo) {
     XmlQualifiedName itemName;
     foreach (XmlSchemaElement element in elements.Values) {
         itemName = element.QualifiedName;
         schemaInfo.TargetNamespaces[itemName.Namespace] = true;
         if (schemaInfo.ElementDecls[itemName] == null) {
             schemaInfo.ElementDecls.Add(itemName, element.ElementDecl);
         }
     }
     foreach (XmlSchemaAttribute attribute in attributes.Values) {
         itemName = attribute.QualifiedName;
         schemaInfo.TargetNamespaces[itemName.Namespace] = true;
         if (schemaInfo.ElementDecls[itemName] == null) {
             schemaInfo.AttributeDecls.Add(itemName, attribute.AttDef);
         }
     }    
     foreach (XmlSchemaType type in types.Values) {
         itemName = type.QualifiedName;
         schemaInfo.TargetNamespaces[itemName.Namespace] = true;
         XmlSchemaComplexType complexType = type as XmlSchemaComplexType;
         if ((complexType == null || type != XmlSchemaComplexType.AnyType) && schemaInfo.ElementDeclsByType[itemName] == null) {
             schemaInfo.ElementDeclsByType.Add(itemName, type.ElementDecl);
         }
     }
     foreach (XmlSchemaNotation notation in notations.Values) {
         itemName = notation.QualifiedName;
         schemaInfo.TargetNamespaces[itemName.Namespace] = true;
         SchemaNotation no = new SchemaNotation(itemName);
         no.SystemLiteral = notation.System;
         no.Pubid = notation.Public;
         if (schemaInfo.Notations[itemName.Name] == null) {
             schemaInfo.Notations.Add(itemName.Name, no);
         }
     }
 }
コード例 #26
0
ファイル: MainForm.cs プロジェクト: valery-shinkevich/sooda
 private void LoadSchemaFromXml(string fileName)
 {
     schemaInfo = SchemaManager.ReadAndValidateSchema(
         new XmlTextReader(fileName),
         Path.GetDirectoryName(fileName));
 }
コード例 #27
0
    private static void GetAssembliesAndTypes(string[] pClassFilenames, string[] pDependencyFilenames, ref SchemaInfo pSchema)
    {
      // Creates a SchemaExtractor instance on a new domain. This is done
      // so that no assembly is loaded on process start, and at the end,
      // only needed assemblies are loaded.
      AppDomain lDomain = AppDomain.CreateDomain("User assemblies domain.");
      SchemaExtractor lExtractor;
      lExtractor = (SchemaExtractor)lDomain.CreateInstanceFromAndUnwrap(typeof(SchemaExtractor).Assembly.CodeBase, typeof(SchemaExtractor).FullName);
      // Load assemblies and types on the new domain.
      List<string> lTypeNames = null;
      List<string> lAssemblyNames = null;
      List<string> lActualDependencies = null;
      lExtractor.GetAssembliesAndTypesHelper(pClassFilenames, pDependencyFilenames, ref lAssemblyNames, ref lTypeNames, ref lActualDependencies);
      AppDomain.Unload(lDomain);

      // Load assemblies on this domain (to be able to access types).
      Assembly l;
      foreach (string lDep in lActualDependencies)
      {
        l = Assembly.LoadFrom(lDep);
      }

      // Obtain types from names and fill in schema.
      pSchema.PersistableTypes = lTypeNames.Select(lTypeName => DataMember.GetTypeFromAnyAssemblyVersion(lTypeName)).ToArray();
      pSchema.LoadedAssemblies = lActualDependencies.ToArray();
      pSchema.LoadedAssembliesNames = lAssemblyNames.ToArray();
    }
コード例 #28
0
        private async void GenerateScourceDbScripts()
        {
            SchemaInfo schemaInfo = this.GetSourceTreeSchemaInfo();

            if (!this.ValidateSource(schemaInfo))
            {
                return;
            }

            this.btnGenerateSourceScripts.Enabled = false;

            DatabaseType sourceDbType = this.GetDatabaseType(this.cboSourceDB.Text);

            int dataBatchSize = SettingManager.Setting.DataBatchSize;
            DbInterpreterOption sourceScriptOption = new DbInterpreterOption()
            {
                ScriptOutputMode = GenerateScriptOutputMode.WriteToFile, DataBatchSize = dataBatchSize
            };

            this.SetGenerateScriptOption(sourceScriptOption);

            GenerateScriptMode scriptMode = this.GetGenerateScriptMode();

            if (scriptMode == GenerateScriptMode.None)
            {
                MessageBox.Show("Please specify the script mode.");
                return;
            }

            DbInterpreter dbInterpreter = DbInterpreterHelper.GetDbInterpreter(sourceDbType, this.sourceDbConnectionInfo, sourceScriptOption);

            SelectionInfo selectionInfo = new SelectionInfo()
            {
                UserDefinedTypeNames = schemaInfo.UserDefinedTypes.Select(item => item.Name).ToArray(),
                TableNames           = schemaInfo.Tables.Select(item => item.Name).ToArray(),
                ViewNames            = schemaInfo.Views.Select(item => item.Name).ToArray()
            };

            try
            {
                schemaInfo = await dbInterpreter.GetSchemaInfoAsync(selectionInfo);

                dbInterpreter.Subscribe(this);

                GenerateScriptMode mode = GenerateScriptMode.None;

                if (scriptMode.HasFlag(GenerateScriptMode.Schema))
                {
                    mode = GenerateScriptMode.Schema;
                    dbInterpreter.GenerateSchemaScripts(schemaInfo);
                }

                if (scriptMode.HasFlag(GenerateScriptMode.Data))
                {
                    mode = GenerateScriptMode.Data;
                    await dbInterpreter.GenerateDataScriptsAsync(schemaInfo);
                }

                this.OpenInExplorer(dbInterpreter.GetScriptOutputFilePath(mode));

                MessageBox.Show(DONE);
            }
            catch (Exception ex)
            {
                this.HandleException(ex);
            }

            this.btnGenerateSourceScripts.Enabled = true;
        }
コード例 #29
0
 private void AssertEqual(SchemaInfo x, SchemaInfo y)
 {
     AssertExtensions.AssertSequenceEquivalent(x.ReferenceTables, y.ReferenceTables);
     AssertExtensions.AssertSequenceEquivalent(x.ShardedTables, y.ShardedTables);
 }
コード例 #30
0
 public OguObjectCollection <IOguObject> QueryDescendants(IOrganization parent, string prefix, int maxCount)
 {
     return(this.QueryDescendants <IOguObject>(parent, prefix, maxCount, SchemaInfo.FilterByCategory("Users", "Groups", "Organizations").ToSchemaNames()));
 }
コード例 #31
0
        static XmlQualifiedName AddAttributeTypeToXmlSchema(SchemaInfo schemaInfo, UxmlAttributeDescription description, IUxmlFactory factory, FactoryProcessingHelper processingData)
        {
            if (description.name == null)
            {
                return(null);
            }

            string attrTypeName = factory.uxmlQualifiedName + "_" + description.name + "_" + k_TypeSuffix;
            string attrTypeNameInBaseElement = factory.substituteForTypeQualifiedName + "_" + description.name + "_" + k_TypeSuffix;

            FactoryProcessingHelper.AttributeRecord attrRecord;
            if (processingData.attributeTypeNames.TryGetValue(attrTypeNameInBaseElement, out attrRecord))
            {
                // If restriction != baseElement.restriction, we need to declare a new type.
                // Note: we do not support attributes having a less restrictive restriction than its base type.
                if ((description.restriction == null && attrRecord.desc.restriction == null) ||
                    (description.restriction != null && description.restriction.Equals(attrRecord.desc.restriction)))
                {
                    // Register attrTypeName -> attrRecord for potential future derived elements.
                    processingData.attributeTypeNames.Add(attrTypeName, attrRecord);
                    return(attrRecord.name);
                }
            }

            XmlQualifiedName xqn;

            FactoryProcessingHelper.AttributeRecord attributeRecord;

            if (description.restriction == null)
            {
                // Type is a built-in type.
                xqn             = new XmlQualifiedName(description.type, description.typeNamespace);
                attributeRecord = new FactoryProcessingHelper.AttributeRecord {
                    name = xqn, desc = description
                };
                processingData.attributeTypeNames.Add(attrTypeName, attributeRecord);
                return(xqn);
            }

            string attrTypeNameForSchema = factory.uxmlName + "_" + description.name + "_" + k_TypeSuffix;

            xqn = new XmlQualifiedName(attrTypeNameForSchema, schemaInfo.schema.TargetNamespace);

            XmlSchemaSimpleType simpleType = new XmlSchemaSimpleType();

            simpleType.Name = attrTypeNameForSchema;

            UxmlEnumeration enumRestriction = description.restriction as UxmlEnumeration;

            if (enumRestriction != null)
            {
                XmlSchemaSimpleTypeRestriction restriction = new XmlSchemaSimpleTypeRestriction();
                simpleType.Content       = restriction;
                restriction.BaseTypeName = new XmlQualifiedName(description.type, description.typeNamespace);

                foreach (var v in enumRestriction.values)
                {
                    XmlSchemaEnumerationFacet enumValue = new XmlSchemaEnumerationFacet();
                    enumValue.Value = v;
                    restriction.Facets.Add(enumValue);
                }
            }
            else
            {
                UxmlValueMatches regexRestriction = description.restriction as UxmlValueMatches;
                if (regexRestriction != null)
                {
                    XmlSchemaSimpleTypeRestriction restriction = new XmlSchemaSimpleTypeRestriction();
                    simpleType.Content       = restriction;
                    restriction.BaseTypeName = new XmlQualifiedName(description.type, description.typeNamespace);

                    XmlSchemaPatternFacet pattern = new XmlSchemaPatternFacet();
                    pattern.Value = regexRestriction.regex;
                    restriction.Facets.Add(pattern);
                }
                else
                {
                    UxmlValueBounds bounds = description.restriction as UxmlValueBounds;
                    if (bounds != null)
                    {
                        XmlSchemaSimpleTypeRestriction restriction = new XmlSchemaSimpleTypeRestriction();
                        simpleType.Content       = restriction;
                        restriction.BaseTypeName = new XmlQualifiedName(description.type, description.typeNamespace);

                        XmlSchemaFacet facet;
                        if (bounds.excludeMin)
                        {
                            facet = new XmlSchemaMinExclusiveFacet();
                        }
                        else
                        {
                            facet = new XmlSchemaMinInclusiveFacet();
                        }
                        facet.Value = bounds.min;
                        restriction.Facets.Add(facet);

                        if (bounds.excludeMax)
                        {
                            facet = new XmlSchemaMaxExclusiveFacet();
                        }
                        else
                        {
                            facet = new XmlSchemaMaxInclusiveFacet();
                        }
                        facet.Value = bounds.max;
                        restriction.Facets.Add(facet);
                    }
                    else
                    {
                        Debug.Log("Unsupported restriction type.");
                    }
                }
            }

            schemaInfo.schema.Items.Add(simpleType);
            attributeRecord = new FactoryProcessingHelper.AttributeRecord {
                name = xqn, desc = description
            };
            processingData.attributeTypeNames.Add(attrTypeName, attributeRecord);
            return(xqn);
        }
コード例 #32
0
 public void LoadAllFederationAssemblies()
 {
   if (m_typesAssemblies != null && m_typesAssemblies.Length > 0)
     m_schemaInfo = SchemaExtractor.Extract(m_typesAssemblies, m_typesDependencyAssemblies);
 }
コード例 #33
0
 protected void CreateSchemaInfoTable()
 {
     EnsureHasConnection();
     SchemaInfo.CreateTableIfYouHaventAlready();
 }
コード例 #34
0
        /// <summary>
        ///     Get Schema Information for current DB.
        ///     The Schema Information will be cache into CacheManager.Default
        /// </summary>
        /// <returns></returns>
        public virtual SchemaInfo GetSchemaInfo(string databaseName = null)
        {
            if (databaseName.IsNullOrEmpty())
            {
                var cn = (SqlConnectionStringBuilder)ConnectionString;
                databaseName = cn.InitialCatalog;
                if (databaseName.IsNullOrEmpty())
                {
                    databaseName = cn.AttachDBFilename;
                }
            }
            Guard.ArgumentIsNotNull(databaseName, nameof(databaseName));

            SchemaInfo schema;

            using (var reader = ExecuteReader(QuerySchemaInfo))
            {
                schema = new SchemaInfo(databaseName);

                while (reader.Read())
                {
                    #region Field Values

                    var ordinalPosition        = reader.GetValue <int>(FieldOrdinalPosition);
                    var tableName              = reader.GetValue <string>(FieldTableName);
                    var tableSchema            = reader.GetValue <string>(FieldTableSchema);
                    var columnName             = reader.GetValue <string>(FieldColumnName);
                    var isNullable             = reader.GetValue <bool>(FieldIsNullable);
                    var dataType               = reader.GetValue <string>(FieldDataType).ToSqlDbType();
                    var characterMaximumLength = reader.GetValue <int>(FieldCharacterMaximumLength);
                    var isIdentity             = reader.GetValue <bool>(FieldIsIdentity);
                    var isComputed             = reader.GetValue <bool>(FieldIsComputed);
                    var isPrimaryKey           = reader.GetValue <bool>(FieldIsPrimaryKey);
                    var isPoreignKey           = reader.GetValue <bool>(FieldIsPoreignKey);
                    var fkTableSchema          = reader.GetValue <string>(FieldFkTableSchema);
                    var fkTableName            = reader.GetValue <string>(FieldFkTableName);
                    var fkColumnName           = reader.GetValue <string>(FieldFkColumnName);
                    var rowCount               = reader.GetValue <int>(FieldRowCount);
                    var foreignKeyName         = reader.GetValue <string>(FieldForeignKeyName);
                    var isTable = reader.GetValue <bool>(FieldIsTable);

                    #endregion Field Values

                    #region Collect Info

                    var tbName = new DbName(tableSchema, tableName);

                    if (isTable)
                    {
                        //Collect Tables
                        var table = schema.Tables[tbName];

                        if (table == null)
                        {
                            table = new TableInfo(tbName)
                            {
                                RowCount = rowCount
                            };
                            schema.Tables.Add(table);
                        }

                        //Collect ColumnInfo
                        var column = table.Columns[columnName];
                        if (column == null)
                        {
                            column = new ColumnInfo
                            {
                                Name            = columnName,
                                OrdinalPosition = ordinalPosition,
                                DataType        = dataType,
                                IsIdentity      = isIdentity,
                                IsPrimaryKey    = isPrimaryKey,
                                IsNullable      = isNullable,
                                MaxLengh        = characterMaximumLength,
                                IsComputed      = isComputed
                            };
                            table.Columns.Add(column);
                        }

                        if (!isPoreignKey)
                        {
                            continue;
                        }

                        //Collect ForeignKeys
                        var refCol = new ReferencedColumnInfo(fkTableSchema, fkTableName, fkColumnName);
                        table.ForeignKeys.Add(new ForeignKeyInfo(foreignKeyName, column, refCol));
                    }
                    else
                    {
                        //Collect Views
                        var view = schema.Views[tbName];

                        if (view == null)
                        {
                            view = new ViewInfo(tbName);
                            schema.Views.Add(view);
                        }

                        if (!view.Columns.Contains(columnName))
                        {
                            view.Columns.Add(columnName);
                        }
                    }

                    #endregion Collect Info
                }
            }

            schema = GetMaxPrimaryKeyValues(schema);
            return(schema);
        }
コード例 #35
0
        private async Task Convert()
        {
            SchemaInfo schemaInfo = this.GetSourceTreeSchemaInfo();

            if (!this.ValidateSource(schemaInfo))
            {
                return;
            }

            if (this.targetDbConnectionInfo == null)
            {
                MessageBox.Show("Target connection info is null.");
                return;
            }

            if (this.sourceDbConnectionInfo.Server == this.targetDbConnectionInfo.Server && this.sourceDbConnectionInfo.Database == this.targetDbConnectionInfo.Database)
            {
                MessageBox.Show("Source database cannot be equal to the target database.");
                return;
            }

            DatabaseType sourceDbType = this.GetDatabaseType(this.cboSourceDB.Text);
            DatabaseType targetDbType = this.GetDatabaseType(this.cboTargetDB.Text);

            int dataBatchSize = SettingManager.Setting.DataBatchSize;
            DbInterpreterOption sourceScriptOption = new DbInterpreterOption()
            {
                ScriptOutputMode = GenerateScriptOutputMode.None, DataBatchSize = dataBatchSize
            };
            DbInterpreterOption targetScriptOption = new DbInterpreterOption()
            {
                ScriptOutputMode = (GenerateScriptOutputMode.WriteToString), DataBatchSize = dataBatchSize
            };

            this.SetGenerateScriptOption(sourceScriptOption, targetScriptOption);

            if (this.chkGenerateSourceScripts.Checked)
            {
                sourceScriptOption.ScriptOutputMode = sourceScriptOption.ScriptOutputMode | GenerateScriptOutputMode.WriteToFile;
            }

            if (this.chkOutputScripts.Checked)
            {
                targetScriptOption.ScriptOutputMode = targetScriptOption.ScriptOutputMode | GenerateScriptOutputMode.WriteToFile;
            }

            targetScriptOption.GenerateIdentity = this.chkGenerateIdentity.Checked;

            GenerateScriptMode scriptMode = this.GetGenerateScriptMode();

            if (scriptMode == GenerateScriptMode.None)
            {
                MessageBox.Show("Please specify the script mode.");
                return;
            }

            DbConvetorInfo source = new DbConvetorInfo()
            {
                DbInterpreter = DbInterpreterHelper.GetDbInterpreter(sourceDbType, this.sourceDbConnectionInfo, sourceScriptOption)
            };
            DbConvetorInfo target = new DbConvetorInfo()
            {
                DbInterpreter = DbInterpreterHelper.GetDbInterpreter(targetDbType, this.targetDbConnectionInfo, targetScriptOption)
            };

            try
            {
                using (dbConvertor = new DbConvertor(source, target))
                {
                    dbConvertor.Option.GenerateScriptMode          = scriptMode;
                    dbConvertor.Option.BulkCopy                    = this.chkBulkCopy.Checked;
                    dbConvertor.Option.ExecuteScriptOnTargetServer = this.chkExecuteOnTarget.Checked;
                    dbConvertor.Option.UseTransaction              = this.chkUseTransaction.Checked;

                    dbConvertor.Subscribe(this);

                    if (sourceDbType == DatabaseType.MySql)
                    {
                        source.DbInterpreter.Option.InQueryItemLimitCount = 2000;
                    }

                    if (targetDbType == DatabaseType.SqlServer)
                    {
                        target.DbOwner = this.txtTargetDbOwner.Text ?? "dbo";
                    }
                    else if (targetDbType == DatabaseType.MySql)
                    {
                        target.DbInterpreter.Option.RemoveEmoji = true;
                    }

                    dbConvertor.Option.SplitScriptsToExecute = true;

                    this.btnExecute.Enabled = false;
                    this.btnCancel.Enabled  = true;

                    await dbConvertor.Convert(schemaInfo);
                }
            }
            catch (Exception ex)
            {
                this.hasError = true;
                this.HandleException(ex);
            }

            if (!this.hasError)
            {
                this.btnExecute.Enabled = true;
                this.btnCancel.Enabled  = false;

                if (!this.dbConvertor.CancelRequested)
                {
                    this.txtMessage.AppendText(Environment.NewLine + DONE);
                    MessageBox.Show(DONE);
                }
                else
                {
                    MessageBox.Show("Task has been canceled.");
                }
            }
        }
コード例 #36
0
 protected override void SetExtendedSchema(SchemaInfo schema, PropertyInfo pi)
 {
     if (pi.GetCustomAttribute<KeyAttribute>() != null || String.Equals(pi.Name, "Id", StringComparison.OrdinalIgnoreCase))
     {
         schema.IsKey = true;
     }
 }
コード例 #37
0
        public OguObjectCollection <IOguObject> GetObjects(params string[] ids)
        {
            ids.NullCheck("ids");

            SCObjectAndRelationCollection relations = SCSnapshotAdapter.Instance.QueryObjectAndRelationByIDs(SchemaInfo.FilterByCategory("Users", "Groups", "Organizations").ToSchemaNames(), ids, false, DateTime.MinValue);

            relations.FillDetails();

            List <IOguObject> list = new List <IOguObject>(relations.Count);

            foreach (var item in relations)
            {
                SchemaObjectBase obj = item.Detail;
                if (obj != null)
                {
                    IOguObject oguObj = obj.ToSimpleObject().ToOguObject();
                    list.Add(oguObj);
                }
            }

            return(new OguObjectCollection <IOguObject>(list));
        }
コード例 #38
0
ファイル: Extensions.cs プロジェクト: julienM77/squidex
 internal static FieldType WithSchemaNamedId(this FieldType field, SchemaInfo value)
 {
     return(field.WithMetadata(nameof(SchemaNamedId), value.Schema.NamedId()));
 }
コード例 #39
0
        public IEnumerable <IOguObject> GetChildren(IOrganization parent)
        {
            SCObjectAndRelationCollection relations = SCSnapshotAdapter.Instance.QueryObjectAndRelationByParentIDs(SchemaInfo.FilterByCategory("Users", "Groups", "Organizations").ToSchemaNames(), new string[] { parent.ID }, false, true, false, DateTime.MinValue);

            relations.FillDetails();

            var parentList = SCSnapshotAdapter.Instance.LoadAllParentsInfo(true, parent.ID)[parent.ID];

            StringBuilder strB = new StringBuilder(parentList.Count * 15);

            for (int i = 0; i < parentList.Count; i++)
            {
                strB.Append(parentList[i].Name);
                strB.Append("");
            }

            var parentPath = strB.ToString();

            foreach (var item in relations)
            {
                OguBase ogu = (OguBase)item.Detail.ToPhantom();
                ogu.FullPath = parentPath + ogu.Name;

                yield return(ogu);
            }
        }
コード例 #40
0
ファイル: xmlloader.cs プロジェクト: SSCLI/sscli_20021101
        private void LoadDocumentType(XmlValidatingReader vr, XmlDocumentType dtNode)
        {
            SchemaInfo schInfo = vr.GetSchemaInfo();

            if (schInfo != null)
            {
                //set the schema information into the document
                doc.SchemaInformation = schInfo;

                // Notation hashtable
                if (schInfo.Notations != null)
                {
                    foreach (SchemaNotation scNot in schInfo.Notations.Values)
                    {
                        dtNode.Notations.SetNamedItem(new XmlNotation(scNot.Name.Name, scNot.Pubid, scNot.SystemLiteral, doc));
                    }
                }

                // Entity hashtables
                if (schInfo.GeneralEntities != null)
                {
                    foreach (SchemaEntity scEnt in schInfo.GeneralEntities.Values)
                    {
                        XmlEntity ent = new XmlEntity(scEnt.Name.Name, scEnt.Text, scEnt.Pubid, scEnt.Url, scEnt.NData.IsEmpty ? null : scEnt.NData.Name, doc);
                        ent.SetBaseURI(scEnt.DeclaredURI);
                        dtNode.Entities.SetNamedItem(ent);
                    }
                }

                if (schInfo.ParameterEntities != null)
                {
                    foreach (SchemaEntity scEnt in schInfo.ParameterEntities.Values)
                    {
                        XmlEntity ent = new XmlEntity(scEnt.Name.Name, scEnt.Text, scEnt.Pubid, scEnt.Url, scEnt.NData.IsEmpty ? null : scEnt.NData.Name, doc);
                        ent.SetBaseURI(scEnt.DeclaredURI);
                        dtNode.Entities.SetNamedItem(ent);
                    }
                }
                doc.Entities = dtNode.Entities;

                //extract the elements which has attribute defined as ID from the element declarations
                IDictionaryEnumerator elementDecls = schInfo.ElementDecls.GetEnumerator();
                if (elementDecls != null)
                {
                    elementDecls.Reset();
                    while (elementDecls.MoveNext())
                    {
                        SchemaElementDecl elementDecl = (SchemaElementDecl)elementDecls.Value;
                        if (elementDecl.AttDefs != null)
                        {
                            IDictionaryEnumerator attDefs = elementDecl.AttDefs.GetEnumerator();
                            while (attDefs.MoveNext())
                            {
                                SchemaAttDef attdef = (SchemaAttDef)attDefs.Value;
                                if (attdef.Datatype.TokenizedType == XmlTokenizedType.ID)
                                {
                                    doc.AddIdInfo(
                                        doc.GetXmlName(elementDecl.Name.Name, elementDecl.Name.Namespace),
                                        doc.GetXmlName(attdef.Name.Name, attdef.Name.Namespace));
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
コード例 #41
0
ファイル: SchemaInfoBuilder.cs プロジェクト: eaba/SharpPulsar
 public SchemaInfoBuilder()
 {
     _info = new SchemaInfo();
 }
コード例 #42
0
        public override void Run()
        {
            //State = WorkerState.Working;
            try
            {
                //initialize the context
                using (CurrentDbContext = new AryaDbDataContext(CurrentProjectId, ImportRequestedBy))
                {
                    var imageMgr = new ImageManager(CurrentDbContext, CurrentProjectId);

                    List <ListOfValuesInterchangeRecord> allData = ImportData.ListOfValues;
                    //read all the data into a list<T>, change this as its not very efficient and scalable.
                    var invalidRecords = allData.GetInvalidRecords();
                    var listOfValuesInterchangeRecords = invalidRecords as IList <ListOfValuesInterchangeRecord> ?? invalidRecords.ToList();
                    listOfValuesInterchangeRecords.ToList().ForEach(ir => _warnings.Add(new WorkerWarning
                    {
                        LineData     = ir.ToString(),
                        ErrorMessage = Properties.Resources.RequiredValueNullWarningMessage
                    }));
                    var validImportRecords = allData.Except(listOfValuesInterchangeRecords.ToList()).ToList();
                    var newValueCount      = 0;
                    int ignoredCount       = 0;
                    int updatedCount       = 0;
                    // load a dictionary with taxonomy string / id pairs (taken from TaxonomyImport)
                    var taxDict =
                        CurrentDbContext.ExecuteQuery <TaxonomyPathAndId>(@"SELECT TaxonomyPath, TaxonomyId
                                                FROM V_Taxonomy
                                                WHERE TaxonomyPath <> ''
                                                AND ProjectId = {0}", CurrentProjectId).ToDictionary(
                            key => key.TaxonomyPath, value => value.TaxonomyId,
                            StringComparer.OrdinalIgnoreCase);

                    // load attribute and schema dictionaries
                    var attDict =
                        CurrentDbContext.Attributes.Where(
                            a => a.AttributeType == AttributeTypeEnum.Sku.ToString())
                        .Select(a => a)
                        .ToDictionary(key => key.AttributeName, value => value);
                    var schDict = new DoubleKeyDictionary <Guid, Guid, SchemaInfo>();
                    CurrentDbContext.SchemaInfos.ForEach(si => schDict.Add(si.TaxonomyID, si.AttributeID, si));

                    // iterate through the input records.
                    foreach (var csvRecord in validImportRecords)
                    {
                        var currentRecord = csvRecord;
                        // check for taxonomy - if it doesn't exist, give up.
                        if (!taxDict.ContainsKey(currentRecord.TaxonomyPath))
                        {
                            _warnings.Add(new WorkerWarning()
                            {
                                LineData = currentRecord.ToString(), ErrorMessage = Properties.Resources.TaxonomyDoesNotExistsWarningMessage
                            });
                            continue;
                        }
                        var taxId    = taxDict[currentRecord.TaxonomyPath];
                        var taxonomy = CurrentDbContext.TaxonomyInfos.First(ti => ti.ID == taxId);

                        // if attribute exists, get it, otherwise give up.
                        if (!attDict.ContainsKey(currentRecord.AttributeName))
                        {
                            _warnings.Add(new WorkerWarning()
                            {
                                LineData = currentRecord.ToString(), ErrorMessage = Properties.Resources.AttributeDoesNotExistWarningMessage
                            });
                            continue;
                        }
                        var att = attDict[currentRecord.AttributeName];

                        // if schema info exists, get it, otherwise create both it and schema data
                        SchemaInfo sch;
                        if (schDict.ContainsKeys(taxId, att.ID))
                        {
                            sch = schDict[taxId, att.ID];
                        }
                        else
                        {
                            sch = new SchemaInfo(CurrentDbContext)
                            {
                                TaxonomyID  = taxId,
                                Attribute   = att,
                                SchemaDatas =
                                {
                                    new SchemaData(CurrentDbContext)
                                    {
                                        InSchema = true, NavigationOrder = 0, DisplayOrder = 0
                                    }
                                }
                            };
                            att.SchemaInfos.Add(sch);
                            schDict.Add(taxId, att.ID, sch);
                        }
                        var    lov = sch.ListOfValues.FirstOrDefault(v => v.Value.ToLower() == currentRecord.Lov.ToLower() && v.Active);
                        string enrichmentImageGuid = null;
                        int    displayOrder;
                        if (lov != null || (lov == null && CurrentImportOptions.HasFlag(ImportOptions.CreateMissingLOVs)))
                        {
                            // if image url exists try to upload the image - "try" is used in case the url is badly formed.
                            // string enrichmentImage = null;

                            var success = false;
                            if (currentRecord.EnrichmentImage != null)
                            {
                                //Success is for valid uri. If the image name only exist not the real file it will be false and added as warning
                                success             = imageMgr.UploadImage(currentRecord.EnrichmentImage);
                                enrichmentImageGuid = imageMgr.RemoteImageGuid;
                                var newSku = imageMgr.ImageSku;

                                newSku.EntityInfos.Add(new EntityInfo(CurrentDbContext)
                                {
                                    EntityDatas =
                                    {
                                        new EntityData(CurrentDbContext)
                                        {
                                            Attribute =
                                                Attribute.GetAttributeFromName(CurrentDbContext,
                                                                               Framework.Properties.Resources.LovIdAttributeName, true, AttributeTypeEnum.Sku, false),
                                            Value = imageMgr.RemoteImageGuid
                                        }
                                    }
                                });

                                newSku.EntityInfos.Add(new EntityInfo(CurrentDbContext)
                                {
                                    EntityDatas =
                                    {
                                        new EntityData(CurrentDbContext)
                                        {
                                            Attribute =
                                                Attribute.GetAttributeFromName(CurrentDbContext,
                                                                               Framework.Properties.Resources.AttributeIdAttributeName,
                                                                               true, AttributeTypeEnum.Sku, false),
                                            Value = sch.AttributeID.ToString()
                                        }
                                    }
                                });

                                newSku.EntityInfos.Add(new EntityInfo(CurrentDbContext)
                                {
                                    EntityDatas =
                                    {
                                        new EntityData(CurrentDbContext)
                                        {
                                            Attribute =
                                                Attribute.GetAttributeFromName(CurrentDbContext, Framework.Properties.Resources.TaxonomyIdAttributeName,
                                                                               true, AttributeTypeEnum.Sku, false),
                                            Value = sch.TaxonomyID.ToString()
                                        }
                                    }
                                });

                                taxonomy.SkuInfos.Add(new SkuInfo(CurrentDbContext)
                                {
                                    Sku = newSku
                                });
                                if (!success)
                                {
                                    _warnings.Add(new WorkerWarning
                                    {
                                        LineData     = currentRecord.ToString(),
                                        ErrorMessage = Properties.Resources.EnrichmentImageFileNotPresentWarningMessage
                                    });
                                }
                            }

                            if (!string.IsNullOrEmpty(currentRecord.DisplayOrder) && !int.TryParse(currentRecord.DisplayOrder, out displayOrder))
                            {
                                _warnings.Add(new WorkerWarning()
                                {
                                    LineData = currentRecord.ToString(), ErrorMessage = Properties.Resources.DisplayOrderNotValidNumberWarningMessage
                                });
                                continue;
                            }
                        }


                        // if specific value record exists in this schema, get it, otherwise create it.
                        //var lov = sch.ListOfValues.FirstOrDefault(v => v.Value.ToLower() == currentRecord.Lov.ToLower() && v.Active);

                        if (lov == null)
                        {
                            if (CurrentImportOptions.HasFlag(ImportOptions.CreateMissingLOVs))
                            {
                                sch.ListOfValues.Add(entity: new ListOfValue(CurrentDbContext)
                                {
                                    Value           = currentRecord.Lov,
                                    EnrichmentImage = enrichmentImageGuid,
                                    EnrichmentCopy  = currentRecord.EnrichmentCopy,
                                    DisplayOrder    = int.TryParse(currentRecord.DisplayOrder, out displayOrder) ? displayOrder : (int?)null,
                                    CreatedOn       = DateTime.Now,
                                    CreatedBy       = ImportRequestedBy
                                });
                                newValueCount++;
                            }
                            else
                            {
                                _warnings.Add(new WorkerWarning
                                {
                                    LineData     = currentRecord.ToString(),
                                    ErrorMessage = Properties.Resources.CreateLovFlagOffWarningMessage
                                });
                                ProcessSummaryReport(0);
                            }
                        }
                        else
                        {
                            if (lov.Value == currentRecord.Lov && lov.EnrichmentCopy == currentRecord.EnrichmentCopy &&
                                lov.EnrichmentImage == currentRecord.EnrichmentImage && lov.DisplayOrder.ToString() == currentRecord.DisplayOrder)
                            {
                                ignoredCount++;
                                continue;
                            }
                            var updatedFlag = false;
                            if (!string.IsNullOrEmpty(enrichmentImageGuid))
                            {
                                lov.EnrichmentImage = enrichmentImageGuid;
                                updatedFlag         = true;
                            }
                            if (!string.IsNullOrEmpty(currentRecord.EnrichmentCopy))
                            {
                                lov.EnrichmentCopy = currentRecord.EnrichmentCopy;
                                updatedFlag        = true;
                            }
                            if (!string.IsNullOrEmpty(currentRecord.DisplayOrder))
                            {
                                lov.DisplayOrder = int.TryParse(currentRecord.DisplayOrder, out displayOrder)
                                                       ? displayOrder
                                                       : (int?)null;
                                updatedFlag = true;
                            }
                            if (updatedFlag)
                            {
                                lov.CreatedBy = ImportRequestedBy;
                                updatedCount++;
                                lov.CreatedOn = DateTime.Now;
                            }
                            else
                            {
                                ignoredCount++;
                            }
                        }
                    }
                    SaveDataChanges();
                    ProcessSummaryReport(newValueCount, updatedCount, ignoredCount);
                }
            }
            catch (IndexOutOfRangeException ex)
            {
                var newException = new Exception(Properties.Resources.InvalidRowInInputFileMessage, ex);
                Summary.SetError(newException);
            }
            catch (Exception ex)
            {
                Summary.SetError(ex);
            }
        }
コード例 #43
0
        public virtual async Task <SchemaInfo> GetSchemaInfoAsync(SchemaInfoFilter filter = null)
        {
            if (filter == null)
            {
                filter = new SchemaInfoFilter();
            }

            this.FeedbackInfo("Getting schema info...");

            DatabaseObjectType dbObjectType = filter.DatabaseObjectType;

            SchemaInfo schemaInfo = new SchemaInfo();

            using (DbConnection connection = this.CreateConnection())
            {
                if (this.NeedFetchObjects(DatabaseObjectType.UserDefinedType, filter.UserDefinedTypeNames, filter))
                {
                    schemaInfo.UserDefinedTypes = await this.GetUserDefinedTypesAsync(connection, filter);
                }

                if (this.NeedFetchObjects(DatabaseObjectType.Function, filter.FunctionNames, filter))
                {
                    schemaInfo.Functions = await this.GetFunctionsAsync(connection, filter);
                }

                if (this.NeedFetchObjects(DatabaseObjectType.Table, filter.TableNames, filter))
                {
                    schemaInfo.Tables = await this.GetTablesAsync(connection, filter);
                }

                if (this.NeedFetchObjects(DatabaseObjectType.View, filter.ViewNames, filter))
                {
                    schemaInfo.Views = await this.GetViewsAsync(connection, filter);
                }

                if (this.NeedFetchObjects(DatabaseObjectType.Procedure, filter.ProcedureNames, filter))
                {
                    schemaInfo.Procedures = await this.GetProceduresAsync(connection, filter);
                }

                if (this.NeedFetchTableObjects(DatabaseObjectType.TableColumn, filter, null))
                {
                    schemaInfo.TableColumns = await this.GetTableColumnsAsync(connection, filter);
                }

                if (this.NeedFetchTableObjects(DatabaseObjectType.TablePrimaryKey, filter, null))
                {
                    schemaInfo.TablePrimaryKeys = await this.GetTablePrimaryKeysAsync(connection, filter);
                }

                if ((this.Option.SortObjectsByReference && schemaInfo.Tables.Count > 1) || this.NeedFetchTableObjects(DatabaseObjectType.TableForeignKey, filter, null))
                {
                    schemaInfo.TableForeignKeys = await this.GetTableForeignKeysAsync(connection, filter);
                }

                if (this.NeedFetchTableObjects(DatabaseObjectType.TableIndex, filter, null))
                {
                    schemaInfo.TableIndexes = await this.GetTableIndexesAsync(connection, filter, this.Option.IncludePrimaryKeyWhenGetTableIndex);
                }

                if (this.NeedFetchTableObjects(DatabaseObjectType.TableConstraint, filter, null))
                {
                    schemaInfo.TableConstraints = await this.GetTableConstraintsAsync(connection, filter);
                }

                if (this.NeedFetchTableObjects(DatabaseObjectType.TableTrigger, filter, filter.TableTriggerNames))
                {
                    schemaInfo.TableTriggers = await this.GetTableTriggersAsync(connection, filter);
                }
            }

            if (this.Option.SortObjectsByReference)
            {
                if (schemaInfo.Tables.Count > 1)
                {
                    schemaInfo.Tables = TableReferenceHelper.ResortTables(schemaInfo.Tables, schemaInfo.TableForeignKeys);
                }

                DbObjectHelper.Resort(schemaInfo.Views);
                DbObjectHelper.Resort(schemaInfo.Functions);
                DbObjectHelper.Resort(schemaInfo.Procedures);
            }

            this.FeedbackInfo("End get schema info.");

            return(schemaInfo);
        }
コード例 #44
0
        public DataSet GetUserPermissions(string userValue, string appCodeName, UserValueType userValueType, RightMaskType rightMask, DelegationMaskType delegationMask)
        {
            string[] schemaTypes = SchemaInfo.FilterByCategory("Roles").ToSchemaNames();
            string[] userIDs     = OGUReaderService.SplitObjectValues(userValue);

            SCObjectAndRelationCollection users = OGUReaderService.GetSearchAdapter(GetSearchOUIDType(userValueType), SchemaInfo.FilterByCategory("Users").ToSchemaNames(), userIDs, false).QueryObjectsAndRelations();

            SchemaObjectCollection roles = SCSnapshotAdapter.Instance.QueryUserBelongToPermissions(schemaTypes, appCodeName, users.ToIDArray(), false, DateTime.MinValue);

            DataSet ds = new DataSet();

            ds.Tables.Add(QueryHelper.GetAppObjectTableBuilder(schemaTypes).Convert(roles));

            return(ds);
        }
コード例 #45
0
ファイル: XmlLoader.cs プロジェクト: Potapy4/dotnet-wcf
        private void LoadDocumentType(IDtdInfo dtdInfo, XmlDocumentType dtNode)
        {
            SchemaInfo schInfo = dtdInfo as SchemaInfo;

            if (schInfo == null)
            {
                throw new XmlException(ResXml.Xml_InternalError, string.Empty);
            }

            dtNode.DtdSchemaInfo = schInfo;
            if (schInfo != null)
            {
                //set the schema information into the document
                _doc.DtdSchemaInfo = schInfo;

                // Notation hashtable
                if (schInfo.Notations != null)
                {
                    foreach (SchemaNotation scNot in schInfo.Notations.Values)
                    {
                        dtNode.Notations.SetNamedItem(new XmlNotation(scNot.Name.Name, scNot.Pubid, scNot.SystemLiteral, _doc));
                    }
                }

                // Entity hashtables
                if (schInfo.GeneralEntities != null)
                {
                    foreach (SchemaEntity scEnt in schInfo.GeneralEntities.Values)
                    {
                        XmlEntity ent = new XmlEntity(scEnt.Name.Name, scEnt.Text, scEnt.Pubid, scEnt.Url, scEnt.NData.IsEmpty ? null : scEnt.NData.Name, _doc);
                        ent.SetBaseURI(scEnt.DeclaredURI);
                        dtNode.Entities.SetNamedItem(ent);
                    }
                }

                if (schInfo.ParameterEntities != null)
                {
                    foreach (SchemaEntity scEnt in schInfo.ParameterEntities.Values)
                    {
                        XmlEntity ent = new XmlEntity(scEnt.Name.Name, scEnt.Text, scEnt.Pubid, scEnt.Url, scEnt.NData.IsEmpty ? null : scEnt.NData.Name, _doc);
                        ent.SetBaseURI(scEnt.DeclaredURI);
                        dtNode.Entities.SetNamedItem(ent);
                    }
                }
                _doc.Entities = dtNode.Entities;

                //extract the elements which has attribute defined as ID from the element declarations
                IDictionaryEnumerator elementDecls = schInfo.ElementDecls.GetEnumerator();
                if (elementDecls != null)
                {
                    elementDecls.Reset();
                    while (elementDecls.MoveNext())
                    {
                        SchemaElementDecl elementDecl = (SchemaElementDecl)elementDecls.Value;
                        if (elementDecl.AttDefs != null)
                        {
                            IDictionaryEnumerator attDefs = elementDecl.AttDefs.GetEnumerator();
                            while (attDefs.MoveNext())
                            {
                                SchemaAttDef attdef = (SchemaAttDef)attDefs.Value;
                                if (attdef.Datatype.TokenizedType == XmlTokenizedType.ID)
                                {
                                    //we only register the XmlElement based on their Prefix/LocalName and skip the namespace
                                    _doc.AddIdInfo(
                                        _doc.AddXmlName(elementDecl.Prefix, elementDecl.Name.Name, string.Empty, null),
                                        _doc.AddAttrXmlName(attdef.Prefix, attdef.Name.Name, string.Empty, null));
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
コード例 #46
0
 public abstract IDataReader LoadMatchingPrimaryKeys(SchemaInfo schemaInfo, ClassInfo classInfo, SoodaWhereClause whereClause, SoodaOrderBy orderBy, int startIdx, int pageCount);
コード例 #47
0
ファイル: XmlSchema.cs プロジェクト: uQr/referencesource
 public void Compile(ValidationEventHandler validationEventHandler) {
     SchemaInfo sInfo = new SchemaInfo();
     sInfo.SchemaType = SchemaType.XSD;
     CompileSchema(null, System.Xml.XmlConfiguration.XmlReaderSection.CreateDefaultResolver(), sInfo, null, validationEventHandler, NameTable, false);
 }
コード例 #48
0
 public abstract IDataReader LoadObjectList(SchemaInfo schemaInfo, ClassInfo classInfo, SoodaWhereClause whereClause, SoodaOrderBy orderBy, int startIdx, int pageCount, SoodaSnapshotOptions options, out TableInfo[] tables);
コード例 #49
0
ファイル: XmlSchema.cs プロジェクト: uQr/referencesource
#pragma warning disable 618
        internal bool CompileSchema(XmlSchemaCollection xsc, XmlResolver resolver, SchemaInfo schemaInfo, string ns, ValidationEventHandler validationEventHandler, XmlNameTable nameTable, bool CompileContentModel) {

            //Need to lock here to prevent multi-threading problems when same schema is added to set and compiled
            lock (this) {
                //Preprocessing
                SchemaCollectionPreprocessor prep = new SchemaCollectionPreprocessor(nameTable, null, validationEventHandler);
                prep.XmlResolver = resolver;
                if (!prep.Execute(this, ns, true, xsc)) {
                    return false;
                }
            
                //Compilation
                SchemaCollectionCompiler compiler = new SchemaCollectionCompiler(nameTable, validationEventHandler);
                isCompiled = compiler.Execute(this, schemaInfo, CompileContentModel);
                this.SetIsCompiled(isCompiled);
                //
                return isCompiled;
            }
        }
コード例 #50
0
 public abstract IDataReader LoadRefObjectList(SchemaInfo schemaInfo, RelationInfo relationInfo, int masterColumn, object masterValue, out TableInfo[] tables);
コード例 #51
0
        public void Load(IDataReader dr, bool acceptChanges, ISchemaTableReader schemaReader)
        {
            if (null == schemaReader)
                throw new ArgumentNullException("schemaReader");

            this.schemaList.MakeMutable();
            this.schemaList.Clear();
            if (!this.records.IsReadOnly)
            {
                this.records.Clear();
                this.records.MakeReadOnly();
            }
            this._template = null;

            DataTable schemaTable = dr.GetSchemaTable();
            if (null == schemaTable)
                throw  new NullReferenceException("Table Schema can not be read");
            int fieldCount = dr.FieldCount;
            if (fieldCount > schemaTable.Rows.Count)
                throw new InvalidOperationException("Schema table does not contain all necessary fields");

            bool containsIdentity = schemaTable.Columns.OfType<DataColumn>().FirstOrDefault(c => String.Equals("IsIdentity", c.ColumnName)) != null;

            IEnumerable<DataRow> rows = schemaTable.Rows.OfType<DataRow>();
            string[] columnNames = new string[fieldCount];
            for (int j = 0; j < fieldCount; ++j)
            {
                string columnName = dr.GetName(j);
                columnNames[j] = columnName;

                DataRow schemaRow = rows.FirstOrDefault(r => String.Equals(columnName, (String)r["ColumnName"]));
                if (schemaRow != null)
                {
                    if (schemaReader.IsMapped(schemaRow))
                    {
                        SchemaInfo schema = new SchemaInfo(columnName);
                        schema.IsNullable = schemaReader.AllowDBNull(schemaRow);
                        schema.DataType = schemaReader.GetDataType(schemaRow);
                        schema.IsKey = schemaReader.IsKey(schemaRow);
                        schema.MaxLength = schemaReader.GetMaxLength(schemaRow);
                        schema.ReadOnly = schemaReader.IsReadOnly(schemaRow);
                        if (containsIdentity && schemaReader.IsIdentity(schemaRow))
                            schema.DatabaseGeneratedOption = StoreGeneratedPattern.Identity;
                        schema.Order = j;


                        this.schemaList.Add(schema);
                    }
                }
                else
                    throw new NotFoundException("Column not found; {0} ", columnName);
            }
            this.Init();//Hiç Kayıt Yoksa Template oluşturulmuyor.
            while (dr.Read())
            {
                Record newRecord = this.NewRecordInternal();//Template Type oluşturuldu. SchemaInfoCollection ReadOnly
                for (int j = 0; j < fieldCount; ++j)
                {
                    object dbValue = dr[j];

                    if (dr.IsDBNull(j))
                        dbValue = null;

                    SchemaInfo schema = this.schemaList[j];
                    string columnName = schema.ColumnName;
                    ICell cell = newRecord.GetCell(ref columnName);
                    cell.SetValueUnsafe(dbValue);
                    //Yeni oluşan record. PropertyChanged e gerek yok.
                }

                this.SetRecordID(newRecord);

                this.records.Add(newRecord);
            }

            if (acceptChanges)
                this.AcceptChanges();
        }
コード例 #52
0
 public abstract IDataReader ExecuteQuery(Sooda.QL.SoqlQueryExpression query, SchemaInfo schema, params object[] parameters);
コード例 #53
0
        // TODO: move this elsewhere
        public static void CreateSystemSchema(this ITransaction transaction)
        {
            transaction.CreateSystem();

            // TODO: get the configured default culture...
            var culture = CultureInfo.CurrentCulture.Name;
            var schemaInfo = new SchemaInfo(SystemSchema.Name, SchemaTypes.System);
            schemaInfo.Culture = culture;

            transaction.CreateSchema(schemaInfo);
        }
コード例 #54
0
 public IDataReader ExecuteQuery(Sooda.QL.SoqlQueryExpression queryText, SchemaInfo schema, ArrayList parameters)
 {
     return(ExecuteQuery(queryText, schema, parameters.ToArray()));
 }