Esempio n. 1
0
        public void LocateTypes()
        {
            const string csdl =
                @"<?xml version=""1.0"" encoding=""utf-16""?>
<Schema Namespace=""Grumble"" 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>
  <ComplexType Name=""Smod"">
    <Property Name=""Id"" Type=""Edm.Int32"" />
    <Property Name=""Collection"" Type=""Collection(Edm.Int32)"" />
    <Property Name=""ref"" Type=""Ref(Grumble.Person)"" />
  </ComplexType>
</Schema>";
            IEdmModel model;
            IEnumerable <EdmError> error;
            bool parsed = SchemaReader.TryParse(new XmlReader[] { XmlReader.Create(new StringReader(csdl)) }, out model, out error);

            Assert.IsTrue(parsed, "parsed");

            IEdmComplexType   complexType     = (IEdmComplexType)model.FindType("Grumble.Smod");
            IEdmTypeReference primitive       = complexType.FindProperty("Id").Type;
            IEdmTypeReference collection      = complexType.FindProperty("Collection").Type;
            IEdmTypeReference entityReference = complexType.FindProperty("ref").Type;

            AssertCorrectLocation((CsdlLocation)primitive.Location(), csdl, @"Property Name=""Id"" Type=""Edm.Int32"" ");
            AssertCorrectLocation((CsdlLocation)collection.Location(), csdl, @"Property Name=""Collection"" Type=""Collection(Edm.Int32)"" ");
            AssertCorrectLocation((CsdlLocation)entityReference.Location(), csdl, @"Property Name=""ref"" Type=""Ref(Grumble.Person)"" ");
        }
Esempio n. 2
0
        public void CsdlUnnamedTypeDefinitionToStringTest()
        {
            const string csdl =
                @"<?xml version=""1.0"" encoding=""utf-16""?>
<Schema Namespace=""Namespace"" 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>
  <Function Name=""Function1""><ReturnType Type=""Edm.Int32""/>
    <Parameter Name=""P1"" Type=""Collection(Edm.Int32)"" />
    <Parameter Name=""P2"" Type=""Ref(Namespace.AstonishingEntity)"" />
  </Function>
</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");

            IEdmOperation           operation  = (IEdmOperation)(model.FindOperations("Namespace.Function1")).First();
            IEdmCollectionType      collection = (IEdmCollectionType)operation.FindParameter("P1").Type.Definition;
            IEdmEntityReferenceType entityRef  = (IEdmEntityReferenceType)operation.FindParameter("P2").Type.Definition;

            Assert.AreEqual("Collection([Edm.Int32 Nullable=True])", collection.ToString(), "To string correct");
            Assert.AreEqual("EntityReference(Namespace.AstonishingEntity)", entityRef.ToString(), "To string correct");
        }
        static AlternateKeysVocabularyModel()
        {
            Assembly assembly = typeof(AlternateKeysVocabularyModel).GetAssembly();

            // Resource name has leading namespace and folder in .NetStandard dll.
            string[] allResources = assembly.GetManifestResourceNames();
            string alternateKeysVocabularies = allResources.Where(x => x.Contains("AlternateKeysVocabularies.xml")).FirstOrDefault();
            Debug.Assert(alternateKeysVocabularies != null, "AlternateKeysVocabularies.xml: not found.");

            using (Stream stream = assembly.GetManifestResourceStream(alternateKeysVocabularies))
            {
                IEnumerable<EdmError> errors;
                Debug.Assert(stream != null, "AlternateKeysVocabularies.xml: stream!=null");
                SchemaReader.TryParse(new[] { XmlReader.Create(stream) }, out Instance, out errors);
            }

            AlternateKeysTerm = Instance.FindDeclaredTerm(AlternateKeysVocabularyConstants.AlternateKeys);
            Debug.Assert(AlternateKeysTerm != null, "Expected Alternate Key term");

            AlternateKeyType = Instance.FindDeclaredType(AlternateKeysVocabularyConstants.AlternateKeyType) as IEdmComplexType;
            Debug.Assert(AlternateKeyType != null, "Expected Alternate Key type");

            PropertyRefType = Instance.FindDeclaredType(AlternateKeysVocabularyConstants.PropertyRefType) as IEdmComplexType;
            Debug.Assert(PropertyRefType != null, "Expected Alternate Key property ref type");
        }
        private static IEdmModel GetEdmModel(string schema)
        {
            bool parsed = SchemaReader.TryParse(new XmlReader[] { XmlReader.Create(new StringReader(schema)) }, out IEdmModel parsedModel, out IEnumerable <EdmError> errors);

            Assert.True(parsed, $"Parse failure. {string.Join(Environment.NewLine, errors.Select(e => e.ToString()))}");
            return(parsedModel);
        }
        private void BasicXsdValidationTestForParserInputCsdl(IEnumerable <XElement> csdls, EdmVersion edmVersion)
        {
            IEdmModel edmModel;
            IEnumerable <EdmError> parserErrors;
            var csdlsEdmVersionUpdated = csdls.Select(n => XElement.Parse(n.ToString().Replace(n.Name.NamespaceName, EdmLibCsdlContentGenerator.GetCsdlFullNamespace(edmVersion).NamespaceName)));

            var isParsed = SchemaReader.TryParse(csdlsEdmVersionUpdated.Select(e => e.CreateReader()), out edmModel, out parserErrors);

            if (!isParsed)
            {
                // XSD verification is a sufficent condition, but not a necessary condition of EDMLib parser.
                Assert.IsTrue(this.GetXsdValidationResults(csdlsEdmVersionUpdated, edmVersion).Count() > 0, "It should be invalid for the CSDL {0} XSDs", edmVersion);
            }
            else
            {
                IEnumerable <EdmError> validationErrors;
                edmModel.Validate(toProductVersionlookup[edmVersion], out validationErrors);
                var xsdValidationErrors = new List <string>();

                xsdValidationErrors.AddRange(this.GetXsdValidationResults(csdlsEdmVersionUpdated, edmVersion));

                if (!validationErrors.Any() && xsdValidationErrors.Any())
                {
                    Assert.Fail("XSD validation must succeed when there is no semantic validation error.");
                }
                else if (validationErrors.Any() && !xsdValidationErrors.Any())
                {
                    foreach (var validationError in validationErrors)
                    {
                        Console.WriteLine("The test data has no XSD error, but it has a validation error : {0}", validationError.ErrorMessage);
                    }
                }
            }
        }
