public void BuildManifestSchemaNull()
 {
     var executor = Substitute.For<IExecutor>();
     var statements = Substitute.For<IStatements>();
     var dl = new SchemaReader(executor, statements);
     dl.BuildManifest(new List<Definition>(), null);
 }
        /// <summary>
        /// Serialize a message. (See <see cref="IAsyncSerializer{T}.SerializeAsync(T, SerializationContext)" />.)
        /// </summary>
        public virtual async Task <byte[]> SerializeAsync(T data, SerializationContext context)
        {
            var serialize = await(_cache.GetOrAdd(SubjectNameBuilder(context), async subject =>
            {
                int id;
                Action <T, Stream> @delegate;

                try
                {
                    var existing = await _resolve(subject).ConfigureAwait(false);
                    var schema   = SchemaReader.Read(existing.SchemaString);

                    @delegate = SerializerBuilder.BuildDelegate <T>(schema);
                    id        = existing.Id;
                }
                catch (Exception e) when(RegisterAutomatically && (
                                             (e is SchemaRegistryException sre && sre.ErrorCode == 40401) ||
                                             (e is AggregateException a && a.InnerExceptions.All(i =>
                                                                                                 i is UnsupportedSchemaException ||
                                                                                                 i is UnsupportedTypeException
                                                                                                 ))
                                             ))
                {
                    var schema = SchemaBuilder.BuildSchema <T>();
                    var json   = SchemaWriter.Write(schema);

                    @delegate = SerializerBuilder.BuildDelegate <T>(schema);
                    id        = await _register(subject, json).ConfigureAwait(false);
                }

                var bytes = BitConverter.GetBytes(id);

                if (BitConverter.IsLittleEndian)
                {
                    Array.Reverse(bytes);
                }

                return(value =>
                {
                    var stream = new MemoryStream();

                    using (stream)
                    {
                        stream.WriteByte(0x00);
                        stream.Write(bytes, 0, bytes.Length);

                        @delegate(value, stream);
                    }

                    return stream.ToArray();
                });
            })).ConfigureAwait(false);

            return(serialize(data));
        }
예제 #3
0
        private ExportResult Import(ISheet sheet, string dataFilePath)
        {
            Schema schema = SchemaReader.ReadSchema(sheet, setting.headModel);

            if (dataFormat != DataFormat.None)
            {
                ImportData(sheet, schema, dataFilePath);
            }

            return(ExportResult.Success);
        }
예제 #4
0
        public void SerializerTestModelOperationReturnTypeWithDuplicateFacets()
        {
            var       csdls = ModelBuilder.OperationReturnTypeWithDuplicateFacets();
            IEdmModel edmModel;
            IEnumerable <EdmError> errors;
            var isParsed = SchemaReader.TryParse(csdls.Select(e => e.CreateReader()), out edmModel, out errors);

            Assert.AreEqual(2, errors.Count(), "Expecting errors.");
            Assert.AreEqual(EdmErrorCode.UnexpectedXmlAttribute, errors.ElementAt(0).ErrorCode, "Invalid error code.");
            Assert.AreEqual(EdmErrorCode.UnexpectedXmlAttribute, errors.ElementAt(1).ErrorCode, "Invalid error code.");
        }
        public async Task LoadSprocs()
        {
            var dl = new SchemaReader(connectionString);
            var manifest = await dl.Load(SchemaTypes.StoredProcedure);

            Assert.IsNotNull(manifest);
            Assert.AreEqual(1, manifest.Count());
            var manyTypes = manifest.FirstOrDefault();
            Assert.IsNotNull(manyTypes);
            Assert.AreEqual(16, manyTypes.Variables.Count());
        }
예제 #6
0
        public IFCReader(string filePath, SchemaReader schema)
        {
            SchemaReader = schema;
            Header       = new List <IFCHeader>();
            ReplaceTable = new List <IFCReplaceRecord>();
            InverseTable = new List <IFCInverseRecord>();
            Dictionary <string, IFCObject> dist = CombineIFC(SplitIFCFile(filePath));

            InsertObjs = dist.Values.ToList();
            FindInverseData(dist);
        }
예제 #7
0
        static MeasuresHelpers()
        {
            using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("ODataSamples.Services.Core.Vocabularies.MeasuresVocabularies.xml"))
            {
                IEnumerable <EdmError> errors;
                SchemaReader.TryParse(new[] { XmlReader.Create(stream) }, out Instance, out errors);
            }

            ISOCurrencyTerm = Instance.FindDeclaredTerm(MeasuresISOCurrency);
            ScaleTerm       = Instance.FindDeclaredTerm(MeasuresScale);
        }
예제 #8
0
        public void CanReadSchema(string fileNameStem, JsonSchema expected)
        {
            JsonSchema actual;

            using (var reader = new StreamReader(TestUtil.GetTestDataStream(fileNameStem)))
            {
                actual = SchemaReader.ReadSchema(reader, TestUtil.GetTestDataFilePath(fileNameStem));
            }

            actual.Should().Be(expected);
        }
