Ejemplo n.º 1
0
        public void FindVocabularyAnnotationInParallel()
        {
            int annotationCount = 30;
            var edmModel        = new EdmParModel().Model as EdmModel;
            var container       = edmModel.EntityContainer;

            for (int i = 0; i < annotationCount; i++)
            {
                EdmTerm term = new EdmTerm("NS", "Test" + i, EdmPrimitiveTypeKind.String);
                EdmVocabularyAnnotation annotation = new EdmVocabularyAnnotation(
                    container,
                    term,
                    new EdmStringConstant("desc" + i));
                edmModel.AddVocabularyAnnotation(annotation);
            }

            IEdmModel loadedEdmModel = null;

            using (var ms = new MemoryStream())
            {
                var xw = XmlWriter.Create(ms, new XmlWriterSettings {
                    Indent = true
                });

                IEnumerable <EdmError> errors;
                var res = CsdlWriter.TryWriteCsdl(edmModel, xw, CsdlTarget.OData, out errors);
                xw.Flush();
                ms.Flush();
                ms.Seek(0, SeekOrigin.Begin);
                using (var sr = new StreamReader(ms))
                {
                    var metadata = sr.ReadToEnd();
                    loadedEdmModel = CsdlReader.Parse(XmlReader.Create(new MemoryStream(Encoding.UTF8.GetBytes(metadata))));
                }
            }
            container = loadedEdmModel.EntityContainer;

            int errorCount           = 0;
            int totalAnnotationCount = 0;
            int taskCount            = 100;

            Parallel.ForEach(
                Enumerable.Range(0, taskCount),
                index =>
            {
                try
                {
                    var count = loadedEdmModel.FindVocabularyAnnotations(container).ToList().Count();
                    Interlocked.Add(ref totalAnnotationCount, count);
                }
                catch (Exception ew)
                {
                    Console.WriteLine(ew);
                    Interlocked.Increment(ref errorCount);
                }
            });

            Assert.AreEqual(0, errorCount);
            Assert.AreEqual(taskCount * annotationCount, totalAnnotationCount);
        }
Ejemplo n.º 2
0
        private IEdmModel EntityTypeTermModel()
        {
            var model = new EdmModel();

            var entityTypeElement = new EdmEntityType("NS", "EntityTypeElement");

            entityTypeElement.AddKeys(entityTypeElement.AddStructuralProperty("KeyProperty", EdmCoreModel.Instance.GetInt32(false)));
            entityTypeElement.AddStructuralProperty("IntegerProperty", EdmCoreModel.Instance.GetInt32(true));
            entityTypeElement.AddStructuralProperty("StringProperty", EdmCoreModel.Instance.GetString(true));
            model.AddElement(entityTypeElement);

            var entityTypeTerm = new EdmTerm("NS", "EntityTypeTerm", new EdmEntityTypeReference(entityTypeElement, true));

            model.AddElement(entityTypeTerm);

            var inlineEntityTypeAnnotation = new EdmVocabularyAnnotation(entityTypeElement, entityTypeTerm, new EdmRecordExpression(
                                                                             new EdmPropertyConstructor("KeyProperty", new EdmIntegerConstant(1)),
                                                                             new EdmPropertyConstructor("IntegerProperty", new EdmIntegerConstant(111)),
                                                                             new EdmPropertyConstructor("StringProperty", new EdmStringConstant("Inline String 111"))));

            inlineEntityTypeAnnotation.SetSerializationLocation(model, EdmVocabularyAnnotationSerializationLocation.Inline);
            model.AddVocabularyAnnotation(inlineEntityTypeAnnotation);

            var outlineEntityTypeAnnotation = new EdmVocabularyAnnotation(entityTypeTerm, entityTypeTerm, new EdmRecordExpression(
                                                                              new EdmPropertyConstructor("KeyProperty", new EdmIntegerConstant(2)),
                                                                              new EdmPropertyConstructor("IntegerProperty", new EdmIntegerConstant(222)),
                                                                              new EdmPropertyConstructor("StringProperty", new EdmStringConstant("Outline String 222"))));

            model.AddVocabularyAnnotation(outlineEntityTypeAnnotation);

            return(model);
        }