Esempio n. 6
0
        public static new void InitializeService(DataServiceConfiguration config)
        {
            BaseService.InitializeService(config);

            config.AnnotationsBuilder =
                (model) =>
            {
                var xmlReaders = new XmlReader[] { XmlReader.Create(new StringReader(@"
                        <Schema xmlns=""http://docs.oasis-open.org/odata/ns/edm"" Namespace=""Microsoft.Test.OData.Services.ODataWriterService"" >
                            <Annotations Target=""Microsoft.Test.OData.Services.AstoriaDefaultService.Customer"">
                                <Annotation Term=""CustomInstanceAnnotations.Term1"" Bool=""true"" />
                            </Annotations>
                        </Schema>
                        ")) };

                IEdmModel annotationsModel;
                IEnumerable <EdmError> errors;
                bool parsed = SchemaReader.TryParse(xmlReaders, model, out annotationsModel, out errors);
                if (!parsed)
                {
                    throw new EdmParseException(errors);
                }

                return(new IEdmModel[] { annotationsModel });
            };
        }
        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"">
  <EntityContainer Name=""Container"">
    <Annotation Term=""Org.OData.Authorization.V1.Authorizations"">
      <Collection>
        <Record Type=""Org.OData.Authorization.V1.OpenIDConnect"">
          <PropertyValue Property=""IssuerUrl"" String=""http://any"" />
          <PropertyValue Property=""Name"" String=""OpenIDConnect Name"" />
          <PropertyValue Property=""Description"" String=""OpenIDConnect Description"" />
        </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"" />
        </Record>
      </Collection>
    </Annotation>
  </EntityContainer>
</Schema>";

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

            Assert.True(parsed);
            return(parsedModel);
        }
Esempio n. 8
0
        void VerifyResult(string[] inputText, string expectedResult, CsdlTarget target, Action <IEdmModel> visitModel)
        {
            IEdmModel model;
            IEnumerable <EdmError> errors;
            List <XmlReader>       readers = new List <XmlReader>();

            foreach (string s in inputText)
            {
                readers.Add(XmlReader.Create(new StringReader(s)));
            }
            bool parsed = SchemaReader.TryParse(readers, out model, out errors);

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

            if (visitModel != null)
            {
                visitModel(model);
            }

            StringWriter      sw       = new StringWriter();
            XmlWriterSettings settings = new XmlWriterSettings();

            settings.Indent   = true;
            settings.Encoding = System.Text.Encoding.UTF8;
            XmlWriter xw = XmlWriter.Create(sw, settings);

            CsdlWriter.TryWriteCsdl(model, xw, target, out errors);
            xw.Flush();
            xw.Close();
            string outputText = sw.ToString();

            Assert.AreEqual(expectedResult, outputText, "Expected Result = Output");
        }
Esempio n. 9
0
        static CoreVocabularyModel()
        {
            IsInitializing = true;
            Assembly assembly = typeof(CoreVocabularyModel).GetAssembly();

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

            Debug.Assert(coreVocabularies != null, "CoreVocabularies.xml: not found.");

            using (Stream stream = assembly.GetManifestResourceStream(coreVocabularies))
            {
                IEnumerable <EdmError> errors;
                Debug.Assert(stream != null, "CoreVocabularies.xml: stream!=null");
                SchemaReader.TryParse(new[] { XmlReader.Create(stream) }, out Instance, out errors);
                IsInitializing = false;
            }

            AcceptableMediaTypesTerm = Instance.FindDeclaredTerm(CoreVocabularyConstants.AcceptableMediaTypes);
            ComputedTerm             = Instance.FindDeclaredTerm(CoreVocabularyConstants.Computed);
            ConcurrencyTerm          = Instance.FindDeclaredTerm(CoreVocabularyConstants.OptimisticConcurrency);
            ConventionalIDsTerm      = Instance.FindDeclaredTerm(CoreVocabularyConstants.ConventionalIDs);
            DereferenceableIDsTerm   = Instance.FindDeclaredTerm(CoreVocabularyConstants.DereferenceableIDs);
            DescriptionTerm          = Instance.FindDeclaredTerm(CoreVocabularyConstants.Description);
            ImmutableTerm            = Instance.FindDeclaredTerm(CoreVocabularyConstants.Immutable);
            IsLanguageDependentTerm  = Instance.FindDeclaredTerm(CoreVocabularyConstants.IsLanguageDependent);
            IsMediaTypeTerm          = Instance.FindDeclaredTerm(CoreVocabularyConstants.IsMediaType);
            IsURLTerm           = Instance.FindDeclaredTerm(CoreVocabularyConstants.IsURL);
            LongDescriptionTerm = Instance.FindDeclaredTerm(CoreVocabularyConstants.LongDescription);
            MediaTypeTerm       = Instance.FindDeclaredTerm(CoreVocabularyConstants.MediaType);
            RequiresTypeTerm    = Instance.FindDeclaredTerm(CoreVocabularyConstants.RequiresType);
            ResourcePathTerm    = Instance.FindDeclaredTerm(CoreVocabularyConstants.ResourcePath);
            PermissionsTerm     = Instance.FindDeclaredTerm(CoreVocabularyConstants.Permissions);
        }
Esempio n. 10
0
        public void ParserTestForDifferentUnderlyingXmlReaders()
        {
            var csdl =
                @"<Schema Namespace=""DefaultNamespace"" xmlns=""http://docs.oasis-open.org/odata/ns/edm"">
      <Action Name=""FunctionImportsWithReturnTypePrimitiveDataType"">
        <Parameter Name=""PrimitiveParameter1"" Type=""Edm.Binary"" />
        <Parameter Name=""PrimitiveParameter2""><Foo /></Parameter>
      </Action>
      <EntityContainer Name=""MyContainer"">
        <ActionImport Name=""FunctionImportsWithReturnTypePrimitiveDataType"" Action=""DefaultNamespace.FunctionImportsWithReturnTypePrimitiveDataType"" />
      </EntityContainer>
</Schema>";
            IEdmModel model;
            IEnumerable <EdmError> errors;
            var  csdlElements = new XElement[] { XElement.Parse(csdl) };
            bool parsed       = SchemaReader.TryParse(new System.Xml.XmlReader[] { System.Xml.XmlReader.Create(new System.IO.StringReader(csdl)) }, out model, out errors);

            Assert.IsFalse(parsed, "parsed");
            Assert.AreEqual(2, errors.Count(), "2 errors");
            Assert.AreEqual(EdmErrorCode.UnexpectedXmlElement, errors.First().ErrorCode, "10: Unexpected Xml Element");

            parsed = SchemaReader.TryParse(new System.Xml.XmlReader[] { csdlElements.First().CreateReader() }, out model, out errors);
            Assert.IsFalse(parsed, "parsed");
            Assert.AreEqual(2, errors.Count(), "2 errors");
            Assert.AreEqual(EdmErrorCode.UnexpectedXmlElement, errors.First().ErrorCode, "10: Unexpected Xml Element");
        }
Esempio n. 11
0
        private IEdmModel DeSerializeCsdlsToModel(IEnumerable <XElement> csdls)
        {
            IEdmModel model;
            IEnumerable <EdmError> errors;
            var isParsed = SchemaReader.TryParse(csdls.Select(e => e.CreateReader()), out model, out errors);

            Assert.IsTrue(isParsed, "Error occurs while deserializing csdl to model");
            return(model);
        }
Esempio n. 12
0
        public void VocabularySerializingAnnotationTermsWithNoNamespace()
        {
            IEdmModel edmModel;
            IEnumerable <EdmError> errors;
            var isParsed = SchemaReader.TryParse(VocabularyTestModelBuilder.AnnotationTermsWithNoNamespace().Select(e => e.CreateReader()), out edmModel, out errors);

            Assert.IsFalse(isParsed, "SchemaReader.TryParse failed");
            Assert.IsFalse(errors.Count() == 0, "SchemaReader.TryParse returned errors");
        }
        private IEdmModel GetParserResult(IEnumerable <XElement> csdlElements)
        {
            IEdmModel edmModel;
            IEnumerable <EdmError> errors;
            bool success = SchemaReader.TryParse(csdlElements.Select(e => e.CreateReader()), out edmModel, out errors);

            ExceptionUtilities.Assert(success, "Parse failed -- are you using an invalid model?");
            return(edmModel);
        }
        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"">
      <Annotation Term=""Org.OData.Authorization.V1.Authorizations"">
        <Collection>
          <Record Type=""Org.OData.Authorization.V1.OpenIDConnect"">
            <PropertyValue Property=""IssuerUrl"" String=""http://any"" />
            <PropertyValue Property=""Name"" String=""OpenIDConnect Name"" />
            <PropertyValue Property=""Description"" String=""OpenIDConnect Description"" />
          </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>
    </EntitySet>
    <Singleton Name=""Me"" Type=""NS.Entity"" />
  </EntityContainer>
  <Annotations Target=""NS.Container/Me"">
    <Annotation Term=""Org.OData.Authorization.V1.Authorizations"">
      <Collection>
        <Record Type=""Org.OData.Authorization.V1.OpenIDConnect"">
          <PropertyValue Property=""IssuerUrl"" String=""http://any"" />
          <PropertyValue Property=""Name"" String=""OpenIDConnect Name"" />
          <PropertyValue Property=""Description"" String=""OpenIDConnect Description"" />
        </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);
        }