예제 #9
0
        public void LocateEntityContainer()
        {
            const string csdl =
                @"<?xml version=""1.0"" encoding=""utf-16""?>
<Schema Namespace=""Hot"" Alias=""Fuzz"" xmlns=""http://docs.oasis-open.org/odata/ns/edm"">
  <EntityType Name=""Person"">
    <Key>
      <PropertyRef Name=""Id"" />
    </Key>
    <Property Name=""Id"" Type=""Int32"" Nullable=""false"" />
    <Property Name=""Address"" Type=""String"" MaxLength=""100"" />
  </EntityType>
  <EntityType Name=""Pet"">
    <Key>
      <PropertyRef Name=""PetId"" />
    </Key>
    <Property Name=""Id"" Type=""Int32"" Nullable=""false"" />
    <Property Name=""OwnerId"" Type=""Int32"" Nullable=""false"" />
  </EntityType>
  <EntityContainer Name=""Wild"">
    <EntitySet Name=""People"" EntityType=""Hot.Person"" />
    <EntitySet Name=""Pets"" EntityType=""Hot.Pet"" />
  </EntityContainer>
</Schema>";

            IEdmModel model;
            IEnumerable <EdmError> errors;
            bool parsed = SchemaReader.TryParse(new XmlReader[] { XmlReader.Create(new StringReader(csdl)) }, out model, out errors);

            Assert.IsTrue(parsed, "parsed");
            Assert.IsTrue(errors.Count() == 0, "No errors");

            IEdmEntityType person        = (IEdmEntityType)model.FindType("Hot.Person");
            IEdmProperty   personId      = person.FindProperty("Id");
            IEdmProperty   personAddress = person.FindProperty("Address");
            IEdmEntityType pet           = (IEdmEntityType)model.FindType("Hot.Pet");
            IEdmProperty   petId         = pet.FindProperty("Id");
            IEdmProperty   ownerId       = pet.FindProperty("OwnerId");

            IEdmEntityContainer wild   = model.EntityContainer;
            IEdmEntitySet       people = model.EntityContainer.FindEntitySet("People");
            IEdmEntitySet       pets   = model.EntityContainer.FindEntitySet("Pets");

            AssertCorrectLocation((CsdlLocation)person.Location(), csdl, @"EntityType Name=""Person""");
            AssertCorrectLocation((CsdlLocation)personId.Location(), csdl, @"Property Name=""Id"" Type=""Int32"" Nullable=""false""");
            AssertCorrectLocation((CsdlLocation)personAddress.Location(), csdl, @"Property Name=""Address"" Type=""String"" MaxLength=""100"" ");
            AssertCorrectLocation((CsdlLocation)pet.Location(), csdl, @"EntityType Name=""Pet""");
            AssertCorrectLocation((CsdlLocation)petId.Location(), csdl, @"Property Name=""Id"" Type=""Int32"" Nullable=""false"" ");
            AssertCorrectLocation((CsdlLocation)ownerId.Location(), csdl, @"Property Name=""OwnerId"" Type=""Int32"" Nullable=""false"" ");
            AssertCorrectLocation((CsdlLocation)wild.Location(), csdl, @"EntityContainer Name=""Wild""");
            AssertCorrectLocation((CsdlLocation)people.Location(), csdl, @"EntitySet Name=""People"" EntityType=""Hot.Person"" ");
            AssertCorrectLocation((CsdlLocation)pets.Location(), csdl, @"EntitySet Name=""Pets"" EntityType=""Hot.Pet"" ");
        }
예제 #10
0
        /// <summary>
        ///     Opens the book asynchronously without reading its content. Holds the handle to the EPUB file.
        /// </summary>
        /// <param name="stream">Stream of file to be parsed</param>
        /// <returns></returns>
        private static async Task <EpubBookRef> OpenBookAsync(Stream stream)
        {
            var epubArchive = new ZipArchive(stream);
            var bookRef     = new EpubBookRef(epubArchive)
            {
                Schema = await SchemaReader.ReadSchemaAsync(epubArchive).ConfigureAwait(false)
            };

            bookRef.Title      = bookRef.Schema.Package.Metadata.Titles.FirstOrDefault() ?? string.Empty;
            bookRef.AuthorList = bookRef.Schema.Package.Metadata.Creators.Select(creator => creator.Creator).ToList();
            bookRef.Content    = ContentReader.ParseContentMap(bookRef);
            return(bookRef);
        }
예제 #11
0
        public void ThrowsOnLogicallyInvalidSchema(LogicallyInvalidSchemaTestCase test)
        {
            Action action = () =>
            {
                using (var reader = new StringReader(test.SchemaText))
                {
                    SchemaReader.ReadSchema(reader, TestUtil.TestFilePath);
                }
            };

            action.Should().Throw <SchemaValidationException>()
            .Where(ex => LogicallyInvalidSchemaExceptionPredicate(ex, test));
        }
예제 #12
0
        public void AmbiguousOperationTest()
        {
            string csdl = @"
<Schema Namespace=""DefaultNamespace"" xmlns=""http://docs.oasis-open.org/odata/ns/edm"">
    <Term Name=""Annotation"" Type=""Edm.Int32"" />
    <EntityType Name=""Entity"" >
        <Key>
            <PropertyRef Name=""ID"" />
        </Key>
        <Property Name=""ID"" Type=""Edm.Int32"" Nullable=""False"" />
    </EntityType>
    <Function Name=""Function"">
        <Parameter Name=""Parameter"" Type=""Edm.String"" />
        <Parameter Name=""Parameter2"" Type=""Ref(DefaultNamespace.Entity)"" />
        <ReturnType Type=""Edm.Int32"" />
    </Function>
    <Function Name=""Function"">
        <Parameter Name=""Parameter"" Type=""Edm.String"" />
        <Parameter Name=""Parameter2"" Type=""Ref(DefaultNamespace.Entity)"" />
        <ReturnType Type=""Edm.Int32"" />
    </Function>
    <Function Name=""Function"">
        <Parameter Name=""Parameter"" Type=""Edm.String"" />
        <Parameter Name=""Parameter2"" Type=""Ref(DefaultNamespace.Entity)"" />
        <ReturnType Type=""Edm.Int32"" />
    </Function>
    <Annotations Target=""DefaultNamespace.Function(Edm.String, Ref(DefaultNamespace.Entity))"">
        <Annotation Term=""AnnotationNamespace.Annotation"">
            <Int>42</Int>
        </Annotation>
    </Annotations>
</Schema>";

            IEdmModel model;
            IEnumerable <EdmError> errors;
            bool parsed = SchemaReader.TryParse(new XmlReader[] { XmlReader.Create(new StringReader(csdl)) }, out model, out errors);

            Assert.IsTrue(parsed, "parsed");
            Assert.IsTrue(errors.Count() == 0, "No errors");

            IEdmVocabularyAnnotation annotation         = model.VocabularyAnnotations.First();
            IEdmOperation            firstOperation     = model.FindOperations("DefaultNamespace.Function").First();
            IEdmOperation            ambiguousOperation = annotation.Target as IEdmOperation;

            Assert.IsNotNull(ambiguousOperation, "Function not null");
            Assert.AreEqual(EdmSchemaElementKind.Function, ambiguousOperation.SchemaElementKind, "Correct schema element kind");
            Assert.IsNull(ambiguousOperation.ReturnType, "Null return type");
            Assert.AreEqual("DefaultNamespace", ambiguousOperation.Namespace, "Correct namespace");
            Assert.AreEqual(firstOperation.Parameters.First(), ambiguousOperation.Parameters.First(), "Function gets parameters from first function");
            Assert.AreEqual(firstOperation.FindParameter("Parameter"), ambiguousOperation.FindParameter("Parameter"), "Find parameter defers to first function");
        }