Ejemplo n.º 3
0
        private static void AddOptimisticConcurrencyAnnotation(this EdmModel model, IEdmVocabularyAnnotatable target,
                                                               NavigationSourceConfiguration navigationSourceConfiguration, EdmTypeMap edmTypeMap)
        {
            EntityTypeConfiguration entityTypeConfig = navigationSourceConfiguration.EntityType;

            IEnumerable <StructuralPropertyConfiguration> concurrencyPropertyies =
                entityTypeConfig.Properties.OfType <StructuralPropertyConfiguration>().Where(property => property.ConcurrencyToken);

            IList <IEdmStructuralProperty> edmProperties = new List <IEdmStructuralProperty>();

            foreach (StructuralPropertyConfiguration property in concurrencyPropertyies)
            {
                IEdmProperty value;
                if (edmTypeMap.EdmProperties.TryGetValue(property.PropertyInfo, out value))
                {
                    var item = value as IEdmStructuralProperty;
                    if (item != null)
                    {
                        edmProperties.Add(item);
                    }
                }
            }

            if (edmProperties.Any())
            {
                IEdmCollectionExpression collectionExpression = new EdmCollectionExpression(edmProperties.Select(p => new EdmPropertyPathExpression(p.Name)).ToArray());
                IEdmTerm term = Microsoft.OData.Edm.Vocabularies.V1.CoreVocabularyModel.ConcurrencyTerm;
                EdmVocabularyAnnotation annotation = new EdmVocabularyAnnotation(target, term, collectionExpression);
                annotation.SetSerializationLocation(model, EdmVocabularyAnnotationSerializationLocation.Inline);
                model.SetVocabularyAnnotation(annotation);
            }
        }
        public static IEdmModel InterfaceCriticalKindValueUnexpectedWithOtherErrorsModel()
        {
            var model     = new EdmModel();
            var valueTerm = new EdmTerm("DefaultNamespace", "Note", EdmCoreModel.Instance.GetString(true));

            model.AddElement(valueTerm);
            model.AddElement(valueTerm);

            var entity = new EdmEntityType("DefaultNamespace", "foo");

            model.AddElement(entity);

            var entityContainer = new EdmEntityContainer("DefaultNamespace", "container");

            model.AddElement(entityContainer);

            var badString = new CustomStringConstant("foo", EdmExpressionKind.None, EdmValueKind.String);

            var valueAnnotation = new EdmVocabularyAnnotation(
                valueTerm,
                valueTerm,
                badString);

            model.AddVocabularyAnnotation(valueAnnotation);

            var valueAnnotation2 = new EdmVocabularyAnnotation(
                valueTerm,
                valueTerm,
                new EdmStringConstant("foo"));

            model.AddVocabularyAnnotation(valueAnnotation2);

            return(model);
        }
Ejemplo n.º 5
0
        public static void SetAnnotation <TEntity>(
            this EdmModel model,
            IEdmTerm term,
            IEdmExpression expression,
            Expression <Func <TEntity, object> > propertyExpression = null)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }
            var type = model.GetEdmType(typeof(TEntity)) as EdmEntityType;
            IEdmVocabularyAnnotatable target = type;

            if (propertyExpression != null)
            {
                var property = type.Properties().Single(p => p.Name == propertyExpression.GetAccessedProperty().Name);
                target = property;
            }
            var label = new EdmLabeledExpression("Value", expression);
            //var coll1 = new EdmCollectionExpression(new EdmStringConstant("test1"), new EdmStringConstant("test2"), new EdmStringConstant("test3"), label);
            //var coll = new EdmCollectionExpression(expression, coll1);
            var annotation = new EdmVocabularyAnnotation(target, term, label);

            annotation.SetSerializationLocation(model, target.ToSerializationLocation());
            model.AddVocabularyAnnotation(annotation);
        }
        public static IEdmModel InvalidPropertyTypeUsingIsTypeOnInlineAnnotationModel()
        {
            var model = new EdmModel();

            var bike = new EdmComplexType("NS", "Bike");

            bike.AddStructuralProperty("Color", EdmCoreModel.Instance.GetString(true));
            model.AddElement(bike);

            var car          = new EdmComplexType("NS", "Car");
            var carExpensive = car.AddStructuralProperty("Expensive", new EdmComplexTypeReference(bike, true));

            model.AddElement(car);

            var carTerm = new EdmTerm("NS", "CarTerm", new EdmComplexTypeReference(car, true));

            model.AddElement(carTerm);

            var valueAnnotation = new EdmVocabularyAnnotation(
                car,
                carTerm,
                new EdmRecordExpression(
                    new EdmPropertyConstructor(carExpensive.Name, new EdmIsTypeExpression(new EdmStringConstant("foo"), EdmCoreModel.Instance.GetString(true)))));

            valueAnnotation.SetSerializationLocation(model, EdmVocabularyAnnotationSerializationLocation.Inline);
            model.AddVocabularyAnnotation(valueAnnotation);

            return(model);
        }
        public static IEdmModel CastNullableToNonNullableOnInlineAnnotationModel()
        {
            var model = new EdmModel();

            var address = new EdmComplexType("NS", "Address");

            address.AddStructuralProperty("StreetNumber", EdmCoreModel.Instance.GetInt32(true));
            address.AddStructuralProperty("StreetName", EdmCoreModel.Instance.GetString(true));
            model.AddElement(address);

            var friend = new EdmComplexType("NS", "Friend");

            friend.AddStructuralProperty("Name", EdmCoreModel.Instance.GetString(true));
            friend.AddStructuralProperty("NickNames", EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetString(true)));
            friend.AddStructuralProperty("Address", new EdmComplexTypeReference(address, true));
            model.AddElement(friend);

            var friendInfo = new EdmTerm("NS", "FriendInfo", EdmCoreModel.GetCollection(new EdmComplexTypeReference(friend, true)));

            model.AddElement(friendInfo);

            var valueAnnotationCast = new EdmCastExpression(new EdmCollectionExpression(new EdmStringConstant("foo"), new EdmStringConstant("bar")), new EdmComplexTypeReference(friend, true));
            var valueAnnotation     = new EdmVocabularyAnnotation(
                friendInfo,
                friendInfo,
                valueAnnotationCast);

            valueAnnotation.SetSerializationLocation(model, EdmVocabularyAnnotationSerializationLocation.Inline);
            model.AddVocabularyAnnotation(valueAnnotation);

            return(model);
        }