Esempio n. 15
0
        public void CheckMultiVersionCsdlsRoundtrip()
        {
            const string inputText =
                @"<?xml version=""1.0"" encoding=""utf-16""?>
<Schema Namespace=""Real4"" xmlns=""http://docs.oasis-open.org/odata/ns/edm"">
  <ComplexType Name=""Complex4"" BaseType=""Real4.Complex1"">
    <Property Name=""Prop4"" Type=""Edm.Int32"" Nullable=""false"" />
  </ComplexType>
</Schema>";

            XmlWriterSettings settings = new XmlWriterSettings();

            settings.Indent   = true;
            settings.Encoding = System.Text.Encoding.UTF8;
            List <StringWriter> outStrings = new List <StringWriter>();
            List <XmlReader>    readers    = new List <XmlReader>();
            List <XmlWriter>    writers    = new List <XmlWriter>();

            foreach (string s in new string[] { inputText })
            {
                readers.Add(XmlReader.Create(new StringReader(s)));
            }

            for (int i = 0; i < readers.Count; i++)
            {
                StringWriter sw = new StringWriter();
                outStrings.Add(sw);
                writers.Add(XmlWriter.Create(sw, settings));
            }

            IEdmModel model;
            IEnumerable <EdmError> errors;
            bool parsed = SchemaReader.TryParse(readers, out model, out errors);

            Assert.IsTrue(parsed, "Model Parsed");
            Assert.IsTrue(errors.Count() == 0, "No errors");
            Assert.AreEqual(EdmConstants.EdmVersion4, model.GetEdmVersion(), "Version check");

            IEnumerator <XmlWriter> writerEnumerator = writers.GetEnumerator();

            model.TryWriteSchema(s => { writerEnumerator.MoveNext(); return(writerEnumerator.Current); }, out errors);

            foreach (XmlWriter xw in writers)
            {
                xw.Flush();
                xw.Close();
            }

            IEnumerator <StringWriter> swEnumerator = outStrings.GetEnumerator();

            foreach (string input in new string[] { inputText })
            {
                swEnumerator.MoveNext();
                Assert.IsTrue(swEnumerator.Current.ToString() == input, "Input = Output");
            }
        }
 private static IEdmModel LoadSchemaEdmModel(Assembly assembly, string vocabularyName, IEnumerable <IEdmModel> referenceModels)
 {
     using (Stream stream = assembly.GetManifestResourceStream(vocabularyName))
     {
         IEdmModel model;
         IEnumerable <EdmError> errors;
         SchemaReader.TryParse(new[] { XmlReader.Create(stream) }, referenceModels, false, out model, out errors);
         return(model);
     }
 }
