public void TryMatchMediaTypeWithBinaryRawValueMatchesRequest_OnODataSingleton() { // Arrange IEdmModel model = GetBinaryModel(); IEdmSingleton rawSingletonValue = model.EntityContainer.FindSingleton("RawSingletonValue"); IEdmEntityType rawValueEntity = model.SchemaElements.OfType <IEdmEntityType>().First(e => e.Name == "RawValueEntity"); IEdmStructuralProperty property = rawValueEntity.FindProperty("BinaryProperty") as IEdmStructuralProperty; Assert.NotNull(property); // Guard PropertySegment propertySegment = new PropertySegment(property); ODataPath path = new ODataPath(new SingletonSegment(rawSingletonValue), propertySegment, new ValueSegment(propertySegment.EdmType)); ODataBinaryValueMediaTypeMapping mapping = new ODataBinaryValueMediaTypeMapping(); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/RawSingletonValue/BinaryProperty/$value"); request.ODataProperties().Path = path; // Act double mapResult = mapping.TryMatchMediaType(request); // Assert Assert.Equal(1.0, mapResult); }
private static string GetRootElementName(ODataPath path) { if (path != null) { ODataPathSegment lastSegment = path.Segments.LastOrDefault(); if (lastSegment != null) { OperationSegment actionSegment = lastSegment as OperationSegment; if (actionSegment != null) { IEdmAction action = actionSegment.Operations.Single() as IEdmAction; if (action != null) { return(action.Name); } } PropertySegment propertyAccessSegment = lastSegment as PropertySegment; if (propertyAccessSegment != null) { return(propertyAccessSegment.Property.Name); } } } return(null); }
public void TryMatchMediaType_WithNonRawvalueRequest_DoesntMatchRequest() { IEdmModel model = ODataTestUtil.GetEdmModel(); IEdmEntitySet people = model.EntityContainer.FindEntitySet("People"); IEdmEntityType personType = model.SchemaElements.OfType <IEdmEntityType>().First(e => e.Name == "FormatterPerson"); IEdmStructuralProperty ageProperty = personType.FindProperty("Age") as IEdmStructuralProperty; Assert.NotNull(ageProperty); // Guard PropertySegment propertySegment = new PropertySegment(ageProperty); var keys = new[] { new KeyValuePair <string, object>("PerId", 1) }; KeySegment keySegment = new KeySegment(keys, personType, people); ODataPath path = new ODataPath(new EntitySetSegment(people), keySegment, propertySegment); ODataPrimitiveValueMediaTypeMapping mapping = new ODataPrimitiveValueMediaTypeMapping(); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/People(1)/Age/"); request.ODataProperties().Path = path; double mapResult = mapping.TryMatchMediaType(request); Assert.Equal(0, mapResult); }
public void TryMatchMediaType_DoesnotMatchRequest_ODataEnumValueMediaTypeMappingWithNonRawvalueRequest() { // Arrange IEdmModel model = GetEnumModel(); IEdmEntitySet enumEntity = model.EntityContainer.FindEntitySet("EnumEntity"); IEdmEntityType enumEntityType = model.SchemaElements.OfType <IEdmEntityType>().First(e => e.Name == "EnumEntity"); IEdmStructuralProperty property = enumEntityType.FindProperty("EnumProperty") as IEdmStructuralProperty; Assert.NotNull(property); // Guard PropertySegment propertySegment = new PropertySegment(property); var keys = new[] { new KeyValuePair <string, object>("Id", 1) }; KeySegment keySegment = new KeySegment(keys, enumEntityType, enumEntity); ODataPath path = new ODataPath(new EntitySetSegment(enumEntity), keySegment, propertySegment); ODataEnumValueMediaTypeMapping mapping = new ODataEnumValueMediaTypeMapping(); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/EnumEntity(1)/EnumProperty/"); request.ODataProperties().Path = path; // Act double mapResult = mapping.TryMatchMediaType(request); // Assert Assert.Equal(0, mapResult); }
public void TryMatchMediaTypeWithBinaryRawValueMatchesRequest() { IEdmModel model = GetBinaryModel(); IEdmEntitySet rawValues = model.EntityContainer.FindEntitySet("RawValue"); IEdmEntityType rawValueEntity = model.SchemaElements.OfType <IEdmEntityType>().First(e => e.Name == "RawValueEntity"); IEdmStructuralProperty property = rawValueEntity.FindProperty("BinaryProperty") as IEdmStructuralProperty; Assert.NotNull(property); // Guard PropertySegment propertySegment = new PropertySegment(property); var keys = new[] { new KeyValuePair <string, object>("Id", 1) }; KeySegment keySegment = new KeySegment(keys, rawValueEntity, rawValues); ODataPath path = new ODataPath(new EntitySetSegment(rawValues), keySegment, propertySegment, new ValueSegment(propertySegment.EdmType)); ODataBinaryValueMediaTypeMapping mapping = new ODataBinaryValueMediaTypeMapping(); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/RawValue(1)/BinaryProperty/$value"); request.ODataProperties().Path = path; double mapResult = mapping.TryMatchMediaType(request); Assert.Equal(1.0, mapResult); }
internal static IEdmTypeReference GetExpectedPayloadType(Type type, ODataPath path, IEdmModel model) { IEdmTypeReference expectedPayloadType = null; if (typeof(IEdmObject).IsAssignableFrom(type)) { // typeless mode. figure out the expected payload type from the OData Path. IEdmType edmType = path.EdmType; if (edmType != null) { expectedPayloadType = EdmLibHelpers.ToEdmTypeReference(edmType, isNullable: false); if (expectedPayloadType.TypeKind() == EdmTypeKind.Collection) { IEdmTypeReference elementType = expectedPayloadType.AsCollection().ElementType(); if (elementType.IsEntity()) { // collection of entities cannot be CREATE/UPDATEd. Instead, the request would contain a single entry. expectedPayloadType = elementType; } } } } else { TryGetInnerTypeForDelta(ref type); expectedPayloadType = model.GetEdmTypeReference(type); } return(expectedPayloadType); }
public void TryMatchMediaType_WithNonRawvalueRequest_DoesntMatchRequest_OnSingleton() { // Arrange IEdmModel model = ODataTestUtil.GetEdmModel(); IEdmSingleton president = model.EntityContainer.FindSingleton("President"); model.SchemaElements.OfType <IEdmEntityType>().First(e => e.Name == "FormatterPerson"); IEdmEntityType personType = model.SchemaElements.OfType <IEdmEntityType>().First(e => e.Name == "FormatterPerson"); IEdmStructuralProperty ageProperty = personType.FindProperty("Age") as IEdmStructuralProperty; Assert.NotNull(ageProperty); // Guard PropertySegment propertySegment = new PropertySegment(ageProperty); ODataPath path = new ODataPath(new SingletonSegment(president), propertySegment); ODataPrimitiveValueMediaTypeMapping mapping = new ODataPrimitiveValueMediaTypeMapping(); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/President/Age/"); request.ODataProperties().Path = path; // Act double mapResult = mapping.TryMatchMediaType(request); // Assert Assert.Equal(0, mapResult); }
public override string SelectAction(ODataPath odataPath, HttpControllerContext controllerContext, ILookup<string, HttpActionDescriptor> actionMap) { var controllerType = controllerContext.ControllerDescriptor.ControllerType; if (typeof(CustomersController) == controllerType) { if (odataPath.PathTemplate.Equals("~/entityset/key/navigation")) //POST OR GET { controllerContext.RouteData.Values["orderID"] = ((KeySegment)odataPath.Segments[1]).Keys.Single().Value; return controllerContext.Request.Method.ToString(); } } else if (typeof(OrdersController) == controllerType) { if (odataPath.PathTemplate.Equals("~/entityset/key/navigation")) //POST OR GET { controllerContext.RouteData.Values["customerID"] = ((KeySegment)odataPath.Segments[1]).Keys.Single().Value; return controllerContext.Request.Method.ToString(); } if (odataPath.PathTemplate.Equals("~/entityset/key/navigation/key")) //PATCH OR DELETE { controllerContext.RouteData.Values["customerID"] = ((KeySegment)odataPath.Segments[1]).Keys.Single().Value; controllerContext.RouteData.Values["key"] = ((KeySegment)odataPath.Segments[3]).Keys.Single().Value; return controllerContext.Request.Method.ToString(); } } return base.SelectAction(odataPath, controllerContext, actionMap); }
public void GetETagTEntity_Returns_ETagInHeader() { // Arrange CustomersModelWithInheritance model = new CustomersModelWithInheritance(); HttpRequestMessage request = new HttpRequestMessage(); request.EnableHttpDependencyInjectionSupport(model.Model); Dictionary <string, object> properties = new Dictionary <string, object> { { "City", "Foo" } }; EntityTagHeaderValue etagHeaderValue = new DefaultODataETagHandler().CreateETag(properties); ODataPath odataPath = new ODataPath(new EntitySetSegment(model.Customers)); request.ODataProperties().Path = odataPath; // Act ETag <Customer> result = request.GetETag <Customer>(etagHeaderValue); dynamic dynamicResult = result; // Assert Assert.Equal("Foo", result["City"]); Assert.Equal("Foo", dynamicResult.City); }
public override string SelectAction(ODataPath odataPath, HttpControllerContext controllerContext, ILookup <string, HttpActionDescriptor> actionMap) { var controllerType = controllerContext.ControllerDescriptor.ControllerType; if (typeof(CustomersController) == controllerType) { if (odataPath.PathTemplate.Equals("~/entityset/key/navigation")) //POST OR GET { controllerContext.RouteData.Values["orderID"] = ((KeySegment)odataPath.Segments[1]).Keys.Single().Value; return(controllerContext.Request.Method.ToString()); } } else if (typeof(OrdersController) == controllerType) { if (odataPath.PathTemplate.Equals("~/entityset/key/navigation")) //POST OR GET { controllerContext.RouteData.Values["customerID"] = ((KeySegment)odataPath.Segments[1]).Keys.Single().Value; return(controllerContext.Request.Method.ToString()); } if (odataPath.PathTemplate.Equals("~/entityset/key/navigation/key")) //PATCH OR DELETE { controllerContext.RouteData.Values["customerID"] = ((KeySegment)odataPath.Segments[1]).Keys.Single().Value; controllerContext.RouteData.Values["key"] = ((KeySegment)odataPath.Segments[3]).Keys.Single().Value; return(controllerContext.Request.Method.ToString()); } } return(base.SelectAction(odataPath, controllerContext, actionMap)); }
private static PropertySegment GetProperty(HttpRequestMessage request) { ODataPath odataPath = request.ODataProperties().Path; if (odataPath == null || odataPath.Segments.Count < 2) { return(null); } return(odataPath.Segments[odataPath.Segments.Count - 2] as PropertySegment); }
private static bool IsDynamicProperty(HttpRequestMessage request) { ODataPath odataPath = request.ODataProperties().Path; if (odataPath == null || odataPath.Segments.Count < 2) { return(false); } return(odataPath.Segments[odataPath.Segments.Count - 2] is DynamicPathSegment); }
/// <inheritdoc/> protected async override Task <HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { if (request == null) { throw Error.ArgumentNull("request"); } HttpConfiguration configuration = request.GetConfiguration(); if (configuration == null) { throw Error.InvalidOperation(SRResources.RequestMustContainConfiguration); } HttpResponseMessage response = await base.SendAsync(request, cancellationToken); // Do not interfere with null responses, we want to buble it up to the top. // Do not handle 204 responses as the spec says a 204 response must not include an ETag header // unless the request's representation data was saved without any transformation applied to the body // (i.e., the resource's new representation data is identical to the representation data received in the // PUT request) and the ETag value reflects the new representation. // Even in that case returning an ETag is optional and it requires access to the original object which is // not possible with the current architecture, so if the user is interested he can set the ETag in that // case by himself on the response. if (response == null || !response.IsSuccessStatusCode || response.StatusCode == HttpStatusCode.NoContent) { return(response); } ODataPath path = request.ODataProperties().Path; IEdmModel model = request.GetModel(); IEdmEntityType edmType = GetSingleEntityEntityType(path); object value = GetSingleEntityObject(response); IEdmEntityTypeReference typeReference = GetTypeReference(model, edmType, value); if (typeReference != null) { ResourceContext context = CreateInstanceContext(typeReference, value); context.EdmModel = model; context.NavigationSource = path.NavigationSource; IETagHandler etagHandler = configuration.GetETagHandler(); EntityTagHeaderValue etag = CreateETag(context, etagHandler); if (etag != null) { response.Headers.ETag = etag; } } return(response); }
public override string SelectController(ODataPath odataPath, HttpRequestMessage request) { // We use always use the last navigation as the controller vs. the initial entityset if (odataPath.PathTemplate.Contains("~/entityset/key/navigation")) { // Find controller. Controller should be last navigation property return odataPath.Segments[odataPath.Segments.Count - 1] is NavigationPropertySegment ? odataPath.Segments[odataPath.Segments.Count - 1].Identifier : odataPath.Segments[odataPath.Segments.Count - 2].Identifier; } return base.SelectController(odataPath, request); }
public override string SelectController(ODataPath odataPath, HttpRequestMessage request) { // We use always use the last navigation as the controller vs. the initial entityset if (odataPath.PathTemplate.Contains("~/entityset/key/navigation")) { // Find controller. Controller should be last navigation property return(odataPath.Segments[odataPath.Segments.Count - 1] is NavigationPropertySegment ? odataPath.Segments[odataPath.Segments.Count - 1].Identifier : odataPath.Segments[odataPath.Segments.Count - 2].Identifier); } return(base.SelectController(odataPath, request)); }
public void GetIfMatchOrNoneMatch_ReturnsETag_SetETagHeaderValue(string header) { // Arrange HttpRequestMessage request = new HttpRequestMessage(); HttpConfiguration cofiguration = new HttpConfiguration(); request.SetConfiguration(cofiguration); Dictionary <string, object> properties = new Dictionary <string, object> { { "Name", "Foo" } }; EntityTagHeaderValue etagHeaderValue = new DefaultODataETagHandler().CreateETag(properties); if (header.Equals("IfMatch")) { request.Headers.IfMatch.Add(etagHeaderValue); } else { request.Headers.IfNoneMatch.Add(etagHeaderValue); } ODataModelBuilder builder = new ODataModelBuilder(); EntityTypeConfiguration <Customer> customer = builder.EntityType <Customer>(); customer.HasKey(c => c.Id); customer.Property(c => c.Id); customer.Property(c => c.Name).IsConcurrencyToken(); builder.EntitySet <Customer>("Customers"); IEdmModel model = builder.GetEdmModel(); var customers = model.FindDeclaredEntitySet("Customers"); Mock <ODataPathSegment> mockSegment = new Mock <ODataPathSegment> { CallBase = true }; mockSegment.Setup(s => s.GetEdmType(null)).Returns(model.GetEdmType(typeof(Customer))); mockSegment.Setup(s => s.GetNavigationSource(null)).Returns((IEdmNavigationSource)customers); ODataPath odataPath = new ODataPath(new[] { mockSegment.Object }); request.ODataProperties().Path = odataPath; request.ODataProperties().Model = model; ODataQueryContext context = new ODataQueryContext(model, typeof(Customer)); // Act ODataQueryOptions <Customer> query = new ODataQueryOptions <Customer>(context, request); ETag result = header.Equals("IfMatch") ? query.IfMatch : query.IfNoneMatch; dynamic dynamicResult = result; // Assert Assert.Equal("Foo", result["Name"]); Assert.Equal("Foo", dynamicResult.Name); }
/// <summary> /// Selects the appropriate action based on the parsed OData URI. /// </summary> /// <param name="odataPath">Parsed OData URI</param> /// <param name="controllerContext">Context for HttpController</param> /// <param name="actionMap">Mapping from action names to HttpActions</param> /// <returns>String corresponding to controller action name</returns> public string SelectAction( ODataPath odataPath, HttpControllerContext controllerContext, ILookup <string, HttpActionDescriptor> actionMap) { // TODO GitHubIssue#44 : implement action selection for $ref, navigation scenarios, etc. Ensure.NotNull(odataPath, "odataPath"); Ensure.NotNull(controllerContext, "controllerContext"); Ensure.NotNull(actionMap, "actionMap"); if (!(controllerContext.Controller is RestierController)) { // RESTier cannot select action on controller which is not RestierController. return(null); } HttpMethod method = controllerContext.Request.Method; ODataPathSegment lastSegment = odataPath.Segments.LastOrDefault(); bool isAction = IsAction(lastSegment); if (method == HttpMethod.Get && !IsMetadataPath(odataPath) && !isAction) { return(MethodNameOfGet); } if (method == HttpMethod.Post && isAction) { return(MethodNameOfPostAction); } if (method == HttpMethod.Post) { return(MethodNameOfPost); } if (method == HttpMethod.Delete) { return(MethodNameOfDelete); } if (method == HttpMethod.Put) { return(MethodNameOfPut); } if (method == new HttpMethod("PATCH")) { return(MethodNameOfPatch); } return(null); }
private ODataQueryContext GetODataQueryContext() { IEdmEntitySet set = _edmModel.EntityContainer.EntitySets() // .FirstOrDefault(_ => (_.Type as EdmCollectionType)?.ElementType.Definition.FullTypeName() == typeof(TDto).FullName); .FirstOrDefault(_ => (_.Type as EdmCollectionType)?.ElementType.Definition.FullTypeName() == $"{_elementClrType.Namespace}.{_elementClrType.Name}"); // ODataPath path = new ODataPath(); ODataPath path = new ODataPath(new EntitySetSegment(set)); // new EntitySetPathSegment("FakeEntitySet"),new KeyValuePathSegment("FakeKey"),new PropertyAccessPathSegment("FakeProperty"),new ValuePathSegment() ODataQueryContext context = new ODataQueryContext(_edmModel, _elementClrType, path); return(context); }
public override string SelectController(System.Web.OData.Routing.ODataPath odataPath, HttpRequestMessage request) { if (odataPath.PathTemplate.StartsWith("~/unboundfunction")) { var item = odataPath.Segments.FirstOrDefault(); if (item.Identifier.StartsWith(Constants.ValidationFunctionName)) { return(Constants.ExtendedMetadataControllerName); } } return(null); }
private Uri CreateUriFromPath(ODataPath path) { var segments = path.Segments; var computedUri = _serviceRoot; // Append each segment to base uri foreach (ODataPathSegment segment in segments) { KeySegment keySegment = segment as KeySegment; if (keySegment != null) { computedUri = AppendKeyExpression(computedUri, keySegment.Keys); continue; } EntitySetSegment entitySetSegment = segment as EntitySetSegment; if (entitySetSegment != null) { computedUri = AppendSegment(computedUri, entitySetSegment.EntitySet.Name); continue; } SingletonSegment singletonSegment = segment as SingletonSegment; if (singletonSegment != null) { computedUri = AppendSegment(computedUri, singletonSegment.Singleton.Name); continue; } var typeSegment = segment as TypeSegment; if (typeSegment != null) { var edmType = typeSegment.EdmType; if (edmType.TypeKind == EdmTypeKind.Collection) { var collectionType = (IEdmCollectionType)edmType; edmType = collectionType.ElementType.Definition; } computedUri = AppendSegment(computedUri, edmType.FullTypeName()); } else { computedUri = AppendSegment( computedUri, ((NavigationPropertySegment)segment).NavigationProperty.Name); } } return(computedUri); }
public virtual string SelectController(ODataPath odataPath, HttpRequestMessage request) { SingletonSegment singletonSegment = odataPath.Segments.FirstOrDefault() as SingletonSegment; if (singletonSegment != null) { var edmType = odataPath.EdmType as EdmEntityType; if (edmType != null && edmType.Name == "Manufacturer") { return("Manufacturers"); } } return(null); }
private ODataDeserializer GetDeserializer(Type type, ODataPath path, IEdmModel model, ODataDeserializerProvider deserializerProvider, out IEdmTypeReference expectedPayloadType) { expectedPayloadType = GetExpectedPayloadType(type, path, model); // Get the deserializer using the CLR type first from the deserializer provider. ODataDeserializer deserializer = deserializerProvider.GetODataDeserializer(type, Request); if (deserializer == null && expectedPayloadType != null) { // we are in typeless mode, get the deserializer using the edm type from the path. deserializer = deserializerProvider.GetEdmTypeDeserializer(expectedPayloadType); } return(deserializer); }
public string SelectAction(ODataPath odataPath, HttpControllerContext controllerContext, ILookup <string, HttpActionDescriptor> actionMap) { if (odataPath.PathTemplate == "~/singleton") { const string actionName = "GetSingleton"; if (actionMap.Contains(actionName)) { var segment = odataPath.Segments[0] as SingletonSegment; controllerContext.RouteData.Values["name"] = segment.Singleton.Name; return(actionName); } } return(null); }
internal static IEdmAction GetAction(ODataDeserializerContext readContext) { if (readContext == null) { throw Error.ArgumentNull("readContext"); } ODataPath path = readContext.Path; if (path == null || path.Segments.Count == 0) { throw new SerializationException(SRResources.ODataPathMissing); } IEdmAction action = null; if (path.PathTemplate == "~/unboundaction") { // only one segment, it may be an unbound action OperationImportSegment unboundActionSegment = path.Segments.Last() as OperationImportSegment; if (unboundActionSegment != null) { IEdmActionImport actionImport = unboundActionSegment.OperationImports.First() as IEdmActionImport; if (actionImport != null) { action = actionImport.Action; } } } else { // otherwise, it may be a bound action OperationSegment actionSegment = path.Segments.Last() as OperationSegment; if (actionSegment != null) { action = actionSegment.Operations.First() as IEdmAction; } } if (action == null) { string message = Error.Format(SRResources.RequestNotActionInvocation, path.ToString()); throw new SerializationException(message); } return(action); }
public override string SelectAction(System.Web.OData.Routing.ODataPath odataPath, HttpControllerContext controllerContext, ILookup <string, HttpActionDescriptor> actionMap) { if (odataPath.PathTemplate.StartsWith("~/unboundfunction")) { var funcId = ((OperationImportSegment)odataPath.Segments[0]).Identifier; var action = actionMap.FirstOrDefault(a => a.Key == funcId)?.FirstOrDefault(); if (action == null) { return(null); } return(action.ActionName); } return(null); }
public void GetIfMatchOrNoneMatch_ReturnsETag_SetETagHeaderValue(string header) { // Arrange HttpRequestMessage request = new HttpRequestMessage(); Dictionary <string, object> properties = new Dictionary <string, object> { { "Name", "Foo" } }; EntityTagHeaderValue etagHeaderValue = new DefaultODataETagHandler().CreateETag(properties); if (header.Equals("IfMatch")) { request.Headers.IfMatch.Add(etagHeaderValue); } else { request.Headers.IfNoneMatch.Add(etagHeaderValue); } ODataModelBuilder builder = new ODataModelBuilder(); EntityTypeConfiguration <Customer> customer = builder.EntityType <Customer>(); customer.HasKey(c => c.Id); customer.Property(c => c.Id); customer.Property(c => c.Name).IsConcurrencyToken(); builder.EntitySet <Customer>("Customers"); IEdmModel model = builder.GetEdmModel(); var customers = model.FindDeclaredEntitySet("Customers"); EntitySetSegment entitySetSegment = new EntitySetSegment(customers); ODataPath odataPath = new ODataPath(new[] { entitySetSegment }); request.ODataProperties().Path = odataPath; request.EnableHttpDependencyInjectionSupport(model); ODataQueryContext context = new ODataQueryContext(model, typeof(Customer)); // Act ODataQueryOptions <Customer> query = new ODataQueryOptions <Customer>(context, request); ETag result = header.Equals("IfMatch") ? query.IfMatch : query.IfNoneMatch; dynamic dynamicResult = result; // Assert Assert.Equal("Foo", result["Name"]); Assert.Equal("Foo", dynamicResult.Name); }
public ODataDeltaFeedSerializerTests() { _model = SerializationTestsHelpers.SimpleCustomerOrderModel(); _customerSet = _model.EntityContainer.FindEntitySet("Customers"); _model.SetAnnotationValue(_customerSet.EntityType(), new ClrTypeAnnotation(typeof(Customer))); _path = new ODataPath(new EntitySetSegment(_customerSet)); _customers = new[] { new Customer() { FirstName = "Foo", LastName = "Bar", ID = 10, HomeAddress = new Address() { Street = "Street", ZipCode = null, } }, new Customer() { FirstName = "Foo", LastName = "Bar", ID = 42, } }; _deltaFeedCustomers = new EdmChangedObjectCollection(_customerSet.EntityType()); EdmDeltaEntityObject newCustomer = new EdmDeltaEntityObject(_customerSet.EntityType()); newCustomer.TrySetPropertyValue("ID", 10); newCustomer.TrySetPropertyValue("FirstName", "Foo"); EdmDeltaComplexObject newCustomerAddress = new EdmDeltaComplexObject(_model.FindType("Default.Address") as IEdmComplexType); newCustomerAddress.TrySetPropertyValue("Street", "Street"); newCustomerAddress.TrySetPropertyValue("ZipCode", null); newCustomer.TrySetPropertyValue("HomeAddress", newCustomerAddress); _deltaFeedCustomers.Add(newCustomer); _customersType = _model.GetEdmTypeReference(typeof(Customer[])).AsCollection(); _writeContext = new ODataSerializerContext() { NavigationSource = _customerSet, Model = _model, Path = _path }; _serializerProvider = DependencyInjectionHelper.GetDefaultODataSerializerProvider(); }
// This function is used to determine whether an OData path includes operation (import) path segments. // We use this function to make sure the value of ODataUri.Path in ODataMessageWriterSettings is null // when any path segment is an operation. ODL will try to calculate the context URL if the ODataUri.Path // equals to null. private static bool IsOperationPath(ODataPath path) { if (path == null) { return(false); } foreach (ODataPathSegment segment in path.Segments) { if (segment is OperationSegment || segment is OperationImportSegment) { return(true); } } return(false); }
public void Constructor_TakingEdmTypeAndPath_SetsProperties() { // Arrange IEdmModel model = new EdmModel(); IEdmEntityType entityType = new Mock <IEdmEntityType>().Object; IEdmEntityContainer entityContiner = new Mock <IEdmEntityContainer>().Object; EdmEntitySet entitySet = new EdmEntitySet(entityContiner, "entitySet", entityType); ODataPath path = new ODataPath(new EntitySetSegment(entitySet)); // Act ODataQueryContext context = new ODataQueryContext(model, entityType, path); // Assert Assert.Same(model, context.Model); Assert.Same(entityType, context.ElementType); Assert.Same(entitySet, context.NavigationSource); Assert.Null(context.ElementClrType); }
private static Uri GenerateContainmentODataPathSegments(ResourceContext resourceContext, bool isEntityId) { Contract.Assert(resourceContext != null); Contract.Assert( resourceContext.NavigationSource.NavigationSourceKind() == EdmNavigationSourceKind.ContainedEntitySet); Contract.Assert(resourceContext.Request != null); ODataPath path = resourceContext.Request.ODataProperties().Path; if (path == null) { throw Error.InvalidOperation(SRResources.ODataPathMissing); } path = new ContainmentPathBuilder().TryComputeCanonicalContainingPath(path); List <ODataPathSegment> odataPath = path.Segments.ToList(); // create a template entity set if it's contained entity set IEdmEntitySet entitySet = resourceContext.NavigationSource as IEdmEntitySet; if (entitySet == null) { EdmEntityContainer container = new EdmEntityContainer("NS", "Default"); entitySet = new EdmEntitySet(container, resourceContext.NavigationSource.Name, resourceContext.NavigationSource.EntityType()); } odataPath.Add(new EntitySetSegment(entitySet)); odataPath.Add(new KeySegment(ConventionsHelpers.GetEntityKey(resourceContext), resourceContext.StructuredType as IEdmEntityType, resourceContext.NavigationSource)); if (!isEntityId) { bool isSameType = resourceContext.StructuredType == resourceContext.NavigationSource.EntityType(); if (!isSameType) { odataPath.Add(new TypeSegment(resourceContext.StructuredType, resourceContext.NavigationSource)); } } string odataLink = resourceContext.Url.CreateODataLink(odataPath); return(odataLink == null ? null : new Uri(odataLink)); }
public void GenerateODataLink_ThrowsIdLinkNullForEntityIdHeader_IfEntitySetLinkBuilderReturnsNull() { // Arrange var linkBuilder = new Mock <NavigationSourceLinkBuilderAnnotation>(); var model = new CustomersModelWithInheritance(); model.Model.SetAnnotationValue(model.Customer, new ClrTypeAnnotation(typeof(TestEntity))); model.Model.SetNavigationSourceLinkBuilder(model.Customers, linkBuilder.Object); var path = new ODataPath(new EntitySetSegment(model.Customers)); var request = new HttpRequestMessage(); request.ODataProperties().Path = path; request.EnableHttpDependencyInjectionSupport(model.Model); // Act & Assert Assert.Throws <InvalidOperationException>( () => ResultHelpers.GenerateODataLink(request, _entity, isEntityId: true), "The Id link builder for the entity set 'Customers' returned null. An Id link is required for the OData-EntityId header."); }
public void GetETag_Returns_ETagInHeader_ForInteger(byte byteValue, short shortValue, long longValue) { // Arrange Dictionary <string, object> properties = new Dictionary <string, object> { { "ByteVal", byteValue }, { "LongVal", longValue }, { "ShortVal", shortValue } }; EntityTagHeaderValue etagHeaderValue = new DefaultODataETagHandler().CreateETag(properties); var builder = new ODataConventionModelBuilder(); builder.EntitySet <MyEtagOrder>("Orders"); IEdmModel model = builder.GetEdmModel(); IEdmEntitySet orders = model.FindDeclaredEntitySet("Orders"); ODataPath odataPath = new ODataPath(new EntitySetSegment(orders)); HttpRequestMessage request = new HttpRequestMessage(); request.EnableHttpDependencyInjectionSupport(model); request.ODataProperties().Path = odataPath; // Act ETag result = request.GetETag(etagHeaderValue); dynamic dynamicResult = result; // Assert byte actualByte = Assert.IsType <byte>(result["ByteVal"]); Assert.Equal(actualByte, dynamicResult.ByteVal); Assert.Equal(byteValue, actualByte); short actualShort = Assert.IsType <short>(result["ShortVal"]); Assert.Equal(actualShort, dynamicResult.ShortVal); Assert.Equal(shortValue, actualShort); long actualLong = Assert.IsType <long>(result["LongVal"]); Assert.Equal(actualLong, dynamicResult.LongVal); Assert.Equal(longValue, actualLong); }
internal static IReadOnlyDictionary<string, object> GetPathKeyValues(ODataPath path) { if (path.PathTemplate == "~/entityset/key" || path.PathTemplate == "~/entityset/key/cast") { var keySegment = (KeySegment)path.Segments[1]; return GetPathKeyValues(keySegment); } else if (path.PathTemplate == "~/entityset/cast/key") { var keySegment = (KeySegment)path.Segments[2]; return GetPathKeyValues(keySegment); } else { throw new InvalidOperationException(string.Format( CultureInfo.InvariantCulture, Resources.InvalidPathTemplateInRequest, "~/entityset/key")); } }
public RestierQueryBuilder(ApiBase api, ODataPath path) { Ensure.NotNull(api, "api"); Ensure.NotNull(path, "path"); this.api = api; this.path = path; this.handlers[typeof(EntitySetSegment)] = this.HandleEntitySetPathSegment; this.handlers[typeof(SingletonSegment)] = this.HandleSingletonPathSegment; this.handlers[typeof(OperationSegment)] = this.EmptyHandler; this.handlers[typeof(OperationImportSegment)] = this.EmptyHandler; this.handlers[typeof(CountSegment)] = this.HandleCountPathSegment; this.handlers[typeof(ValueSegment)] = this.HandleValuePathSegment; this.handlers[typeof(KeySegment)] = this.HandleKeyValuePathSegment; this.handlers[typeof(NavigationPropertySegment)] = this.HandleNavigationPathSegment; this.handlers[typeof(PropertySegment)] = this.HandlePropertyAccessPathSegment; this.handlers[typeof(TypeSegment)] = this.HandleEntityTypeSegment; // Complex cast is not supported by EF, and is not supported here // this.handlers[ODataSegmentKinds.ComplexCast] = null; }
public void GetIfMatchOrNoneMatch_ReturnsETag_SetETagHeaderValue(string header) { // Arrange HttpRequestMessage request = new HttpRequestMessage(); HttpConfiguration cofiguration = new HttpConfiguration(); request.SetConfiguration(cofiguration); Dictionary<string, object> properties = new Dictionary<string, object> { { "Name", "Foo" } }; EntityTagHeaderValue etagHeaderValue = new DefaultODataETagHandler().CreateETag(properties); if (header.Equals("IfMatch")) { request.Headers.IfMatch.Add(etagHeaderValue); } else { request.Headers.IfNoneMatch.Add(etagHeaderValue); } ODataModelBuilder builder = new ODataModelBuilder(); EntityTypeConfiguration<Customer> customer = builder.EntityType<Customer>(); customer.HasKey(c => c.Id); customer.Property(c => c.Id); customer.Property(c => c.Name).IsConcurrencyToken(); builder.EntitySet<Customer>("Customers"); IEdmModel model = builder.GetEdmModel(); var customers = model.FindDeclaredEntitySet("Customers"); Mock<ODataPathSegment> mockSegment = new Mock<ODataPathSegment> { CallBase = true }; mockSegment.Setup(s => s.GetEdmType(null)).Returns(model.GetEdmType(typeof(Customer))); mockSegment.Setup(s => s.GetNavigationSource(null)).Returns((IEdmNavigationSource)customers); ODataPath odataPath = new ODataPath(new[] { mockSegment.Object }); request.ODataProperties().Path = odataPath; request.ODataProperties().Model = model; ODataQueryContext context = new ODataQueryContext(model, typeof(Customer)); // Act ODataQueryOptions<Customer> query = new ODataQueryOptions<Customer>(context, request); ETag result = header.Equals("IfMatch") ? query.IfMatch : query.IfNoneMatch; dynamic dynamicResult = result; // Assert Assert.Equal("Foo", result["Name"]); Assert.Equal("Foo", dynamicResult.Name); }