예제 #13
0
        public void DetectsInvalidSchema(string jsonText)
        {
            Action action = () =>
            {
                using (var reader = new StringReader(jsonText))
                {
                    SchemaReader.ReadSchema(reader, TestUtil.TestFilePath);
                }
            };

            action.Should().Throw <JsonSyntaxException>()
            .Where(ex => ex.JsonReaderException.LineNumber == 2 &&
                   ex.JsonReaderException.LinePosition == 9);
        }
예제 #14
0
        /// <summary>
        /// Reads edm model from resource file
        /// </summary>
        /// <param name="modelName">The name of resource file containing the model</param>
        /// <returns>Edm model</returns>
        private static IEdmModel ReadModelFromResources(string modelName)
        {
            IEdmModel model;
            IEnumerable <EdmError> errors;
            var  csdlStream  = new MemoryStream(ReadTestResource(modelName));
            bool parseResult = SchemaReader.TryParse(new[] { XmlReader.Create(csdlStream) }, out model, out errors);

            if (!parseResult)
            {
                throw new InvalidOperationException("Failed to load model : " + string.Join(Environment.NewLine, errors.Select(e => e.ErrorMessage)));
            }

            return(model);
        }
예제 #15
0
        /// <summary>
        /// Opens the book asynchronously without reading its content. Holds the handle to the EPUB file.
        /// </summary>
        /// <param name="stream">stream from the EPUB file</param>
        /// <returns></returns>
        public static async Task <EpubBookRef> OpenBookAsync(Stream stream)
        {
            ZipArchive  epubArchive = new ZipArchive(stream);
            EpubBookRef bookRef     = new EpubBookRef(epubArchive);

            bookRef.Schema = await SchemaReader.ReadSchemaAsync(epubArchive).ConfigureAwait(false);

            bookRef.Title      = bookRef.Schema.Package.Metadata.Titles.FirstOrDefault() ?? String.Empty;
            bookRef.AuthorList = bookRef.Schema.Package.Metadata.Creators.Select(creator => creator.Creator).ToList();
            bookRef.Author     = String.Join(", ", bookRef.AuthorList);
            bookRef.Content    = await Task.Run(() => ContentReader.ParseContentMap(bookRef)).ConfigureAwait(false);

            return(bookRef);
        }
예제 #16
0
        private static async Task GenerateEntities(string token, string path)
        {
            var url        = "https://api.github.com/graphql";
            var connection = new Connection(url, token);

            Console.WriteLine("Reading from " + url);
            var schema = await SchemaReader.ReadSchema(connection);

            foreach (var file in CodeGenerator.Generate(schema, "Octokit.GraphQL"))
            {
                Console.WriteLine("Writing " + file.FileName);
                File.WriteAllText(Path.Combine(path, file.FileName), file.Content);
            }
        }
        private static IEdmModel GetEdmModel()
        {
            const string schema = @"<?xml version=""1.0"" encoding=""utf-16""?>
<Schema Namespace=""NS"" xmlns=""http://docs.oasis-open.org/odata/ns/edm"">
  <EntityType Name=""Entity"">
    <Key>
      <PropertyRef Name=""Id"" />
    </Key>
    <Property Name=""Id"" Type=""Edm.Int32"" Nullable=""false"" />
  </EntityType>
  <EntityContainer Name=""Container"">
    <EntitySet Name=""Entities"" EntityType=""NS.Entity"" />
  </EntityContainer>
  <Annotations Target=""NS.Container"">
    <Annotation Term=""Org.OData.Authorization.V1.Authorizations"">
      <Collection>
        <Record Type=""Org.OData.Authorization.V1.OAuth2ClientCredentials"">
          <PropertyValue Property=""TokenUrl"" String=""http://TokenUrl"" />
          <PropertyValue Property=""RefreshUrl"" String=""http://RefreshUrl"" />
          <PropertyValue Property=""Name"" String=""OAuth2ClientCredentials Name"" />
          <PropertyValue Property=""Description"" String=""OAuth2ClientCredentials Description"" />
          <PropertyValue Property=""Scopes"">
            <Collection>
              <Record>
                 <PropertyValue Property=""Scope"" String=""Scope1"" />
                 <PropertyValue Property=""Grant"" String=""Grant1"" />
                 <PropertyValue Property=""Description"" String=""Description 1"" />
              </Record>
            </Collection>
          </PropertyValue>
        </Record>
        <Record Type=""Org.OData.Authorization.V1.Http"">
          <PropertyValue Property=""BearerFormat"" String=""Http BearerFormat"" />
          <PropertyValue Property=""Scheme"" String=""Http Scheme"" />
          <PropertyValue Property=""Name"" String=""Http Name"" />
          <PropertyValue Property=""Description"" String=""Http Description"" />
        </Record>
      </Collection>
    </Annotation>
  </Annotations>
</Schema>";

            IEdmModel parsedModel;
            IEnumerable <EdmError> errors;
            bool parsed = SchemaReader.TryParse(new XmlReader[] { XmlReader.Create(new StringReader(schema)) }, out parsedModel, out errors);

            Assert.True(parsed);
            return(parsedModel);
        }
예제 #18
0
        /// <inheritdoc />
        public virtual async Task <byte[]> SerializeAsync(T data, SerializationContext context)
        {
            var subject = SubjectNameBuilder(context);

            Task <Func <T, byte[]> > task;

            lock (cache)
            {
                if (!cache.TryGetValue(subject, out task) || task.IsFaulted)
                {
                    cache[subject] = task = ((Func <string, Task <Func <T, byte[]> > >)(async subject =>
                    {
                        switch (RegisterAutomatically)
                        {
                        case AutomaticRegistrationBehavior.Always:
                            var schema = SchemaBuilder.BuildSchema <T>();
                            var id = await RegistryClient.RegisterSchemaAsync(subject, new Schema(SchemaWriter.Write(schema), SchemaType.Avro)).ConfigureAwait(false);

                            return(Build(id, schema));

                        case AutomaticRegistrationBehavior.Never:
                            var registration = await RegistryClient.GetLatestSchemaAsync(subject).ConfigureAwait(false);

                            if (registration.SchemaType != SchemaType.Avro)
                            {
                                throw new UnsupportedSchemaException(null, $"The latest schema with subject {subject} is not an Avro schema.");
                            }

                            return(Build(registration.Id, SchemaReader.Read(registration.SchemaString)));

                        default:
                            throw new ArgumentOutOfRangeException(nameof(RegisterAutomatically));
                        }
                    }))(subject);
                }
            }

            var serialize = await task.ConfigureAwait(false);

            if (data == null && TombstoneBehavior != TombstoneBehavior.None)
            {
                if (context.Component == MessageComponentType.Value || TombstoneBehavior != TombstoneBehavior.Strict)
                {
                    return(null);
                }
            }

            return(serialize(data));
        }