Esempio n. 17
0
        public void SerializerTestModelOperationDuplicateReturnType()
        {
            var       csdls = ModelBuilder.FunctionDuplicateReturnType();
            IEdmModel edmModel;
            IEnumerable <EdmError> errors;
            var isParsed = SchemaReader.TryParse(csdls.Select(e => e.CreateReader()), out edmModel, out errors);

            Assert.AreEqual(1, errors.Count(), "Expecting errors.");
            Assert.AreEqual(EdmErrorCode.UnexpectedXmlElement, errors.ElementAt(0).ErrorCode, "Invalid error code.");
        }
Esempio n. 18
0
        protected IEdmModel GetParserResult(IEnumerable <XElement> csdlElements, params IEdmModel[] referencedModels)
        {
            IEdmModel edmModel;
            IEnumerable <EdmError> errors;
            var isParsed = SchemaReader.TryParse(csdlElements.Select(e => e.CreateReader()), referencedModels, out edmModel, out errors);

            Assert.IsTrue(isParsed, "SchemaReader.TryParse failed");
            Assert.IsTrue(!errors.Any(), "SchemaReader.TryParse returned errors");
            return(edmModel);
        }
Esempio n. 19
0
        protected void VerifySemanticValidation(IEdmModel testModel, ValidationRuleSet ruleset, IEnumerable <EdmError> expectedErrors)
        {
            // Compare the actual errors of the test models to the expected errors.
            IEnumerable <EdmError> actualErrors = null;
            var validationResult = testModel.Validate(ruleset, out actualErrors);

            Assert.IsTrue(actualErrors.Any() ? !validationResult : validationResult, "The return value of the Validate method does not match the reported validation errors.");
            this.CompareErrors(actualErrors, expectedErrors);

            // Compare the round-tripped immutable model through the CSDL serialized from the original test model against the expected errors.
            Func <EdmVersion> GetEdmVersionFromRuleSet = () =>
            {
                EdmVersion result = EdmVersion.Latest;
                foreach (var edmVersion in new EdmVersion[] { EdmVersion.V40 })
                {
                    var versionRuleSet = ValidationRuleSet.GetEdmModelRuleSet(toProductVersionlookup[edmVersion]);
                    if (versionRuleSet.Count() == ruleset.Count() && !ruleset.Except(versionRuleSet).Any())
                    {
                        result = edmVersion;
                        break;
                    }
                }
                return(result);
            };

            IEnumerable <EdmError> serializationErrors;
            var serializedCsdls = this.GetSerializerResult(testModel, GetEdmVersionFromRuleSet(), out serializationErrors).Select(n => XElement.Parse(n));

            if (!serializedCsdls.Any())
            {
                Assert.AreNotEqual(0, serializationErrors.Count(), "Empty models should have associated errors");
                return;
            }

            if (!actualErrors.Any())
            {
                // if the original test model is valid, the round-tripped model should be well-formed and valid.
                IEnumerable <EdmError> parserErrors = null;
                IEdmModel roundtrippedModel         = null;
                var       isWellformed = SchemaReader.TryParse(serializedCsdls.Select(e => e.CreateReader()), out roundtrippedModel, out parserErrors);
                Assert.IsTrue(isWellformed && !parserErrors.Any(), "The model from valid CSDLs should be generated back to well-formed CSDLs.");

                IEnumerable <EdmError> validationErrors = null;
                var isValid = roundtrippedModel.Validate(out validationErrors);
                Assert.IsTrue(!validationErrors.Any() && isValid, "The model from valid CSDLs should be generated back to valid CSDLs.");
            }
            else
            {
                // if the originl test model is not valid, the serializer should still generate CSDLs that parser can handle, but the round trip-ability is not guarantted.
                IEnumerable <EdmError> parserErrors = null;
                IEdmModel roundtrippedModel         = null;
                var       isWellformed = SchemaReader.TryParse(serializedCsdls.Select(e => e.CreateReader()), out roundtrippedModel, out parserErrors);
                Assert.IsTrue(isWellformed, "The parser cannot handle the CSDL that the serializer generated:" + Environment.NewLine + String.Join(Environment.NewLine, parserErrors));
            }
        }
