private void CreateEntityTypeBody(EdmEntityType type, IEntityTypeConfiguration config)
        {
            CreateStructuralTypeBody(type, config);
            IEdmStructuralProperty[] keys = config.Keys.Select(p => type.DeclaredProperties.OfType<IEdmStructuralProperty>().First(dp => dp.Name == p.PropertyInfo.Name)).ToArray();
            type.AddKeys(keys);

            foreach (NavigationPropertyConfiguration navProp in config.NavigationProperties)
            {
                EdmNavigationPropertyInfo info = new EdmNavigationPropertyInfo();
                info.Name = navProp.Name;
                info.TargetMultiplicity = navProp.Multiplicity;
                info.Target = _types[navProp.RelatedClrType] as IEdmEntityType;
                //TODO: If target end has a multiplity of 1 this assumes the source end is 0..1.
                //      I think a better default multiplicity is *
                type.AddUnidirectionalNavigation(info);
            }
        }
        EdmEntityTypeWrapper AddTable(EdmModel model, TableData dataBuilder)
        {
            var propertyMap = new Dictionary<Field, EdmStructuralProperty>();

            var table = new EdmEntityType("sitecore.com", dataBuilder.Name);
            foreach (var field in dataBuilder.Schema.Fields)
            {
                var prop = table.AddStructuralProperty(field.Name, GetEdmType(field.ValueType), IsNullable(field.ValueType));                
                if (field.FieldType == FieldType.Key)
                {
                    table.AddKeys(prop);
                }
                propertyMap.Add(field, prop);
            }            
            model.AddElement(table);            

            return new EdmEntityTypeWrapper {Type = table, Properties = propertyMap};
        }
        public void GetEntityKeyValue_DerivedType()
        {
            // Arrange
            var entityInstance = new { Key = "key" };
            EdmEntityType baseEntityType = new EdmEntityType("NS", "Name");
            baseEntityType.AddKeys(baseEntityType.AddStructuralProperty("Key", EdmPrimitiveTypeKind.String));
            EdmEntityType derivedEntityType = new EdmEntityType("NS", "Derived", baseEntityType);

            EntityInstanceContext entityInstanceContext = new EntityInstanceContext(_writeContext, derivedEntityType.AsReference(), entityInstance);

            // Act
            var keyValue = ConventionsHelpers.GetEntityKeyValue(entityInstanceContext);

            // Assert
            Assert.Equal("'key'", keyValue);
        }
        public void GetEntityKeyValue_MultipleKeys_DerivedType()
        {
            // Arrange
            var entityInstance = new { Key1 = "key1", Key2 = 2, Key3 = true };
            EdmEntityType baseEntityType = new EdmEntityType("NS", "Name");
            baseEntityType.AddKeys(baseEntityType.AddStructuralProperty("Key1", EdmPrimitiveTypeKind.String));
            baseEntityType.AddKeys(baseEntityType.AddStructuralProperty("Key2", EdmPrimitiveTypeKind.Int32));
            baseEntityType.AddKeys(baseEntityType.AddStructuralProperty("Key3", EdmPrimitiveTypeKind.Boolean));
            EdmEntityType derivedEntityType = new EdmEntityType("NS", "Derived", baseEntityType);

            EntityInstanceContext entityInstanceContext = new EntityInstanceContext(_writeContext, derivedEntityType.AsReference(), entityInstance);

            // Act
            var keyValue = ConventionsHelpers.GetEntityKeyValue(entityInstanceContext);

            // Assert
            Assert.Equal("Key1='key1',Key2=2,Key3=true", keyValue);
        }
        public void GetEntityKeyValue_SingleKey_DifferentDataTypes(object value, object expectedValue)
        {
            // Arrange
            EdmEntityType entityType = new EdmEntityType("NS", "Name");
            entityType.AddKeys(entityType.AddStructuralProperty("Property", EdmPrimitiveTypeKind.String));
            var entityInstance = new { Property = value };

            EntityInstanceContext entityInstanceContext = new EntityInstanceContext(_writeContext, entityType.AsReference(), entityInstance);

            // Act
            var keyValue = ConventionsHelpers.GetEntityKeyValue(entityInstanceContext);

            // Assert
            Assert.Equal(expectedValue, keyValue);
        }
        public void GetEntityKeyValue_ThrowsForNullKeys_WithMultipleKeys()
        {
            // Arrange
            var entityInstance = new { Key1 = "abc", Key2 = "def", Key3 = (string)null };
            EdmEntityType entityType = new EdmEntityType("NS", "Name");
            entityType.AddKeys(entityType.AddStructuralProperty("Key1", EdmPrimitiveTypeKind.String));
            entityType.AddKeys(entityType.AddStructuralProperty("Key2", EdmPrimitiveTypeKind.Int32));
            entityType.AddKeys(entityType.AddStructuralProperty("Key3", EdmPrimitiveTypeKind.Boolean));

            EntityInstanceContext entityInstanceContext = new EntityInstanceContext(_writeContext, entityType.AsReference(), entityInstance);

            // Act & Assert
            Assert.Throws<InvalidOperationException>(
                () => ConventionsHelpers.GetEntityKeyValue(entityInstanceContext),
                "Key property 'Key3' of type 'NS.Name' is null. Key properties cannot have null values.");
        }
        public void ProcessRequest(HttpContext context)
        {
            if (!HttpContext.Current.Request.IsAuthenticated)
            {
                HttpContext.Current.GetOwinContext().Authentication.Challenge(new AuthenticationProperties { RedirectUri = HttpContext.Current.Request.FilePath }, "OAuth2Bearer");
                return;
            }
            MSRAHttpResponseMessage message = new MSRAHttpResponseMessage(this.ContextBase.Response);
            message.StatusCode = 200;
            message.SetHeader(ODataConstants.ContentTypeHeader, "application/json");
            // create the writer, indent for readability
            ODataMessageWriterSettings messageWriterSettings = new ODataMessageWriterSettings()
            {
                Indent = true,
                CheckCharacters = false,
                BaseUri = context.Request.Url

            };
            messageWriterSettings.SetContentType(ODataFormat.Json);
               messageWriterSettings.SetMetadataDocumentUri(new Uri("http://localhost:31435/odata/MSRAQuery/$metadata"));

            if (string.IsNullOrEmpty(QueryId))
            {
                AzureTestDBEntities db = new AzureTestDBEntities();
                var queries = db.MsrRecurringQueries.ToList().Take(1);

                ODataWorkspace workSpace = new ODataWorkspace();
                var collections = new List<ODataResourceCollectionInfo>();

                foreach (MsrRecurringQuery recurringQuery in queries)
                {

                    ODataResourceCollectionInfo collectionInfo = new ODataResourceCollectionInfo()
                    {
                        Name = "MsrRecurringQueries",
                        Url = new Uri(context.Request.Url+"data/" + recurringQuery.RecurringQueryID.ToString(), UriKind.Absolute)
                    };
                    collectionInfo.SetAnnotation<AtomResourceCollectionMetadata>(new AtomResourceCollectionMetadata()
                    {
                        Title = new AtomTextConstruct()
                        {
                            Text = "MsrRecurringQueries"//recurringQuery.RecurringQueryName
                        },
                    });
                    collections.Add(collectionInfo);

                }
                workSpace.Collections = collections.AsEnumerable<ODataResourceCollectionInfo>();

                using (ODataMessageWriter messageWriter = new ODataMessageWriter(message, messageWriterSettings))
                {
                    messageWriter.WriteServiceDocumentAsync(workSpace);
                }
            }

            else
            {
                EdmModel mainModel =(EdmModel) QueryMetadataHttpHandler.BuildODataModel();
                using (ODataMessageWriter messageWriter = new ODataMessageWriter(message, messageWriterSettings, mainModel))
                {
                    var msrRecurringQueryResultType = new EdmEntityType("mainNS", "MsrRecurringQuery", null);
                    IEdmPrimitiveType edmPrimitiveType1 = new MSRAEdmPrimitiveType("Int32", "Edm", EdmPrimitiveTypeKind.Int32, EdmSchemaElementKind.TypeDefinition, EdmTypeKind.Primitive);
                    IEdmPrimitiveType edmPrimitiveType2 = new MSRAEdmPrimitiveType("String", "Edm", EdmPrimitiveTypeKind.String, EdmSchemaElementKind.TypeDefinition, EdmTypeKind.Primitive);
                    IEdmPrimitiveType edmPrimitiveType3 = new MSRAEdmPrimitiveType("String", "Edm", EdmPrimitiveTypeKind.String, EdmSchemaElementKind.TypeDefinition, EdmTypeKind.Primitive);
                    IEdmPrimitiveType edmPrimitiveType4 = new MSRAEdmPrimitiveType("String", "Edm", EdmPrimitiveTypeKind.String, EdmSchemaElementKind.TypeDefinition, EdmTypeKind.Primitive);
                    IEdmPrimitiveType edmPrimitiveType5 = new MSRAEdmPrimitiveType("String", "Edm", EdmPrimitiveTypeKind.String, EdmSchemaElementKind.TypeDefinition, EdmTypeKind.Primitive);
                    IEdmPrimitiveType edmPrimitiveType6 = new MSRAEdmPrimitiveType("Decimal", "Edm", EdmPrimitiveTypeKind.Decimal, EdmSchemaElementKind.TypeDefinition, EdmTypeKind.Primitive);
                    msrRecurringQueryResultType.AddKeys(new EdmStructuralProperty(msrRecurringQueryResultType, "RowId", new EdmPrimitiveTypeReference(edmPrimitiveType1, false)));
                    msrRecurringQueryResultType.AddProperty(new EdmStructuralProperty(msrRecurringQueryResultType, "RowId", new EdmPrimitiveTypeReference(edmPrimitiveType1, false)));

                    msrRecurringQueryResultType.AddProperty(new EdmStructuralProperty(msrRecurringQueryResultType, "Pricing_Level", new EdmPrimitiveTypeReference(edmPrimitiveType2, false)));
                    msrRecurringQueryResultType.AddProperty(new EdmStructuralProperty(msrRecurringQueryResultType, "Business_Summary", new EdmPrimitiveTypeReference(edmPrimitiveType3, false)));
                    msrRecurringQueryResultType.AddProperty(new EdmStructuralProperty(msrRecurringQueryResultType, "Future_Flag", new EdmPrimitiveTypeReference(edmPrimitiveType4, false)));
                    msrRecurringQueryResultType.AddProperty(new EdmStructuralProperty(msrRecurringQueryResultType, "Fiscal_Month", new EdmPrimitiveTypeReference(edmPrimitiveType5, false)));
                    msrRecurringQueryResultType.AddProperty(new EdmStructuralProperty(msrRecurringQueryResultType, "MS_Sales_Amount_Const", new EdmPrimitiveTypeReference(edmPrimitiveType6, false)));
                    ODataWriter feedWriter = messageWriter.CreateODataFeedWriter(
                        mainModel.EntityContainers().Select(c => c.EntitySets().First()).First(), msrRecurringQueryResultType);
                    ODataFeed feed = new ODataFeed()
                    {
                        Id = "MsrRecurringQueries",

                    };

                    feedWriter.WriteStart(feed);

                    AzureTestDBEntities db = new AzureTestDBEntities();
                    var queries = db.T_annooli_231161891 ;
                    foreach (var recurringQuery in queries)
                    {
                        ODataEntry entry = this.GetODataEntry(recurringQuery);
                        feedWriter.WriteStart(entry);
                        feedWriter.WriteEnd();
                    }
                    feedWriter.WriteEnd();
                }
            }
        }
        public CustomersModelWithInheritance()
        {
            EdmModel model = new EdmModel();

            // complex type address
            EdmComplexType address = new EdmComplexType("NS", "Address");
            address.AddStructuralProperty("Street", EdmPrimitiveTypeKind.String);
            address.AddStructuralProperty("City", EdmPrimitiveTypeKind.String);
            address.AddStructuralProperty("State", EdmPrimitiveTypeKind.String);
            address.AddStructuralProperty("ZipCode", EdmPrimitiveTypeKind.String);
            address.AddStructuralProperty("Country", EdmPrimitiveTypeKind.String);
            model.AddElement(address);

            // entity type customer
            EdmEntityType customer = new EdmEntityType("NS", "Customer");
            customer.AddKeys(customer.AddStructuralProperty("ID", EdmPrimitiveTypeKind.Int32));
            customer.AddStructuralProperty("Name", EdmPrimitiveTypeKind.String);
            customer.AddStructuralProperty("Address", new EdmComplexTypeReference(address, isNullable: true));
            model.AddElement(customer);

            // derived entity type special customer
            EdmEntityType specialCustomer = new EdmEntityType("NS", "SpecialCustomer", customer);
            specialCustomer.AddStructuralProperty("SpecialCustomerProperty", EdmPrimitiveTypeKind.Guid);
            model.AddElement(specialCustomer);

            // entity type order
            EdmEntityType order = new EdmEntityType("NS", "Order");
            order.AddKeys(order.AddStructuralProperty("ID", EdmPrimitiveTypeKind.Int32));
            order.AddStructuralProperty("Amount", EdmPrimitiveTypeKind.Int32);
            model.AddElement(order);

            // derived entity type special order
            EdmEntityType specialOrder = new EdmEntityType("NS", "SpecialOrder", order);
            specialOrder.AddStructuralProperty("SpecialOrderProperty", EdmPrimitiveTypeKind.Guid);
            model.AddElement(specialOrder);

            // entity sets
            EdmEntityContainer container = new EdmEntityContainer("NS", "ModelWithInheritance");
            model.AddElement(container);
            EdmEntitySet customers = container.AddEntitySet("Customers", customer);
            EdmEntitySet orders = container.AddEntitySet("Orders", order);

            // actions
            EdmFunctionImport upgradeCustomer = container.AddFunctionImport(
                "upgrade", returnType: null, entitySet: new EdmEntitySetReferenceExpression(customers), sideEffecting: true, composable: false, bindable: true);
            upgradeCustomer.AddParameter("entity", new EdmEntityTypeReference(customer, false));
            EdmFunctionImport upgradeSpecialCustomer = container.AddFunctionImport(
                "specialUpgrade", returnType: null, entitySet: new EdmEntitySetReferenceExpression(customers), sideEffecting: true, composable: false, bindable: true);
            upgradeSpecialCustomer.AddParameter("entity", new EdmEntityTypeReference(specialCustomer, false));

            // navigation properties
            customers.AddNavigationTarget(
                customer.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo
                {
                    Name = "Orders",
                    TargetMultiplicity = EdmMultiplicity.Many,
                    Target = order
                }),
                orders);
            orders.AddNavigationTarget(
                 order.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo
                 {
                     Name = "Customer",
                     TargetMultiplicity = EdmMultiplicity.ZeroOrOne,
                     Target = customer
                 }),
                customers);

            // navigation properties on derived types.
            customers.AddNavigationTarget(
                specialCustomer.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo
                {
                    Name = "SpecialOrders",
                    TargetMultiplicity = EdmMultiplicity.Many,
                    Target = order
                }),
                orders);
            orders.AddNavigationTarget(
                 specialOrder.AddUnidirectionalNavigation(new EdmNavigationPropertyInfo
                 {
                     Name = "SpecialCustomer",
                     TargetMultiplicity = EdmMultiplicity.ZeroOrOne,
                     Target = customer
                 }),
                customers);
            model.SetAnnotationValue<BindableProcedureFinder>(model, new BindableProcedureFinder(model));

            // set properties
            Model = model;
            Container = container;
            Customer = customer;
            Order = order;
            Address = address;
            SpecialCustomer = specialCustomer;
            SpecialOrder = specialOrder;
            Orders = orders;
            Customers = customers;
            UpgradeCustomer = upgradeCustomer;
        }
        public void ApplyProperty_IgnoresKeyProperty_WhenPatchKeyModeIsIgnore()
        {
            // Arrange
            ODataProperty property = new ODataProperty { Name = "Key1", Value = "Value1" };
            EdmEntityType entityType = new EdmEntityType("namespace", "name");
            entityType.AddKeys(new EdmStructuralProperty(entityType, "Key1", EdmLibHelpers.GetEdmPrimitiveTypeReferenceOrNull(typeof(string))));
            EdmEntityTypeReference entityTypeReference = new EdmEntityTypeReference(entityType, isNullable: false);
            ODataDeserializerProvider provider = new DefaultODataDeserializerProvider(EdmCoreModel.Instance);

            var resource = new Mock<IDelta>(MockBehavior.Strict);

            // Act
            ODataEntryDeserializer.ApplyProperty(property, entityTypeReference, resource.Object, provider, new ODataDeserializerContext { IsPatchMode = true, PatchKeyMode = PatchKeyMode.Ignore });

            // Assert
            resource.Verify();
        }
        public void ApplyProperty_ThrowsOnKeyProperty_WhenPatchKeyModeIsThrow()
        {
            // Arrange
            ODataProperty property = new ODataProperty { Name = "Key1", Value = "Value1" };
            EdmEntityType entityType = new EdmEntityType("namespace", "name");
            entityType.AddKeys(new EdmStructuralProperty(entityType, "Key1", EdmLibHelpers.GetEdmPrimitiveTypeReferenceOrNull(typeof(string))));
            EdmEntityTypeReference entityTypeReference = new EdmEntityTypeReference(entityType, isNullable: false);
            ODataDeserializerProvider provider = new DefaultODataDeserializerProvider(EdmCoreModel.Instance);

            var resource = new Mock<IDelta>(MockBehavior.Strict);

            // Act && Assert
            Assert.Throws<InvalidOperationException>(
                () => ODataEntryDeserializer.ApplyProperty(property, entityTypeReference, resource.Object, provider, new ODataDeserializerContext { IsPatchMode = true, PatchKeyMode = PatchKeyMode.Throw }),
                "Cannot apply PATCH on key property 'Key1' on entity type 'namespace.name' when 'PatchKeyMode' is 'Throw'.");
        }
 /// <summary>
 /// Create a new type with the standard set of properties(PK, RK and TimeStamp).
 /// </summary>
 /// <param name="namespaceName">Namespace the entity belongs to.</param>
 /// <param name="name">Name of the entity.</param>
 /// <returns>The EdmEntityType created.</returns>
 internal static EdmEntityType CreateEntityType(string namespaceName, string name)
 {
     EdmEntityType entityType = new EdmEntityType(namespaceName, name, null, false, true);
     entityType.AddKeys(
         entityType.AddStructuralProperty("RowKey", EdmPrimitiveTypeKind.String),
         entityType.AddStructuralProperty("PartitionKey", EdmPrimitiveTypeKind.String));
         entityType.AddStructuralProperty("Timestamp", EdmCoreModel.Instance.GetDateTime(false), null, EdmConcurrencyMode.Fixed);  // We need this because we want to ensure that this property is not used for optimistic concurrency checks. 
     return entityType;
 }
        public void DollarMetadata_Works_WithMultipleReferentialConstraints_ForUntypedModel()
        {
            // Arrange
            EdmModel model = new EdmModel();

            EdmEntityType customer = new EdmEntityType("DefaultNamespace", "Customer");
            customer.AddKeys(customer.AddStructuralProperty("CustomerId", EdmCoreModel.Instance.GetInt32(false)));
            customer.AddStructuralProperty("Name", EdmCoreModel.Instance.GetString(false));
            model.AddElement(customer);

            EdmEntityType order = new EdmEntityType("DefaultNamespace", "Order");
            order.AddKeys(order.AddStructuralProperty("OrderId", EdmCoreModel.Instance.GetInt32(false)));
            EdmStructuralProperty orderCustomerId = order.AddStructuralProperty("CustomerForeignKey", EdmCoreModel.Instance.GetInt32(true));
            model.AddElement(order);

            customer.AddBidirectionalNavigation(
                new EdmNavigationPropertyInfo
                {
                    Name = "Orders",
                    Target = order,
                    TargetMultiplicity = EdmMultiplicity.Many
                },
                new EdmNavigationPropertyInfo
                {
                    Name = "Customer",
                    TargetMultiplicity = EdmMultiplicity.ZeroOrOne,
                    DependentProperties = new[] { orderCustomerId },
                });

            const string expect =
                "        <ReferentialConstraint>\r\n" +
                "          <Principal Role=\"Customer\">\r\n" +
                "            <PropertyRef Name=\"CustomerId\" />\r\n" +
                "          </Principal>\r\n" +
                "          <Dependent Role=\"Orders\">\r\n" +
                "            <PropertyRef Name=\"CustomerForeignKey\" />\r\n" +
                "          </Dependent>\r\n" +
                "        </ReferentialConstraint>";

            HttpServer server = new HttpServer();
            server.Configuration.Routes.MapODataServiceRoute("odata", "odata", model);

            HttpClient client = new HttpClient(server);

            // Act
            HttpResponseMessage response = client.GetAsync("http://localhost/odata/$metadata").Result;

            // Assert
            Assert.True(response.IsSuccessStatusCode);
            Assert.Equal("application/xml", response.Content.Headers.ContentType.MediaType);
            Assert.Contains(expect, response.Content.ReadAsStringAsync().Result);
        }
Example #13
0
 private void CreateEntityTypeBody(EdmEntityType type, EntityTypeConfiguration config)
 {
     CreateStructuralTypeBody(type, config);
     IEdmStructuralProperty[] keys = config.Keys.Select(p => type.DeclaredProperties.OfType<IEdmStructuralProperty>().First(dp => dp.Name == p.PropertyInfo.Name)).ToArray();
     type.AddKeys(keys);
 }