예제 #19
0
        public void Tests(TestCase test)
        {
            JsonSchema schema = SchemaReader.ReadSchema(test.SchemaText, TestUtil.TestFilePath);
            var        target = new Validator(schema);

            Result[] results = target.Validate(test.InstanceText, TestUtil.TestFilePath);

            results.Length.Should().Be(test.ExpectedMessages.Length);

            List <string> actualMessages = results.Select(
                r => r.FormatForVisualStudio(
                    RuleFactory.GetRuleFromRuleId(r.RuleId))).ToList();

            actualMessages.Should().ContainInOrder(test.ExpectedMessages);
        }
예제 #20
0
        private void PerformSchemaValidation(
            string instanceText,
            string instanceFilePath,
            string schemaFilePath,
            IAnalysisLogger logger)
        {
            string     schemaText = FileSystem.ReadAllText(schemaFilePath);
            JsonSchema schema     = SchemaReader.ReadSchema(schemaText, schemaFilePath);

            var validator = new Validator(schema);

            Result[] results = validator.Validate(instanceText, instanceFilePath);

            ReportResults(results, logger);
        }
예제 #21
0
        /// <summary>
        /// Builds a serializer for the Confluent wire format.
        /// </summary>
        /// <typeparam name="T">
        /// The type to be deserialized.
        /// </typeparam>
        /// <param name="id">
        /// A schema ID to include in each serialized payload.
        /// </param>
        /// <param name="json">
        /// The schema to build the Avro serializer from.
        /// </param>
        /// <param name="tombstoneBehavior">
        /// The behavior of the serializer on tombstone records.
        /// </param>
        /// <returns>
        /// A <see cref="ISerializer{T}" /> based on <paramref name="json" />.
        /// </returns>
        protected virtual ISerializer <T> Build <T>(
            int id,
            string json,
            TombstoneBehavior tombstoneBehavior)
        {
            var schema = SchemaReader.Read(json);

            if (tombstoneBehavior != TombstoneBehavior.None)
            {
                if (default(T) != null)
                {
                    throw new UnsupportedTypeException(typeof(T), $"{typeof(T)} cannot represent tombstone values.");
                }

                var hasNull = schema is Abstract.NullSchema ||
                              (schema is Abstract.UnionSchema union && union.Schemas.Any(s => s is Abstract.NullSchema));

                if (tombstoneBehavior == TombstoneBehavior.Strict && hasNull)
                {
                    throw new UnsupportedSchemaException(schema, "Tombstone serialization is not supported for schemas that can represent null values.");
                }
            }

            var inner  = SerializerBuilder.BuildDelegateExpression <T>(schema);
            var stream = Expression.Parameter(typeof(Stream));
            var value  = inner.Parameters[0];

            var writerConstructor = inner.Parameters[1].Type
                                    .GetConstructor(new[] { stream.Type });

            if (schema is Abstract.BytesSchema)
            {
                inner = new WireFormatBytesSerializerRewriter(stream)
                        .VisitAndConvert(inner, GetType().Name);
            }

            return(new DelegateSerializer <T>(
                       Expression
                       .Lambda <DelegateSerializer <T> .Implementation>(
                           Expression.Invoke(
                               inner,
                               value,
                               Expression.New(writerConstructor, stream)),
                           new[] { value, stream })
                       .Compile(),
                       id,
                       tombstoneBehavior));
        }
예제 #22
0
        /// <summary>
        /// Saves the schema to file.
        /// </summary>
        /// <param name="path">The file path to save to. If null, the default path will be used.</param>
        public static void Save(string path = null)
        {
            if (string.IsNullOrEmpty(path))
            {
                path = Paths.Root + MySqlHelper.DbSchemaFile;
            }

            // Load the database settings
            var dbSettings = new DbConnectionSettings(Paths.Root + MySqlHelper.DbSettingsFile, true);

            // Get the schema
            var schema = new SchemaReader(dbSettings);

            // Save
            schema.Save(path);
        }
예제 #23
0
        static List <object> GetSchema(string connectionString, string providerName, string table)
        {
            SchemaReader  reader  = new SchemaReader(connectionString, providerName);
            DataTable     columns = reader.Columns(table);
            List <object> list    = new List <object>();

            foreach (DataColumn column in columns.Columns)
            {
                list.Add(new
                {
                    name = column.ColumnName,
                    type = GetSenchaType(column)
                });
            }
            return(list);
        }
예제 #24
0
        /// <summary>
        /// Loads a model from the resource.
        /// </summary>
        /// <param name="resourceAssembly">The assembly that stores the resource.</param>
        /// <param name="name">The name of the resource file to load.</param>
        /// <param name="references">The model references to add.</param>
        /// <returns>The loaded model.</returns>
        public static IEdmModel LoadModelFromResource(Assembly resourceAssembly, string name, params IEdmModel[] references)
        {
            Stream modelStream = resourceAssembly.GetManifestResourceStream(name);

            using (XmlReader reader = XmlReader.Create(modelStream))
            {
                IEdmModel model;
                IEnumerable <EdmError> errors;
                if (!SchemaReader.TryParse(new XmlReader[] { reader }, references, out model, out errors))
                {
                    throw new AssertionFailedException("Model loading failed: " + string.Join("\r\n", errors.Select(e => e.ErrorLocation.ToString() + ": " + e.ErrorMessage)));
                }

                return(model);
            }
        }