Esempio n. 20
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);
        }
Esempio n. 21
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"" ");
        }
Esempio n. 22
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");
        }
Esempio n. 23
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);
        }
Esempio n. 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);
            }
        }
Esempio n. 25
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");
        }
        /// <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);
            }
        }
        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);
        }
Esempio n. 28
0
        /// <summary>
        /// Builds a model with annotations.
        /// </summary>
        /// <param name="annotationXml">The annotation element(s) as XML string.</param>
        /// <param name="references">The model references to add.</param>
        /// <returns>The loaded model.</returns>
        /// <remarks>The <paramref name="annotationXml"/> string must not include the wrapping schema element.</remarks>
        public static IEdmModel BuildAnnotationModel(string annotationXml, params IEdmModel[] references)
        {
            string annotationSchema =
                "<Schema Namespace='TestModelStandardAnnotations' xmlns='http://docs.oasis-open.org/odata/ns/edm'>" +
                annotationXml +
                "</Schema>";

            using (XmlReader reader = XmlReader.Create(new StringReader(annotationSchema)))
            {
                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);
            }
        }
Esempio n. 29
0
        public void ParserTestForIncorrectCsdl20Namespace()
        {
            var       csdls = ModelBuilder.SimpleConstructiveApiTestModel();
            IEdmModel model;
            IEnumerable <EdmError> errors;

            foreach (var csdl in csdls)
            {
                bool parsed = SchemaReader.TryParse(new System.Xml.XmlReader[] { csdl.CreateReader() }, out model, out errors);
                Assert.IsTrue(parsed, "parsed");

                // http://docs.oasis-open.org/odata/ns/edm is a namespace that OData uses.
                var csdlStringNewNamespace = csdl.ToString();
                parsed = SchemaReader.TryParse(new System.Xml.XmlReader[] { System.Xml.XmlReader.Create(new System.IO.StringReader(csdlStringNewNamespace)) }, out model, out errors);
                Assert.IsTrue(parsed, "parsed");

                csdlStringNewNamespace = csdl.ToString().Replace(csdl.GetDefaultNamespace().NamespaceName, "http://schemas.microsoft.com/ado/2007/09/edm");
                parsed = SchemaReader.TryParse(new System.Xml.XmlReader[] { System.Xml.XmlReader.Create(new System.IO.StringReader(csdlStringNewNamespace)) }, out model, out errors);
                Assert.IsFalse(parsed, "The parser should not support other invalid namespaces than http://docs.oasis-open.org/odata/ns/edm.");
            }
        }
        public void ValidateAnnotationAttributeMustNotCollide()
        {
            const string csdl =
                @"<?xml version=""1.0"" encoding=""utf-16""?>
<Schema Namespace=""Hot"" Alias=""Fuzz"" xmlns:Bogus=""http://bogus.com/schema"" xmlns=""http://docs.oasis-open.org/odata/ns/edm"">
  <EntityType Name=""Person"" Bogus:PropertyAnnotationAttribute=""Just kidding"" Bogus:PropertyAnnotationAttribute=""Just kidding"">
    <Key>
      <PropertyRef Name=""Id"" />
    </Key>
    <Bogus:EntityTypeAnnotation Stuff=""Whatever"" />
    <Property Name=""Id"" Type=""Int32"" Nullable=""false""/>
  </EntityType>
</Schema>";

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

            Assert.IsFalse(parsed, "Should fail to parse.");
            Assert.IsTrue(errors.Count() != 0, "Should report a failure");
        }