Ejemplo n.º 8
0
        public static EdmModel OutOfLineVocabularyAnnotationWithAnnotationModel()
        {
            EdmModel model = new EdmModel();

            EdmComplexType simpleType = new EdmComplexType("DefaultNamespace", "SimpleType");

            simpleType.AddStructuralProperty("Data", EdmCoreModel.Instance.GetString(true));
            model.AddElement(simpleType);

            EdmTerm note = new EdmTerm("DefaultNamespace", "Note", EdmCoreModel.Instance.GetString(true));

            model.AddElement(note);

            EdmVocabularyAnnotation valueAnnotation = new EdmVocabularyAnnotation(
                simpleType,
                note,
                new EdmStringConstant("ComplexTypeNote"));

            valueAnnotation.SetSerializationLocation(model, EdmVocabularyAnnotationSerializationLocation.OutOfLine);
            model.AddVocabularyAnnotation(valueAnnotation);

            XElement annotationElement =
                new XElement("{http://foo}Annotation", "1");
            var annotation = new EdmStringConstant(EdmCoreModel.Instance.GetString(false), annotationElement.ToString());

            annotation.SetIsSerializedAsElement(model, true);
            model.SetAnnotationValue(valueAnnotation, "http://foo", "Annotation", annotation);

            return(model);
        }
Ejemplo n.º 9
0
        public static void SetSearchRestrictionsCapabilitiesAnnotation(this EdmModel model, IEdmEntitySet entitySet, bool searchable, CapabilitiesSearchExpressions unsupported)
        {
            if (model == null)
            {
                throw new ArgumentNullException("model");
            }
            if (entitySet == null)
            {
                throw new ArgumentNullException("entitySet");
            }

            var target     = entitySet;
            var term       = SearchRestrictionsTerm;
            var name       = new EdmEnumTypeReference(SearchExpressionsType, false).ToStringLiteral((long)unsupported);
            var properties = new IEdmPropertyConstructor[]
            {
                new EdmPropertyConstructor("Searchable", new EdmBooleanConstant(searchable)),
                new EdmPropertyConstructor("UnsupportedExpressions", new EdmEnumMemberExpression(SearchExpressionsType.Members.Single(m => m.Name == name))),
            };
            var record = new EdmRecordExpression(properties);

            var annotation = new EdmVocabularyAnnotation(target, term, record);

            annotation.SetSerializationLocation(model, entitySet.ToSerializationLocation());
            model.AddVocabularyAnnotation(annotation);
        }
Ejemplo n.º 10
0
        public static EdmModel FindVocabularyAnnotationAcrossModelAnnotationModel()
        {
            var model = new EdmModel();

            var containerOne = new EdmEntityContainer("DefaultNamespace", "ContainerOne");

            model.AddElement(containerOne);

            var termOne = new EdmTerm("DefaultNamespace", "TermOne", EdmCoreModel.Instance.GetString(true));

            model.AddElement(termOne);
            var termTwo = new EdmTerm("DefaultNamespace", "TermTwo", EdmCoreModel.Instance.GetString(true));

            model.AddElement(termTwo);

            var valueAnnotationOne = new EdmVocabularyAnnotation(
                containerOne,
                termOne,
                new EdmStringConstant("1"));

            valueAnnotationOne.SetSerializationLocation(model, EdmVocabularyAnnotationSerializationLocation.Inline);
            model.AddVocabularyAnnotation(valueAnnotationOne);

            return(model);
        }
Ejemplo n.º 11
0
        public void EdmSingletonAnnotationTests()
        {
            EdmModel model = new EdmModel();

            EdmStructuralProperty customerProperty = new EdmStructuralProperty(customerType, "Name", EdmCoreModel.Instance.GetString(false));

            customerType.AddProperty(customerProperty);
            model.AddElement(this.customerType);

            EdmSingleton vipCustomer = new EdmSingleton(this.entityContainer, "VIP", this.customerType);

            EdmTerm term       = new EdmTerm(myNamespace, "SingletonAnnotation", EdmPrimitiveTypeKind.String);
            var     annotation = new EdmVocabularyAnnotation(vipCustomer, term, new EdmStringConstant("Singleton Annotation"));

            model.AddVocabularyAnnotation(annotation);

            var singletonAnnotation = vipCustomer.VocabularyAnnotations(model).Single();

            Assert.Equal(vipCustomer, singletonAnnotation.Target);
            Assert.Equal("SingletonAnnotation", singletonAnnotation.Term.Name);

            singletonAnnotation = model.FindDeclaredVocabularyAnnotations(vipCustomer).Single();
            Assert.Equal(vipCustomer, singletonAnnotation.Target);
            Assert.Equal("SingletonAnnotation", singletonAnnotation.Term.Name);

            EdmTerm propertyTerm       = new EdmTerm(myNamespace, "SingletonPropertyAnnotation", EdmPrimitiveTypeKind.String);
            var     propertyAnnotation = new EdmVocabularyAnnotation(customerProperty, propertyTerm, new EdmStringConstant("Singleton Property Annotation"));

            model.AddVocabularyAnnotation(propertyAnnotation);

            var singletonPropertyAnnotation = customerProperty.VocabularyAnnotations(model).Single();

            Assert.Equal(customerProperty, singletonPropertyAnnotation.Target);
            Assert.Equal("SingletonPropertyAnnotation", singletonPropertyAnnotation.Term.Name);
        }