예제 #25
0
        /// <summary>
        /// Parse Validation Vocabulary Model from ValidationVocabularies.xml
        /// </summary>
        static ValidationVocabularyModel()
        {
            Assembly assembly = typeof(ValidationVocabularyModel).GetAssembly();

            // Resource name has leading namespace and folder in .NetStandard dll.
            string[] allResources           = assembly.GetManifestResourceNames();
            string   validationVocabularies = allResources.Where(x => x.Contains("ValidationVocabularies.xml")).FirstOrDefault();

            Debug.Assert(validationVocabularies != null, "ValidationVocabularies.xml: not found.");

            using (Stream stream = assembly.GetManifestResourceStream(validationVocabularies))
            {
                IEnumerable <EdmError> errors;
                Debug.Assert(stream != null, "ValidationVocabularies.xml: stream!=null");
                SchemaReader.TryParse(new[] { XmlReader.Create(stream) }, out Instance, out errors);
            }
        }
예제 #26
0
        public void CsdlNamedTypeDefinitionToStringTest()
        {
            const string csdl =
                @"<?xml version=""1.0"" encoding=""utf-16""?>
<Schema Namespace=""AwesomeNamespace"" Alias=""Alias"" xmlns=""http://docs.oasis-open.org/odata/ns/edm"">
  <EntityType Name=""AstonishingEntity"">
    <Key>
      <PropertyRef Name=""Id"" />
    </Key>
    <Property Name=""Id"" Type=""Int32"" Nullable=""false"" />
  </EntityType>
  <EntityType Name=""AweInspiringEntity"">
    <Key>
      <PropertyRef Name=""Id"" />
    </Key>
    <Property Name=""Id"" Type=""Int32"" Nullable=""false"" />
    <Property Name=""AstonishingID"" Type=""Int32"" />
  </EntityType>
  <ComplexType Name=""BreathtakingComplex"">
    <Property Name=""Par1"" Type=""Int32"" Nullable=""false"" />
    <Property Name=""Par2"" Type=""Int32"" Nullable=""false"" />
  </ComplexType>
  <EnumType Name=""FabulousEnum"">
    <Member Name=""m1"" />
    <Member Name=""m2"" />
  </EnumType>
</Schema>";
            IEdmModel model;
            IEnumerable <EdmError> errors;
            bool parsed = SchemaReader.TryParse(new XmlReader[] { XmlReader.Create(new StringReader(csdl)) }, out model, out errors);

            Assert.IsTrue(parsed, "parsed");
            Assert.IsTrue(errors.Count() == 0, "No errors");

            IEdmEntityType    astonishing  = (IEdmEntityType)model.FindType("AwesomeNamespace.AstonishingEntity");
            IEdmEntityType    aweInspiring = (IEdmEntityType)model.FindType("AwesomeNamespace.AweInspiringEntity");
            IEdmComplexType   breathTaking = (IEdmComplexType)model.FindType("AwesomeNamespace.BreathtakingComplex");
            IEdmPrimitiveType primitive    = (IEdmPrimitiveType)astonishing.FindProperty("Id").Type.Definition;
            IEdmEnumType      fabulous     = (IEdmEnumType)model.FindType("AwesomeNamespace.FabulousEnum");

            Assert.AreEqual("AwesomeNamespace.AstonishingEntity", astonishing.ToString(), "To string correct");
            Assert.AreEqual("AwesomeNamespace.AweInspiringEntity", aweInspiring.ToString(), "To string correct");
            Assert.AreEqual("AwesomeNamespace.BreathtakingComplex", breathTaking.ToString(), "To string correct");
            Assert.AreEqual("Edm.Int32", primitive.ToString(), "To string correct");
            Assert.AreEqual("AwesomeNamespace.FabulousEnum", fabulous.ToString(), "To string correct");
        }
        public void GetConsoleCommandRequestReceivesCorrectCommand()
        {
            graphClientSub.RootEndpoint.Returns(new Uri("http://localhost:7474/db/data"));
            graphClientSub.ExecutionConfiguration.Returns(
                new ExecutionConfiguration {
                Username = "******", Password = "******"
            });
            IHttpManager  httpManger   = Substitute.For <IHttpManager>();
            ISchemaReader schemaReader = new SchemaReader(httpManger);

            httpManger.GetCommandResponse(null).Returns(string.Empty);
            const string expectedCommand = "{\"command\":\"schema\",\"engine\":\"shell\"}";

            schemaReader.GetSchemaTxt(graphClientSub);
            httpManger.Received()
            .GetConsoleCommandRequest(graphClientSub, Arg.Is <string>(s => string.Equals(s, expectedCommand)));
        }
예제 #28
0
        private ExportResult ExportSheet(ISheet sheet)
        {
            Schema schema = SchemaReader.ReadSchema(sheet, setting.headModel);

            schema.name = setting.FormatSheetName(sheet);

            if (codeFormat != CodeFomat.None)
            {
                GenerateCode(schema);
            }

            if (dataFormat != DataFormat.None)
            {
                ExportData(sheet, schema);
            }

            return(ExportResult.Success);
        }
        private IEdmModel GetEdmModel(string annotation)
        {
            const string template = @"<?xml version=""1.0"" encoding=""utf-16""?>
<Schema Namespace=""NS"" xmlns=""http://docs.oasis-open.org/odata/ns/edm"">
  <EntityContainer Name=""Container"">
   {0}
  </EntityContainer>
  <Term Name=""MyCustomParameter"" Type=""Org.OData.Capabilities.V1.CustomParameter"" />
</Schema>
";
            string       schema   = string.Format(template, annotation);

            IEdmModel model;
            bool      result = SchemaReader.TryParse(new XmlReader[] { XmlReader.Create(new StringReader(schema)) }, out model, out _);

            Assert.True(result);
            return(model);
        }
예제 #30
0
        public override int Run(string[] remainingArguments)
        {
            var results = SchemaReader.GetTables(connectionString.ToString());

            foreach (var table in results)
            {
                var className = (table.Schema + "." + table.Name).Replace(".", "_");

                var file = Path.Combine(Directory, className + ".cs");

                using (var stream = new FileStream(file, FileMode.Create))
                    using (var writer = new StreamWriter(stream, Encoding.UTF8))
                    {
                        writer.WriteLine("using System;");
                        writer.WriteLine();
                        writer.WriteLine("namespace " + Namespace);
                        writer.WriteLine("{");
                        writer.WriteLine("    public partial class " + className);
                        writer.WriteLine("    {");

                        foreach (var column in table.Columns)
                        {
                            SqlTypeInfo type;

                            if (!typeMapping.TryGetValue(column.Type, out type))
                            {
                                throw new Exception("Unable to convert SQL type to .NET type: " + column.Type);
                            }

                            if (column.PrimaryKeyPosition.HasValue)
                            {
                                writer.WriteLine("         [PrimaryKeyPosition({0})]", column.PrimaryKeyPosition.Value);
                            }

                            writer.WriteLine("         public {0} {1};", type.GetTypeExpression(column.IsNullable), column.Name);
                        }

                        writer.WriteLine("    }");
                        writer.WriteLine("}");
                    }
            }

            return(0);
        }
예제 #31
0
        /// <summary>
        /// Serialize a message. (See <see cref="IAsyncSerializer{T}.SerializeAsync(T, SerializationContext)" />.)
        /// </summary>
        public virtual async Task <byte[]> SerializeAsync(T data, SerializationContext context)
        {
            var subject = SubjectNameBuilder(context);

            Task <Func <T, byte[]> > task;

            lock (_cache)
            {
                if (!_cache.TryGetValue(subject, out task) || task.IsFaulted)
                {
                    _cache[subject] = task = ((Func <string, Task <Func <T, byte[]> > >)(async subject =>
                    {
                        switch (RegisterAutomatically)
                        {
                        case AutomaticRegistrationBehavior.Always:
                            var schema = SchemaBuilder.BuildSchema <T>();
                            var id = await _register(subject, SchemaWriter.Write(schema)).ConfigureAwait(false);

                            return(Build(id, schema));

                        case AutomaticRegistrationBehavior.Never:
                            var existing = await _resolve(subject).ConfigureAwait(false);

                            return(Build(existing.Id, SchemaReader.Read(existing.SchemaString)));

                        default:
                            throw new ArgumentOutOfRangeException(nameof(RegisterAutomatically));
                        }
                    }))(subject);
                }
            }

            var serialize = await task.ConfigureAwait(false);

            if (data == null && TombstoneBehavior != TombstoneBehavior.None)
            {
                if (context.Component == MessageComponentType.Value || TombstoneBehavior != TombstoneBehavior.Strict)
                {
                    return(null);
                }
            }

            return(serialize(data));
        }
        private static JsonSchema GetSarifSchema()
        {
            const string SarifSchemaResource = "Microsoft.CodeAnalysis.Sarif.Multitool.sarif-2.1.0.json";
            Assembly     thisAssembly        = typeof(FileWorkItemsCommand).Assembly;

            string sarifSchemaText;

            using (Stream sarifSchemaStream = thisAssembly.GetManifestResourceStream(SarifSchemaResource))
                using (var reader = new StreamReader(sarifSchemaStream))
                {
                    sarifSchemaText = reader.ReadToEnd();
                }

            // The second argument is a file path that the SchemaReader uses when reporting
            // errors. The SchemaReader does not attempt to access this file. Since we obtained
            // the schema from an embedded resource rather than from a file, we use the name
            // of the resource.
            return(SchemaReader.ReadSchema(sarifSchemaText, SarifSchemaResource));
        }
        public async Task LoadTable()
        {
            var dl = new SchemaReader(connectionString);
            var manifest = await dl.Load(SchemaTypes.Table);

            Assert.IsNotNull(manifest);
            Assert.AreEqual(2, manifest.Count());
            var table = (from m in manifest
                               where m.Preface == "dbo"
                               && m.Name == "LotsOfStuff"
                               select m).FirstOrDefault();
            Assert.IsNotNull(table);
            Assert.AreEqual(17, table.Variables.Count());
            var key = (from v in table.Variables
                       where v.IsPrimaryKey
                       select v).FirstOrDefault();
            Assert.IsNotNull(key);
            Assert.AreEqual("Id", key.ParameterName);
        }
        public async Task DualPrimaryKeys()
        {
            var dl = new SchemaReader(connectionString);
            var manifest = await dl.Load(SchemaTypes.Table);

            Assert.IsNotNull(manifest);
            Assert.AreEqual(2, manifest.Count());
            var table = (from m in manifest
                         where m.Preface == "dbo"
                         && m.Name == "DualPrimaryKeys"
                         select m).FirstOrDefault();
            Assert.IsNotNull(table);
            Assert.AreEqual(3, table.Variables.Count());
            var keys = from v in table.Variables
                       where v.IsPrimaryKey
                       select v;
            Assert.IsNotNull(keys);
            foreach (var key in keys)
            {
                Assert.IsTrue(key.ParameterName == "FirstId" || key.ParameterName == "SecondId");
            }
        }
        public async Task SchemasDefault()
        {
            var dl = new SchemaReader(connectionString);
            var data = await dl.Schemas();

            Assert.IsNotNull(data);
            Assert.AreEqual(16, data.Count());
        }
        public async Task SchemasSprocs()
        {
            var dl = new SchemaReader(connectionString);
            var data = await dl.Schemas(SchemaTypes.StoredProcedure);

            Assert.IsNotNull(data);
            Assert.AreEqual(16, data.Count());
        }
 public void MinimizeSchemaNull()
 {
     var executor = Substitute.For<IExecutor>();
     var statements = Substitute.For<IStatements>();
     var dl = new SchemaReader(executor, statements);
     dl.Minimize(null);
 }
 public void BuildManifestEmtpy()
 {
     var executor = Substitute.For<IExecutor>();
     var statements = Substitute.For<IStatements>();
     var dl = new SchemaReader(executor, statements);
     var returned = dl.BuildManifest(new List<Definition>(), new List<Schema>());
     Assert.IsNotNull(returned);
     Assert.AreEqual(0, returned.Count());
 }
 public static global::System.Xml.Schema.XmlSchemaComplexType GetTypedDataSetSchema(global::System.Xml.Schema.XmlSchemaSet xs) {
     SchemaReader ds = new SchemaReader();
     global::System.Xml.Schema.XmlSchemaComplexType type = new global::System.Xml.Schema.XmlSchemaComplexType();
     global::System.Xml.Schema.XmlSchemaSequence sequence = new global::System.Xml.Schema.XmlSchemaSequence();
     global::System.Xml.Schema.XmlSchemaAny any = new global::System.Xml.Schema.XmlSchemaAny();
     any.Namespace = ds.Namespace;
     sequence.Items.Add(any);
     type.Particle = sequence;
     global::System.Xml.Schema.XmlSchema dsSchema = ds.GetSchemaSerializable();
     if (xs.Contains(dsSchema.TargetNamespace)) {
         global::System.IO.MemoryStream s1 = new global::System.IO.MemoryStream();
         global::System.IO.MemoryStream s2 = new global::System.IO.MemoryStream();
         try {
             global::System.Xml.Schema.XmlSchema schema = null;
             dsSchema.Write(s1);
             for (global::System.Collections.IEnumerator schemas = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator(); schemas.MoveNext(); ) {
                 schema = ((global::System.Xml.Schema.XmlSchema)(schemas.Current));
                 s2.SetLength(0);
                 schema.Write(s2);
                 if ((s1.Length == s2.Length)) {
                     s1.Position = 0;
                     s2.Position = 0;
                     for (; ((s1.Position != s1.Length) 
                                 && (s1.ReadByte() == s2.ReadByte())); ) {
                         ;
                     }
                     if ((s1.Position == s1.Length)) {
                         return type;
                     }
                 }
             }
         }
         finally {
             if ((s1 != null)) {
                 s1.Close();
             }
             if ((s2 != null)) {
                 s2.Close();
             }
         }
     }
     xs.Add(dsSchema);
     return type;
 }
 public virtual int FillByAllChildTablesOnly(SchemaReader.ForeignRelationsDataTable dataTable, string TableName) {
     this.Adapter.SelectCommand = this.CommandCollection[2];
     if ((TableName == null)) {
         throw new global::System.ArgumentNullException("TableName");
     }
     else {
         this.Adapter.SelectCommand.Parameters[0].Value = ((string)(TableName));
     }
     if ((this.ClearBeforeFill == true)) {
         dataTable.Clear();
     }
     int returnValue = this.Adapter.Fill(dataTable);
     return returnValue;
 }
 public static global::System.Xml.Schema.XmlSchemaComplexType GetTypedTableSchema(global::System.Xml.Schema.XmlSchemaSet xs) {
     global::System.Xml.Schema.XmlSchemaComplexType type = new global::System.Xml.Schema.XmlSchemaComplexType();
     global::System.Xml.Schema.XmlSchemaSequence sequence = new global::System.Xml.Schema.XmlSchemaSequence();
     SchemaReader ds = new SchemaReader();
     global::System.Xml.Schema.XmlSchemaAny any1 = new global::System.Xml.Schema.XmlSchemaAny();
     any1.Namespace = "http://www.w3.org/2001/XMLSchema";
     any1.MinOccurs = new decimal(0);
     any1.MaxOccurs = decimal.MaxValue;
     any1.ProcessContents = global::System.Xml.Schema.XmlSchemaContentProcessing.Lax;
     sequence.Items.Add(any1);
     global::System.Xml.Schema.XmlSchemaAny any2 = new global::System.Xml.Schema.XmlSchemaAny();
     any2.Namespace = "urn:schemas-microsoft-com:xml-diffgram-v1";
     any2.MinOccurs = new decimal(1);
     any2.ProcessContents = global::System.Xml.Schema.XmlSchemaContentProcessing.Lax;
     sequence.Items.Add(any2);
     global::System.Xml.Schema.XmlSchemaAttribute attribute1 = new global::System.Xml.Schema.XmlSchemaAttribute();
     attribute1.Name = "namespace";
     attribute1.FixedValue = ds.Namespace;
     type.Attributes.Add(attribute1);
     global::System.Xml.Schema.XmlSchemaAttribute attribute2 = new global::System.Xml.Schema.XmlSchemaAttribute();
     attribute2.Name = "tableTypeName";
     attribute2.FixedValue = "EntitiesDataTable";
     type.Attributes.Add(attribute2);
     type.Particle = sequence;
     global::System.Xml.Schema.XmlSchema dsSchema = ds.GetSchemaSerializable();
     if (xs.Contains(dsSchema.TargetNamespace)) {
         global::System.IO.MemoryStream s1 = new global::System.IO.MemoryStream();
         global::System.IO.MemoryStream s2 = new global::System.IO.MemoryStream();
         try {
             global::System.Xml.Schema.XmlSchema schema = null;
             dsSchema.Write(s1);
             for (global::System.Collections.IEnumerator schemas = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator(); schemas.MoveNext(); ) {
                 schema = ((global::System.Xml.Schema.XmlSchema)(schemas.Current));
                 s2.SetLength(0);
                 schema.Write(s2);
                 if ((s1.Length == s2.Length)) {
                     s1.Position = 0;
                     s2.Position = 0;
                     for (; ((s1.Position != s1.Length) 
                                 && (s1.ReadByte() == s2.ReadByte())); ) {
                         ;
                     }
                     if ((s1.Position == s1.Length)) {
                         return type;
                     }
                 }
             }
         }
         finally {
             if ((s1 != null)) {
                 s1.Close();
             }
             if ((s2 != null)) {
                 s2.Close();
             }
         }
     }
     xs.Add(dsSchema);
     return type;
 }
        public void Minimize()
        {
            var schemas = new List<Schema>();
            var schema = new Schema()
            {
                Name = Guid.NewGuid().ToString(),
                Preface = Guid.NewGuid().ToString(),
            };

            schemas.AddRange(new[] { schema, schema, schema, schema });

            var executor = Substitute.For<IExecutor>();
            var statements = Substitute.For<IStatements>();
            var dl = new SchemaReader(executor, statements);
            var returned = dl.Minimize(schemas);

            Assert.IsNotNull(returned);
            Assert.AreEqual(1, returned.Count());
            var def = returned.FirstOrDefault();
            Assert.IsNotNull(def);
            Assert.AreEqual(schema.Name, def.Name);
            Assert.AreEqual(schema.Preface, def.Preface);
        }
        public async Task SchemasTable()
        {
            var dl = new SchemaReader(connectionString);
            var data = await dl.Schemas(SchemaTypes.Table);

            Assert.IsNotNull(data);
            Assert.AreEqual(20, data.Count());
        }
 public virtual int FillByConstraintName(SchemaReader.CONSTRAINT_COLUMN_USAGEDataTable dataTable, string ConstraintName) {
     this.Adapter.SelectCommand = this.CommandCollection[1];
     if ((ConstraintName == null)) {
         throw new global::System.ArgumentNullException("ConstraintName");
     }
     else {
         this.Adapter.SelectCommand.Parameters[0].Value = ((string)(ConstraintName));
     }
     if ((this.ClearBeforeFill == true)) {
         dataTable.Clear();
     }
     int returnValue = this.Adapter.Fill(dataTable);
     return returnValue;
 }
 public virtual int FillByTableName(SchemaReader.TABLE_CONSTRAINTSDataTable dataTable, string tableName) {
     this.Adapter.SelectCommand = this.CommandCollection[1];
     if ((tableName == null)) {
         this.Adapter.SelectCommand.Parameters[0].Value = global::System.DBNull.Value;
     }
     else {
         this.Adapter.SelectCommand.Parameters[0].Value = ((string)(tableName));
     }
     if ((this.ClearBeforeFill == true)) {
         dataTable.Clear();
     }
     int returnValue = this.Adapter.Fill(dataTable);
     return returnValue;
 }
 public virtual int FillContraints(SchemaReader.TABLE_CONSTRAINTSDataTable dataTable) {
     this.Adapter.SelectCommand = this.CommandCollection[0];
     if ((this.ClearBeforeFill == true)) {
         dataTable.Clear();
     }
     int returnValue = this.Adapter.Fill(dataTable);
     return returnValue;
 }
 public virtual int Fill(SchemaReader.EntitiesDataTable dataTable, bool includeTable, bool includeView, bool includeFK, string schmas) {
     this.Adapter.SelectCommand = this.CommandCollection[0];
     this.Adapter.SelectCommand.Parameters[0].Value = ((bool)(includeTable));
     this.Adapter.SelectCommand.Parameters[1].Value = ((bool)(includeView));
     this.Adapter.SelectCommand.Parameters[2].Value = ((bool)(includeFK));
     if ((schmas == null)) {
         throw new global::System.ArgumentNullException("schmas");
     }
     else {
         this.Adapter.SelectCommand.Parameters[3].Value = ((string)(schmas));
     }
     if ((this.ClearBeforeFill == true)) {
         dataTable.Clear();
     }
     int returnValue = this.Adapter.Fill(dataTable);
     return returnValue;
 }
 public virtual int Fill(SchemaReader.SCHEMATADataTable dataTable) {
     this.Adapter.SelectCommand = this.CommandCollection[0];
     if ((this.ClearBeforeFill == true)) {
         dataTable.Clear();
     }
     int returnValue = this.Adapter.Fill(dataTable);
     return returnValue;
 }
 public virtual int FillByTableName(SchemaReader.FieldDefinitionsDataTable dataTable, string tableName) {
     this.Adapter.SelectCommand = this.CommandCollection[1];
     if ((tableName == null)) {
         throw new global::System.ArgumentNullException("tableName");
     }
     else {
         this.Adapter.SelectCommand.Parameters[0].Value = ((string)(tableName));
     }
     if ((this.ClearBeforeFill == true)) {
         dataTable.Clear();
     }
     int returnValue = this.Adapter.Fill(dataTable);
     return returnValue;
 }
 public virtual int Fill(SchemaReader.DBObjPropertiesDataTable dataTable, string propName, string lvl1Type, string lvl1Name, string objType, string objName, string lvl3Type, string lvl3Name) {
     this.Adapter.SelectCommand = this.CommandCollection[0];
     if ((propName == null)) {
         this.Adapter.SelectCommand.Parameters[0].Value = global::System.DBNull.Value;
     }
     else {
         this.Adapter.SelectCommand.Parameters[0].Value = ((string)(propName));
     }
     if ((lvl1Type == null)) {
         this.Adapter.SelectCommand.Parameters[1].Value = global::System.DBNull.Value;
     }
     else {
         this.Adapter.SelectCommand.Parameters[1].Value = ((string)(lvl1Type));
     }
     if ((lvl1Name == null)) {
         this.Adapter.SelectCommand.Parameters[2].Value = global::System.DBNull.Value;
     }
     else {
         this.Adapter.SelectCommand.Parameters[2].Value = ((string)(lvl1Name));
     }
     if ((objType == null)) {
         this.Adapter.SelectCommand.Parameters[3].Value = global::System.DBNull.Value;
     }
     else {
         this.Adapter.SelectCommand.Parameters[3].Value = ((string)(objType));
     }
     if ((objName == null)) {
         this.Adapter.SelectCommand.Parameters[4].Value = global::System.DBNull.Value;
     }
     else {
         this.Adapter.SelectCommand.Parameters[4].Value = ((string)(objName));
     }
     if ((lvl3Type == null)) {
         this.Adapter.SelectCommand.Parameters[5].Value = global::System.DBNull.Value;
     }
     else {
         this.Adapter.SelectCommand.Parameters[5].Value = ((string)(lvl3Type));
     }
     if ((lvl3Name == null)) {
         this.Adapter.SelectCommand.Parameters[6].Value = global::System.DBNull.Value;
     }
     else {
         this.Adapter.SelectCommand.Parameters[6].Value = ((string)(lvl3Name));
     }
     if ((this.ClearBeforeFill == true)) {
         dataTable.Clear();
     }
     int returnValue = this.Adapter.Fill(dataTable);
     return returnValue;
 }
        public void BuildManifest()
        {
            var random = new Random();
            var defs = new List<Definition>();
            var schemas = new List<Schema>();
            var schema = new Schema()
            {
                Name = Guid.NewGuid().ToString(),
                Preface = Guid.NewGuid().ToString(),
            };
            var def = schema.Map<Definition>();
            defs.Add(def);

            var schemaCount = random.Next(15);
            for (var i = 0; i < schemaCount; i++)
            {
                var s = new Schema()
                {
                    Name = schema.Name,
                    Preface = schema.Preface,
                    DataType = Guid.NewGuid().ToString(),
                    ParameterName = Guid.NewGuid().ToString(),
                };
                schemas.Add(s);
            }
            var count = random.Next(15);
            for (var i = 0; i < count; i++)
            {
                var d = new Definition()
                {
                    Name = Guid.NewGuid().ToString(),
                    Preface = Guid.NewGuid().ToString(),
                };
                defs.Add(d);
            }

            var executor = Substitute.For<IExecutor>();
            var statements = Substitute.For<IStatements>();

            var dl = new SchemaReader(executor, statements);
            var manifest = dl.BuildManifest(defs, schemas);

            Assert.IsNotNull(manifest);
            Assert.AreEqual(count + 1, manifest.Count());
            var c = new DefinitionComparer();
            Assert.AreEqual(schemaCount, manifest.ElementAt(0).Variables.Count());
        }