Ejemplo n.º 12
0
        private static void AddComplexPropertyCommunityAlternateKey(EdmModel model, EdmEntityType entity)
        {
            // Alternate key 1 -> Code
            List <IEdmExpression> propertyRefs = new List <IEdmExpression>();
            IEdmRecordExpression  propertyRef  = new EdmRecordExpression(
                new EdmPropertyConstructor("Alias", new EdmStringConstant("Code")),
                new EdmPropertyConstructor("Name", new EdmPropertyPathExpression("Code")));

            propertyRefs.Add(propertyRef);

            EdmRecordExpression alternateKey1 = new EdmRecordExpression(new EdmPropertyConstructor("Key", new EdmCollectionExpression(propertyRefs)));

            // Alternate key 2 -> City & Street
            propertyRefs = new List <IEdmExpression>();
            propertyRef  = new EdmRecordExpression(
                new EdmPropertyConstructor("Alias", new EdmStringConstant("City")),
                new EdmPropertyConstructor("Name", new EdmPropertyPathExpression("Location/City")));
            propertyRefs.Add(propertyRef);

            propertyRef = new EdmRecordExpression(
                new EdmPropertyConstructor("Alias", new EdmStringConstant("Street")),
                new EdmPropertyConstructor("Name", new EdmPropertyPathExpression("Location/Street")));
            propertyRefs.Add(propertyRef);

            EdmRecordExpression alternateKey2 = new EdmRecordExpression(new EdmPropertyConstructor("Key", new EdmCollectionExpression(propertyRefs)));

            IEdmTerm coreAlternateTerm = AlternateKeysVocabularyModel.Instance.FindDeclaredTerm("OData.Community.Keys.V1.AlternateKeys");

            Assert.NotNull(coreAlternateTerm);

            var annotation = new EdmVocabularyAnnotation(entity, coreAlternateTerm, new EdmCollectionExpression(alternateKey1, alternateKey2));

            annotation.SetSerializationLocation(model, EdmVocabularyAnnotationSerializationLocation.Inline);
            model.SetVocabularyAnnotation(annotation);
        }
Ejemplo n.º 13
0
        public void BuildStructuralProperties(EdmModel edmModel, Dictionary <Type, EntityTypeInfo> entityTypes,
                                              Dictionary <Type, EdmEnumType> enumTypes, Dictionary <Type, EdmComplexType> complexTypes)
        {
            foreach (PropertyInfo clrProperty in _metadataProvider.GetProperties(ClrType))
            {
                if (!_metadataProvider.IsNotMapped(clrProperty))
                {
                    EdmStructuralProperty?edmProperty = BuildStructuralProperty(entityTypes, enumTypes, complexTypes, clrProperty);
                    if (edmProperty != null && _metadataProvider.IsDatabaseGenerated(clrProperty))
                    {
                        var databaseGenerated = new EdmVocabularyAnnotation(edmProperty, CoreVocabularyModel.ComputedTerm, new EdmBooleanConstant(true));
                        edmModel.SetVocabularyAnnotation(databaseGenerated);
                    }
                }
            }

            if (_isDbQuery)
            {
                AddDbQueryKeys();
            }
            else
            {
                AddKeys();
            }
        }
Ejemplo n.º 14
0
        private static void SetCoreAnnotation(this EdmModel model, IEdmVocabularyAnnotatable target, IEdmTerm term, string value)
        {
            var expression = new EdmStringConstant(value);
            var annotation = new EdmVocabularyAnnotation(target, term, expression);

            annotation.SetSerializationLocation(model, target.ToSerializationLocation());
            model.AddVocabularyAnnotation(annotation);
        }
Ejemplo n.º 15
0
        private static void SetCapabilitiesAnnotation(this EdmModel model, IEdmVocabularyAnnotatable target, IEdmTerm term, bool value)
        {
            var expression = new EdmBooleanConstant(value);
            var annotation = new EdmVocabularyAnnotation(target, term, expression);

            annotation.SetSerializationLocation(model, target.ToSerializationLocation());
            model.AddVocabularyAnnotation(annotation);
        }
Ejemplo n.º 16
0
        private static void AddSelectTerm <T>(EdmModel model)
        {
            EdmComplexType complexType = new EdmComplexType("NS", "SelectType");

            complexType.AddStructuralProperty("DefaultSelect", new EdmCollectionTypeReference(new EdmCollectionType(EdmCoreModel.Instance.GetString(true))));
            complexType.AddStructuralProperty("DefaultHidden", new EdmCollectionTypeReference(new EdmCollectionType(EdmCoreModel.Instance.GetString(true))));
            model.AddElement(complexType);
            EdmTerm term = new EdmTerm("NS", "MyTerm", new EdmComplexTypeReference(complexType, true));

            model.AddElement(term);

            Type   type       = typeof(T);
            string name       = type.Name;
            var    entityType = model.SchemaElements.OfType <IEdmEntityType>().FirstOrDefault(c => c.Name == name);

            if (entityType == null)
            {
                return;
            }

            IList <string> defaultSelects = new List <string>();
            IList <string> defaultHiddens = new List <string>();
            var            properties     = type.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);

            foreach (var property in properties)
            {
                var attrs = property.GetCustomAttributes(typeof(DefaultSelectAttribute), false);
                if (attrs != null && attrs.Any())
                {
                    defaultSelects.Add(property.Name);
                    continue;
                }

                attrs = property.GetCustomAttributes(typeof(DefaultHiddenAttribute), false);
                if (attrs != null && attrs.Any())
                {
                    defaultHiddens.Add(property.Name);
                    continue;
                }
            }

            if (defaultSelects.Any() && defaultHiddens.Any())
            {
                List <IEdmPropertyConstructor> edmPropertiesConstructors = new List <IEdmPropertyConstructor>
                {
                    new EdmPropertyConstructor("DefaultSelect", new EdmCollectionExpression(
                                                   defaultSelects.Select(e => new EdmPropertyPathExpression(e)))),
                    new EdmPropertyConstructor("DefaultHidden", new EdmCollectionExpression(
                                                   defaultHiddens.Select(e => new EdmPropertyPathExpression(e)))),
                };

                IEdmRecordExpression    record     = new EdmRecordExpression(edmPropertiesConstructors);
                EdmVocabularyAnnotation annotation = new EdmVocabularyAnnotation(entityType, term, record);
                annotation.SetSerializationLocation(model, EdmVocabularyAnnotationSerializationLocation.Inline);
                model.SetVocabularyAnnotation(annotation);
            }
        }
        private static void SetDerivedTypeAnnotation(EdmModel model, IEdmVocabularyAnnotatable target, params string[] derivedTypes)
        {
            IEdmTerm term = ValidationVocabularyModel.DerivedTypeConstraintTerm;
            var      collectionExpression = new EdmCollectionExpression(derivedTypes.Select(d => new EdmStringConstant(d)));
            EdmVocabularyAnnotation valueAnnotationOnProperty = new EdmVocabularyAnnotation(target, term, collectionExpression);

            valueAnnotationOnProperty.SetSerializationLocation(model, EdmVocabularyAnnotationSerializationLocation.Inline);
            model.AddVocabularyAnnotation(valueAnnotationOnProperty);
        }
        public void ExceptionThrowForInvalidPropertyPath()
        {
            EdmModel model = new EdmModel();

            EdmEntityType personType = new EdmEntityType("MyNs", "Person", null, false, false, true);

            personType.AddKeys(personType.AddStructuralProperty("ID", EdmPrimitiveTypeKind.Int32));
            personType.AddStructuralProperty("Name", EdmCoreModel.Instance.GetString(isNullable: true));

            var container = new EdmEntityContainer("MyNs", "Container");

            model.AddElement(personType);
            container.AddEntitySet("People", personType);
            model.AddElement(container);
            IEdmEntitySet peopleSet = model.FindDeclaredEntitySet("People");

            IEdmPathExpression nameExpression = new EdmPropertyPathExpression("NameName");

            IEdmCollectionExpression collection = new EdmCollectionExpression(new[] { nameExpression });
            IEdmTerm term = null;

            foreach (var referencedModel in model.ReferencedModels)
            {
                term = referencedModel.FindDeclaredTerm("Org.OData.Core.V1.OptimisticConcurrency");

                if (term != null)
                {
                    break;
                }
            }

            Assert.NotNull(term);

            EdmVocabularyAnnotation valueAnnotationOnEntitySet = new EdmVocabularyAnnotation(peopleSet, term, collection);

            valueAnnotationOnEntitySet.SetSerializationLocation(model, EdmVocabularyAnnotationSerializationLocation.Inline);
            model.AddVocabularyAnnotation(valueAnnotationOnEntitySet);

            ODataResource entry = new ODataResource
            {
                Properties = new[]
                {
                    new ODataProperty {
                        Name = "ID", Value = 123
                    },
                    new ODataProperty {
                        Name = "Name", Value = "lucy"
                    },
                }
            };

            Action action = () => GetWriterOutputForContentTypeAndKnobValue(entry, model, peopleSet, personType);

            action.ShouldThrow <ODataException>().WithMessage(ErrorStrings.EdmValueUtils_PropertyDoesntExist("MyNs.Person", "NameName"));
        }
        public void TestAnnotationsWithModelReferencesAnnotationsInTheModel()
        {
            var vocabulary = new FunctionalUtilities.ModelWithRemovableElements <EdmModel>(CreateModel());

            vocabulary.RemoveElement(vocabulary.EntityContainer);
            vocabulary.RemoveElement(vocabulary.FindEntityType("NS1.Customer"));
            IEnumerable <EdmError> errors;

            Assert.IsTrue(vocabulary.Validate(out errors), "validate vocabulary");

            var model = new FunctionalUtilities.ModelWithRemovableElements <EdmModel>(CreateModel());

            model.RemoveElement(model.FindTerm("NS1.Title"));
            model.RemoveElement(model.FindEntityType("NS1.Person"));
            model.WrappedModel.AddReferencedModel(vocabulary);

            var vterm    = vocabulary.FindTerm("NS1.Title");
            var tterm    = vocabulary.FindEntityType("NS1.Person");
            var customer = model.FindEntityType("NS1.Customer");

            var vannotation = new EdmVocabularyAnnotation(
                customer,
                vterm,
                "q1",
                new EdmStringConstant("Hello world!"));

            model.WrappedModel.AddVocabularyAnnotation(vannotation);

            var sw = new StringWriter();
            var w  = XmlWriter.Create(sw, new XmlWriterSettings()
            {
                Indent = true
            });

            model.TryWriteSchema(w, out errors);
            w.Close();
            Assert.AreEqual(
                @"<?xml version=""1.0"" encoding=""utf-16""?>
<Schema Namespace=""NS1"" xmlns=""http://docs.oasis-open.org/odata/ns/edm"">
  <EntityType Name=""Customer"">
    <Key>
      <PropertyRef Name=""CustomerID"" />
    </Key>
    <Property Name=""CustomerID"" Type=""Edm.String"" Nullable=""false"" />
  </EntityType>
  <EntityContainer Name=""Container"">
    <EntitySet Name=""Customers"" EntityType=""NS1.Customer"" />
  </EntityContainer>
  <Annotations Target=""NS1.Customer"">
    <Annotation Term=""NS1.Title"" Qualifier=""q1"" String=""Hello world!"" />
  </Annotations>
</Schema>", sw.ToString(), "model.WriteCsdl(w)");
        }
Ejemplo n.º 20
0
        private IEdmVocabularyAnnotation CreateAndAttachVocabularyAnnotation(IEdmVocabularyAnnotatable target, IEdmTerm term, IEdmExpression value, string qualifier)
        {
            var annotation = new EdmVocabularyAnnotation(
                target,
                term,
                qualifier,
                value);

            // ?? Unnatural API
            ((EdmModel)this.baseModel).AddVocabularyAnnotation(annotation);
            return(annotation);
        }
Ejemplo n.º 21
0
        private static void SetCapabilitiesAnnotation(this EdmModel model, IEdmVocabularyAnnotatable target, IEdmTerm term, IEnumerable <string> values)
        {
            if (values == null)
            {
                values = new string[0];
            }

            var expression = new EdmCollectionExpression(values.Select(function => new EdmStringConstant(function)));
            var annotation = new EdmVocabularyAnnotation(target, term, expression);

            annotation.SetSerializationLocation(model, target.ToSerializationLocation());
            model.AddVocabularyAnnotation(annotation);
        }
Ejemplo n.º 22
0
        private IEdmModel BuildVocabularyAnnotationModelWithEdmValueKind(IEdmTypeReference valueKindType, IEdmExpression valueAnnotationValue)
        {
            var model = this.BuildBasicModelWithTerm(valueKindType);

            var valueAnnotation = new EdmVocabularyAnnotation(
                model.FindEntityContainer("foo.Container"),
                model.FindTerm("foo.ValueTerm"),
                valueAnnotationValue);

            model.AddVocabularyAnnotation(valueAnnotation);

            return(model);
        }
Ejemplo n.º 23
0
        public static void SetComputedAnnotation(EdmModel model, IEdmProperty target)
        {
            EdmUtil.CheckArgumentNull(model, "model");
            EdmUtil.CheckArgumentNull(target, "target");

            IEdmBooleanConstantExpression val = new EdmBooleanConstant(true);
            IEdmTerm term = CoreVocabularyModel.ComputedTerm;

            Debug.Assert(term != null, "term!=null");
            EdmVocabularyAnnotation annotation = new EdmVocabularyAnnotation(target, term, val);

            annotation.SetSerializationLocation(model, EdmVocabularyAnnotationSerializationLocation.Inline);
            model.SetVocabularyAnnotation(annotation);
        }
Ejemplo n.º 24
0
        public void AnnotatedModelShouldSupportAddingStringAnnotations()
        {
            var primaryModel    = new EdmModel();
            var entityContainer = new EdmEntityContainer("Fake", "Container");

            primaryModel.AddElement(entityContainer);

            var testSubject = new VocabularyAnnotationCache(primaryModel);

            var annotation = new EdmVocabularyAnnotation(entityContainer, new EdmTerm("fake", "foo", EdmPrimitiveTypeKind.String), new EdmStringConstant("bar"));

            testSubject.Add(annotation);
            testSubject.FindDeclaredVocabularyAnnotations(entityContainer).Should().Contain(annotation).And.HaveCount(1);
        }
Ejemplo n.º 25
0
            public async Task <IEdmModel> GetModelAsync(ModelContext context, CancellationToken cancellationToken)
            {
                var model = await InnerHandler.GetModelAsync(context, cancellationToken);

                var trueConstant = new EdmBooleanConstant(true);

                // Set computed annotation
                var tripType           = (EdmEntityType)model.SchemaElements.Single(e => e.Name == "Trip");
                var trackGuidProperty  = tripType.DeclaredProperties.Single(prop => prop.Name == "TrackGuid");
                var timeStampValueProp = model.EntityContainer.FindEntitySet("Airlines").EntityType().FindProperty("TimeStampValue");
                var computedTerm       = new EdmTerm("Org.OData.Core.V1", "Computed", EdmPrimitiveTypeKind.Boolean);
                var anno1 = new EdmVocabularyAnnotation(trackGuidProperty, computedTerm, trueConstant);
                var anno2 = new EdmVocabularyAnnotation(timeStampValueProp, computedTerm, trueConstant);

                ((EdmModel)model).SetVocabularyAnnotation(anno1);
                ((EdmModel)model).SetVocabularyAnnotation(anno2);

                var immutableTerm = new EdmTerm("Org.OData.Core.V1", "Immutable", EdmPrimitiveTypeKind.Boolean);

                var orderType  = (EdmEntityType)model.SchemaElements.Single(e => e.Name == "Order");
                var orderProp1 = orderType.DeclaredProperties.Single(prop => prop.Name == "ComputedProperty");
                var orderProp2 = orderType.DeclaredProperties.Single(prop => prop.Name == "ImmutableProperty");
                var orderProp3 = orderType.DeclaredProperties.Single(prop => prop.Name == "ComputedOrderDetail");
                var orderProp4 = orderType.DeclaredProperties.Single(prop => prop.Name == "ImmutableOrderDetail");

                ((EdmModel)model).SetVocabularyAnnotation(new EdmVocabularyAnnotation(orderProp1, computedTerm, trueConstant));
                ((EdmModel)model).SetVocabularyAnnotation(new EdmVocabularyAnnotation(orderProp2, immutableTerm, trueConstant));
                ((EdmModel)model).SetVocabularyAnnotation(new EdmVocabularyAnnotation(orderProp3, computedTerm, trueConstant));
                ((EdmModel)model).SetVocabularyAnnotation(new EdmVocabularyAnnotation(orderProp4, immutableTerm, trueConstant));

                var orderDetailType = (EdmComplexType)model.SchemaElements.Single(e => e.Name == "OrderDetail");
                var detailProp1     = orderDetailType.DeclaredProperties.Single(prop => prop.Name == "ComputedProperty");
                var detailProp2     = orderDetailType.DeclaredProperties.Single(prop => prop.Name == "ImmutableProperty");

                ((EdmModel)model).SetVocabularyAnnotation(new EdmVocabularyAnnotation(detailProp1, computedTerm, trueConstant));
                ((EdmModel)model).SetVocabularyAnnotation(new EdmVocabularyAnnotation(detailProp2, immutableTerm, trueConstant));

                var personType = (EdmEntityType)model.SchemaElements.Single(e => e.Name == "Person");
                var type       = personType.FindProperty("PersonId").Type;

                var isNullableField = typeof(EdmTypeReference).GetField("isNullable", BindingFlags.Instance | BindingFlags.NonPublic);

                if (isNullableField != null)
                {
                    isNullableField.SetValue(type, false);
                }

                return(model);
            }
Ejemplo n.º 26
0
        private static void AppendAnnotationForPermission(IEdmModel model)
        {
            IEdmEnumType enumType = model.SchemaElements.OfType <IEdmEnumType>().First(c => c.Name == "Permission");
            EdmTerm      term     = new EdmTerm("NS", "PermissionTerm", new EdmEnumTypeReference(enumType, true), appliesTo: "Property");

            ((EdmModel)model).AddElement(term);

            IEdmEntityType entityType = model.SchemaElements.OfType <IEdmEntityType>().First(c => c.Name == "Customer");
            IEdmProperty   property   = entityType.Properties().First(c => c.Name == "Name");

            EdmVocabularyAnnotation annotation = new EdmVocabularyAnnotation(property, term, new EdmEnumMemberExpression(enumType.Members.First(c => c.Name == "ReadOnly")));

            annotation.SetSerializationLocation(model, EdmVocabularyAnnotationSerializationLocation.Inline);
            ((EdmModel)model).SetVocabularyAnnotation(annotation);
        }
        private static void SetVocabularyAnnotation(this EdmModel model, IEdmVocabularyAnnotatable target,
                                                    IList <IEdmPropertyConstructor> properties, string qualifiedName)
        {
            Contract.Assert(model != null);
            Contract.Assert(target != null);

            IEdmTerm term = model.FindTerm(qualifiedName);

            if (term != null)
            {
                IEdmRecordExpression    record     = new EdmRecordExpression(properties);
                EdmVocabularyAnnotation annotation = new EdmVocabularyAnnotation(target, term, record);
                annotation.SetSerializationLocation(model, EdmVocabularyAnnotationSerializationLocation.Inline);
                model.SetVocabularyAnnotation(annotation);
            }
        }
Ejemplo n.º 28
0
        private static void AppendAnnotation(IEdmModel model)
        {
            EdmTerm term = new EdmTerm("NS", "FooBar", EdmCoreModel.Instance.GetString(true));

            ((EdmModel)model).AddElement(term);

            IEdmEnumType enumType = model.SchemaElements.OfType <IEdmEnumType>().First(c => c.Name == "Appliance");

            var member = enumType.Members.First(c => c.Name == "Stove");

            EdmVocabularyAnnotation annotation = new EdmVocabularyAnnotation(member, term, new EdmStringConstant("Stove Top"));

            // Note: OutOfLine can't work for the "EnumMember" because the OutofLine needs the full type of name.
            annotation.SetSerializationLocation(model, EdmVocabularyAnnotationSerializationLocation.Inline);
            ((EdmModel)model).SetVocabularyAnnotation(annotation);
        }
Ejemplo n.º 29
0
        public void CreatePathItemsReturnsForEscapeFunctionModel(bool enableEscaped, bool hasEscapedAnnotation, bool isComposable, string expected)
        {
            // Arrange
            EdmModel      model    = new EdmModel();
            EdmEntityType customer = new EdmEntityType("NS", "Customer");

            customer.AddKeys(customer.AddStructuralProperty("ID", EdmPrimitiveTypeKind.Int32));
            model.AddElement(customer);
            EdmFunction function = new EdmFunction("NS", "MyFunction", EdmCoreModel.Instance.GetString(false), true, null, isComposable);

            function.AddParameter("entity", new EdmEntityTypeReference(customer, false));
            function.AddParameter("param", EdmCoreModel.Instance.GetString(false));
            model.AddElement(function);
            EdmEntityContainer container = new EdmEntityContainer("NS", "Default");
            EdmEntitySet       customers = new EdmEntitySet(container, "Customers", customer);

            container.AddElement(customers);
            model.AddElement(container);

            if (hasEscapedAnnotation)
            {
                IEdmBooleanConstantExpression booleanConstant = new EdmBooleanConstant(true);
                IEdmTerm term = CommunityVocabularyModel.UrlEscapeFunctionTerm;
                EdmVocabularyAnnotation annotation = new EdmVocabularyAnnotation(function, term, booleanConstant);
                annotation.SetSerializationLocation(model, EdmVocabularyAnnotationSerializationLocation.Inline);
                model.SetVocabularyAnnotation(annotation);
            }

            OpenApiConvertSettings settings = new OpenApiConvertSettings
            {
                EnableUriEscapeFunctionCall        = enableEscaped,
                AddSingleQuotesForStringParameters = true,
            };
            ODataContext context = new ODataContext(model, settings);

            // Act
            var pathItems = context.CreatePathItems();

            // Assert
            Assert.NotNull(pathItems);
            Assert.Equal(4, pathItems.Count);

            Assert.Contains("/Customers", pathItems.Keys);
            Assert.Contains("/Customers/$count", pathItems.Keys);
            Assert.Contains("/Customers({ID})", pathItems.Keys);
            Assert.Contains(expected, pathItems.Keys);
        }
Ejemplo n.º 30
0
            public async Task <IEdmModel> GetModelAsync(ModelContext context, CancellationToken cancellationToken)
            {
                var model = await InnerHandler.GetModelAsync(context, cancellationToken);

                // Set computed annotation
                var tripType           = (EdmEntityType)model.SchemaElements.Single(e => e.Name == "Trip");
                var trackGuidProperty  = tripType.DeclaredProperties.Single(prop => prop.Name == "TrackGuid");
                var timeStampValueProp = model.EntityContainer.FindEntitySet("Airlines").EntityType().FindProperty("TimeStampValue");
                var term  = new EdmTerm("Org.OData.Core.V1", "Computed", EdmPrimitiveTypeKind.Boolean);
                var anno1 = new EdmVocabularyAnnotation(trackGuidProperty, term, new EdmBooleanConstant(true));
                var anno2 = new EdmVocabularyAnnotation(timeStampValueProp, term, new EdmBooleanConstant(true));

                ((EdmModel)model).SetVocabularyAnnotation(anno1);
                ((EdmModel)model).SetVocabularyAnnotation(anno2);

                return(model);
            }