public void OmitOperations() { var resource = new ODataResource(); ODataMessageWriterSettings settings = new ODataMessageWriterSettings(); settings.MetadataSelector = new TestMetadataSelector(); ODataResourceMetadataBuilder resourceMetadataBuilder = fullMetadataLevel.CreateResourceMetadataBuilder( resource, personTypeContext, null, HardCodedTestModel.GetPersonType(), new SelectedPropertiesNode(SelectedPropertiesNode.SelectionType.EntireSubtree), /*isResponse*/ true, /*keyAsSegment*/ false, /*requestUri*/ null, /*settings*/ settings); fullMetadataLevel.InjectMetadataBuilder(resource, resourceMetadataBuilder); var function = new ODataFunction { Metadata = new Uri(MetadataDocumentUri, "#function1"), }; var action = new ODataAction { Metadata = new Uri(MetadataDocumentUri, "#action2") }; resource.AddFunction(function); resource.AddAction(action); resource.MetadataBuilder.Should().BeSameAs(resourceMetadataBuilder); //metadataselector only allows for two HasHat functions to be written as metadata Assert.True(resource.Functions.Count() == 3); Assert.True(resource.Actions.Count() == 1); }
internal void CheckForUnmodifiedTitle(ODataAction action, string originalTitle) { if (!this.interpreter.ShouldIncludeOperationMetadata(PayloadMetadataKind.Operation.Title, () => action.Title != originalTitle)) { action.Title = null; } }
public void PropertyGettersAndSettersTest() { Uri metadata = new Uri("http://odata.org/operationMetadata"); string title = "OperationTitle"; Uri target = new Uri("http://odata.org/operationtarget"); ODataAction action = new ODataAction() { Metadata = metadata, Title = title, Target = target, }; this.Assert.AreSame(metadata, action.Metadata, "Expected reference equal values for property 'Metadata'."); this.Assert.AreEqual(title, action.Title, "Expected equal Title values."); this.Assert.AreSame(target, action.Target, "Expected reference equal values for property 'Target'."); ODataFunction function = new ODataFunction() { Metadata = metadata, Title = title, Target = target, }; this.Assert.AreSame(metadata, function.Metadata, "Expected reference equal values for property 'Metadata'."); this.Assert.AreEqual(title, function.Title, "Expected equal Title values."); this.Assert.AreSame(target, function.Target, "Expected reference equal values for property 'Target'."); }
internal void CheckForUnmodifiedTarget(ODataAction action, Func <Uri> computeOriginalTarget) { if (!this.interpreter.ShouldIncludeOperationMetadata(PayloadMetadataKind.Operation.Target, () => !ReferenceEquals(action.Target, computeOriginalTarget()))) { action.Target = null; } }
public virtual ODataAction CreateODataAction(IEdmFunctionImport action, EntityInstanceContext entityInstanceContext) { if (action == null) { throw Error.ArgumentNull("action"); } if (entityInstanceContext == null) { throw Error.ArgumentNull("entityInstanceContext"); } ODataMetadataLevel metadataLevel = entityInstanceContext.SerializerContext.MetadataLevel; IEdmModel model = entityInstanceContext.EdmModel; ActionLinkBuilder builder = model.GetActionLinkBuilder(action); if (builder == null) { return(null); } if (ShouldOmitAction(action, model, builder, metadataLevel)) { return(null); } Uri target = builder.BuildActionLink(entityInstanceContext); if (target == null) { return(null); } Uri baseUri = new Uri(entityInstanceContext.Url.ODataLink(new MetadataPathSegment())); Uri metadata = new Uri(baseUri, "#" + CreateMetadataFragment(action, model, metadataLevel)); ODataAction odataAction = new ODataAction { Metadata = metadata, }; bool alwaysIncludeDetails = metadataLevel == ODataMetadataLevel.Default || metadataLevel == ODataMetadataLevel.FullMetadata; // Always omit the title in minimal/no metadata modes (it isn't customizable and thus always follows // conventions). if (alwaysIncludeDetails) { odataAction.Title = action.Name; } // Omit the target in minimal/no metadata modes unless it doesn't follow conventions. if (alwaysIncludeDetails || !builder.FollowsConventions) { odataAction.Target = target; } return(odataAction); }
public void ValidateOperationShouldThrowWhenOperationMetadataIsNull() { ODataOperation operation = new ODataAction(); Action action = () => ODataJsonLightValidationUtils.ValidateOperation(metadataDocumentUri, operation); action.ShouldThrow <ODataException>().WithMessage(ErrorStrings.ValidationUtils_ActionsAndFunctionsMustSpecifyMetadata(operation.GetType().Name)); }
/// <summary> /// Adds an ODataAction to an entry. /// </summary> /// <param name="entry">The entry to add the action.</param> /// <param name="action">The action to add.</param> internal static void AddAction(this ODataEntry entry, ODataAction action) { DebugUtils.CheckNoExternalCallers(); Debug.Assert(entry != null, "entry != null"); Debug.Assert(action != null, "action != null"); entry.Actions = entry.Actions.ConcatToReadOnlyEnumerable("Actions", action); }
/// <summary> /// Add action to feed. /// </summary> /// <param name="action">The action to add.</param> public void AddAction(ODataAction action) { ExceptionUtils.CheckArgumentNotNull(action, "action"); if (!this.actions.Contains(action)) { this.actions.Add(action); } }
public void ValidateOperationShouldNotThrowWhenOperationMetadataIsNotOpenAndOperationTargetNull() { ODataOperation operation = new ODataAction { Metadata = new Uri(metadataDocumentUri.OriginalString + "#baz") }; ODataJsonLightValidationUtils.ValidateOperation(metadataDocumentUri, operation); }
internal static void AddActionToEntry(ODataEntry entry, ODataAction action) { if (object.ReferenceEquals(entry.Actions, EmptyActionsList)) { entry.Actions = new ReadOnlyEnumerable <ODataAction>(); } GetSourceListOfEnumerable <ODataAction>(entry.Actions, "Actions").Add(action); }
/// <summary> /// Add action to resource set. /// </summary> /// <param name="action">The action to add.</param> public void AddAction(ODataAction action) { ExceptionUtils.CheckArgumentNotNull(action, "action"); if (!this.actions.Contains(action)) { this.actions.Add(action); } }
internal void SetTitle(ODataAction action, bool isAlwaysAvailable, string title) { Debug.Assert(action != null, "action != null"); if (!isAlwaysAvailable || this.interpreter.ShouldIncludeOperationMetadata(PayloadMetadataKind.Operation.Title, () => false)) { action.Title = title; } }
public virtual Task <ODataAction> CreateODataActionAsync(IEdmAction action, EntityInstanceContext entityInstanceContext) { if (action == null) { throw Error.ArgumentNull("action"); } if (entityInstanceContext == null) { throw Error.ArgumentNull("entityInstanceContext"); } ODataMetadataLevel metadataLevel = entityInstanceContext.SerializerContext.MetadataLevel; IEdmModel model = entityInstanceContext.EdmModel; ActionLinkBuilder builder = model.GetActionLinkBuilder(action); if (builder == null) { return(Task.FromResult((ODataAction)null)); } if (ShouldOmitAction(action, builder, metadataLevel)) { return(Task.FromResult((ODataAction)null)); } Uri target = builder.BuildActionLink(entityInstanceContext); if (target == null) { return(Task.FromResult((ODataAction)null)); } Uri baseUri = new Uri(entityInstanceContext.Url.CreateODataLink(new MetadataPathSegment())); Uri metadata = new Uri(baseUri, "#" + CreateMetadataFragment(action)); ODataAction odataAction = new ODataAction { Metadata = metadata, }; bool alwaysIncludeDetails = metadataLevel == ODataMetadataLevel.FullMetadata; // Always omit the title in minimal/no metadata modes. if (alwaysIncludeDetails) { EmitTitle(model, action, odataAction); } // Omit the target in minimal/no metadata modes unless it doesn't follow conventions. if (alwaysIncludeDetails || !builder.FollowsConventions) { odataAction.Target = target; } return(Task.FromResult(odataAction)); }
internal void SetTarget(ODataAction action, bool isAlwaysAvailable, Func <Uri> computeTarget) { Debug.Assert(action != null, "action != null"); if (!isAlwaysAvailable || this.interpreter.ShouldIncludeOperationMetadata(PayloadMetadataKind.Operation.Target, () => false)) { Debug.Assert(computeTarget != null, "computeTarget != null"); action.Target = computeTarget(); } }
public void ValidateOperationShouldThrowWhenOperationMetadataIsNotMetadataReferenceProperty() { ODataOperation operation = new ODataAction { Metadata = new Uri("foobaz", UriKind.Relative) }; Action action = () => ODataJsonLightValidationUtils.ValidateOperation(metadataDocumentUri, operation); action.ShouldThrow <ODataException>().WithMessage(ErrorStrings.ValidationUtils_InvalidMetadataReferenceProperty("foobaz")); }
public void ValidateOperationShouldThrowWhenOperationMetadataIsOpenAndOperationTargetIsNotNull() { ODataOperation operation = new ODataAction { Metadata = new Uri("http://www.example.com/foo#baz"), Target = new Uri("http://www.example.com") }; Action action = () => ODataJsonLightValidationUtils.ValidateOperation(metadataDocumentUri, operation); action.ShouldThrow <ODataException>().WithMessage(ErrorStrings.ODataJsonLightValidationUtils_OpenMetadataReferencePropertyNotSupported("http://www.example.com/foo#baz", metadataDocumentUri.AbsoluteUri)); }
public void DefaultValuesTest() { ODataAction action = new ODataAction(); this.Assert.IsNull(action.Metadata, "Expected null default value for property 'Metadata'."); this.Assert.IsNull(action.Title, "Expected null default value for property 'Title'."); this.Assert.IsNull(action.Target, "Expected null default value for property 'Target'."); ODataFunction function = new ODataFunction(); this.Assert.IsNull(function.Metadata, "Expected null default value for property 'Metadata'."); this.Assert.IsNull(function.Title, "Expected null default value for property 'Title'."); this.Assert.IsNull(function.Target, "Expected null default value for property 'Target'."); }
public void AddDuplicateAction() { var action = new ODataAction() { Metadata = new Uri("http://odata.org/metadata"), Target = new Uri("http://odata.org/target"), Title = "TestAction", }; this.odataEntry.AddAction(action); this.odataEntry.AddAction(action); this.odataEntry.Actions.Count().Should().Be(1); this.odataEntry.Actions.First().Should().Be(action); }
/// <summary> /// Adds an ODataAction to an entry. /// </summary> /// <param name="entry">The entry to add the action.</param> /// <param name="action">The action to add.</param> internal static void AddActionToEntry(ODataEntry entry, ODataAction action) { DebugUtils.CheckNoExternalCallers(); Debug.Assert(entry != null, "entry != null"); Debug.Assert(action != null, "action != null"); if (object.ReferenceEquals(entry.Actions, EmptyActionsList)) { entry.Actions = new ReadOnlyEnumerable <ODataAction>(); } ReaderUtils.GetSourceListOfEnumerable(entry.Actions, "Actions").Add(action); }
public void AddActionShouldWork() { var action = new ODataAction() { Metadata = new Uri("http://odata.org/metadata"), Target = new Uri("http://odata.org/target"), Title = "TestAction", }; this.odataEntry.AddAction(action); var odataAction = Assert.Single(this.odataEntry.Actions); Assert.Same(action, odataAction); }
private static ODataOperation CreateODataOperation(IEdmOperation operation, OperationLinkBuilder builder, ResourceContext resourceContext) { Contract.Assert(operation != null); Contract.Assert(builder != null); Contract.Assert(resourceContext != null); ODataMetadataLevel metadataLevel = resourceContext.SerializerContext.MetadataLevel; IEdmModel model = resourceContext.EdmModel; if (ShouldOmitOperation(operation, builder, metadataLevel)) { return(null); } Uri target = builder.BuildLink(resourceContext); if (target == null) { return(null); } Uri baseUri = new Uri(resourceContext.Url.CreateODataLink(MetadataSegment.Instance)); Uri metadata = new Uri(baseUri, "#" + CreateMetadataFragment(operation)); ODataOperation odataOperation; if (operation is IEdmAction) { odataOperation = new ODataAction(); } else { odataOperation = new ODataFunction(); } odataOperation.Metadata = metadata; // Always omit the title in minimal/no metadata modes. if (metadataLevel == ODataMetadataLevel.FullMetadata) { EmitTitle(model, operation, odataOperation); } // Omit the target in minimal/no metadata modes unless it doesn't follow conventions. if (!builder.FollowsConventions || metadataLevel == ODataMetadataLevel.FullMetadata) { odataOperation.Target = target; } return(odataOperation); }
private IEnumerable <ODataAction> CreateODataActions( IEnumerable <IEdmFunctionImport> actions, EntityInstanceContext entityInstanceContext) { Contract.Assert(actions != null); Contract.Assert(entityInstanceContext != null); foreach (IEdmFunctionImport action in actions) { ODataAction oDataAction = CreateODataAction(action, entityInstanceContext); if (oDataAction != null) { yield return(oDataAction); } } }
public MissingOperationGeneratorTests() { this.model = new EdmModel(); this.container = new EdmEntityContainer("Fake", "Container"); this.functionEdmMetadata = new EdmFunction("Fake", "FakeFunction", EdmCoreModel.Instance.GetInt32(false), true /*isBound*/, null, true /*isComposable*/); this.actionEdmMetadata = new EdmAction("Fake", "FakeAction", EdmCoreModel.Instance.GetInt32(false), true/*isBound*/, null /*entitySetPath*/); this.model.AddElement(this.container); this.model.AddElement(this.actionEdmMetadata); this.model.AddElement(this.functionEdmMetadata); this.allOperations = new EdmOperation[] { this.actionEdmMetadata, this.functionEdmMetadata }; this.odataAction = new ODataAction {Metadata = new Uri("http://temp.org/$metadata#Fake.FakeAction")}; this.odataFunction = new ODataFunction {Metadata = new Uri("http://temp.org/$metadata#Fake.FakeFunction")}; }
private IEnumerable <ODataAction> CreateODataActions( IEnumerable <IEdmAction> actions, ResourceContext resourceContext) { Contract.Assert(actions != null); Contract.Assert(resourceContext != null); foreach (IEdmAction action in actions) { ODataAction oDataAction = CreateODataAction(action, resourceContext); if (oDataAction != null) { yield return(oDataAction); } } }
/// <summary> /// Tries to serialize the operation. /// </summary> /// <param name="entityToSerialize">The entity to serialize.</param> /// <param name="resourceInstanceInFeed">Whether or not the entity is being serialized in a feed.</param> /// <param name="entityHasMultipleActionsWithSameName">Whether or not there are multiple operations in the current scope with the same name as the current operation.</param> /// <param name="serviceOperationWrapper">The service operation wrapper.</param> /// <param name="odataAction">The ODL object-model representation of the action.</param> /// <returns>Whether or not to serialize the operation.</returns> private bool TrySerializeOperation(EntityToSerialize entityToSerialize, bool resourceInstanceInFeed, bool entityHasMultipleActionsWithSameName, OperationWrapper serviceOperationWrapper, out ODataAction odataAction) { Debug.Assert(serviceOperationWrapper != null, "serviceOperationWrapper != null"); // We only advertise actions. This is a debug assert because GetServiceOperationsByResourceType only returns actions. Debug.Assert(serviceOperationWrapper.Kind == OperationKind.Action, "Only actions can be advertised"); Uri metadata = this.operationLinkBuilder.BuildMetadataLink(serviceOperationWrapper, entityHasMultipleActionsWithSameName); // If the action has OperationParameterBindingKind set to "Always" then we advertise the action without calling "AdvertiseServiceAction". bool isAlwaysAvailable = serviceOperationWrapper.OperationParameterBindingKind == OperationParameterBindingKind.Always; odataAction = new ODataAction { Metadata = metadata }; // There is some subtlety to the interaction between action advertisement and whether or not to include title/target on the wire. // // 1) If an action is always available: // The provider author does not get a chance to customize the title/target values... // so the values will be based on conventions... // so by default do not write them on the wire // 2) If it is only sometimes available: // The values need to be computed to provide them on the instance given to the provider... // but they might not be changed by the provider author... // so compare them to the computed values, and do not write them if they match. // TODO: Action provider should be able to customize title/target even if the action is 'always' advertised // If this gets fixed, then all the behavior should collapse to emulate case #2 above // Create a lazy Uri for the target, because we may need it more than once (see case #2 above). SimpleLazy <Uri> lazyActionTargetUri = new SimpleLazy <Uri>(() => this.operationLinkBuilder.BuildTargetLink(entityToSerialize, serviceOperationWrapper, entityHasMultipleActionsWithSameName)); this.metadataPropertyManager.SetTitle(odataAction, isAlwaysAvailable, serviceOperationWrapper.Name); this.metadataPropertyManager.SetTarget(odataAction, isAlwaysAvailable, () => lazyActionTargetUri.Value); // If the operation is always available, // 1. Return true for MetadataQueryOption.All. // 2. Return false for MetadataQueryOption.None. // 3. Return false for MetadataQueryOption.Default. if (isAlwaysAvailable) { return(this.payloadMetadataParameterInterpreter.ShouldIncludeAlwaysAvailableOperation()); } return(this.AskProviderIfActionShouldBeAdvertised(entityToSerialize, resourceInstanceInFeed, serviceOperationWrapper, lazyActionTargetUri, entityHasMultipleActionsWithSameName, ref odataAction)); }
private async Task <IEnumerable <ODataAction> > CreateODataActionsAsync( IEnumerable <IEdmAction> actions, EntityInstanceContext entityInstanceContext) { Contract.Assert(actions != null); Contract.Assert(entityInstanceContext != null); List <ODataAction> result = new List <ODataAction>(); foreach (IEdmAction action in actions) { ODataAction oDataAction = await CreateODataActionAsync(action, entityInstanceContext); if (oDataAction != null) { result.Add(oDataAction); } } return(result); }
public void InjectMetadataBuilderShouldSetBuilderOnEntryActions() { var entry = new ODataResource(); var builder = new TestEntityMetadataBuilder(entry); var action1 = new ODataAction { Metadata = new Uri(MetadataDocumentUri, "#action1") }; var action2 = new ODataAction { Metadata = new Uri(MetadataDocumentUri, "#action2") }; entry.AddAction(action1); entry.AddAction(action2); testSubject.InjectMetadataBuilder(entry, builder); action1.GetMetadataBuilder().Should().BeSameAs(builder); action2.GetMetadataBuilder().Should().BeSameAs(builder); }
public void InjectMetadataBuilderShouldNotSetBuilderOnEntryActions() { var entry = new ODataEntry(); var builder = new TestEntityMetadataBuilder(entry); var action1 = new ODataAction { Metadata = new Uri("http://service/$metadata#action1", UriKind.Absolute) }; var action2 = new ODataAction { Metadata = new Uri("http://service/$metadata#action2", UriKind.Absolute) }; entry.AddAction(action1); entry.AddAction(action2); testSubject.InjectMetadataBuilder(entry, builder); action1.GetMetadataBuilder().Should().BeNull(); action2.GetMetadataBuilder().Should().BeNull(); }
public MissingOperationGeneratorTests() { this.model = new EdmModel(); this.container = new EdmEntityContainer("Fake", "Container"); this.functionEdmMetadata = new EdmFunction("Fake", "FakeFunction", EdmCoreModel.Instance.GetInt32(false), true /*isBound*/, null, true /*isComposable*/); this.actionEdmMetadata = new EdmAction("Fake", "FakeAction", EdmCoreModel.Instance.GetInt32(false), true /*isBound*/, null /*entitySetPath*/); this.model.AddElement(this.container); this.model.AddElement(this.actionEdmMetadata); this.model.AddElement(this.functionEdmMetadata); this.allOperations = new EdmOperation[] { this.actionEdmMetadata, this.functionEdmMetadata }; this.odataAction = new ODataAction { Metadata = new Uri("http://temp.org/$metadata#Fake.FakeAction") }; this.odataFunction = new ODataFunction { Metadata = new Uri("http://temp.org/$metadata#Fake.FakeFunction") }; }
public void NoOpMetadataBuilderShouldReturnActionsSetByUser() { ODataAction action = new ODataAction() { Metadata = new Uri("http://example.com/$metadata#Action"), Target = new Uri("http://example.com/Action"), Title = "ActionTitle" }; ODataResource entry = new ODataResource(); entry.AddAction(action); Assert.Single(new NoOpResourceMetadataBuilder(entry).GetActions().Where(a => a == action)); // Verify that the action information wasn't removed or changed. Assert.Equal(new Uri("http://example.com/$metadata#Action"), action.Metadata); Assert.Equal(new Uri("http://example.com/Action"), action.Target); Assert.Equal("ActionTitle", action.Title); }
public void NoOpMetadataBuilderShouldReturnActionsSetByUser() { ODataAction action = new ODataAction() { Metadata = new Uri("http://example.com/$metadata#Action"), Target = new Uri("http://example.com/Action"), Title = "ActionTitle" }; ODataEntry entry = new ODataEntry(); entry.AddAction(action); new NoOpEntityMetadataBuilder(entry).GetActions() .Should().ContainSingle(a => a == action); // Verify that the action information wasn't removed or changed. action.Metadata.Should().Be(new Uri("http://example.com/$metadata#Action")); action.Target.Should().Be(new Uri("http://example.com/Action")); action.Title.Should().Be("ActionTitle"); }
public void PropertySettersNullTest() { Uri metadata = new Uri("http://odata.org/operationMetadata"); string title = "OperationTitle"; Uri target = new Uri("http://odata.org/operationtarget"); ODataAction action = new ODataAction() { Metadata = metadata, Title = title, Target = target, }; action.Metadata = null; action.Title = null; action.Target = null; this.Assert.IsNull(action.Metadata, "Expected null value for property 'Metadata'."); this.Assert.IsNull(action.Title, "Expected null value for property 'Title'."); this.Assert.IsNull(action.Target, "Expected null value for property 'Target'."); ODataFunction function = new ODataFunction() { Metadata = metadata, Title = title, Target = target, }; function.Metadata = null; function.Title = null; function.Target = null; this.Assert.IsNull(function.Metadata, "Expected null value for property 'Metadata'."); this.Assert.IsNull(function.Title, "Expected null value for property 'Title'."); this.Assert.IsNull(function.Target, "Expected null value for property 'Target'."); }
internal void SetTarget(ODataAction action, bool isAlwaysAvailable, Func<Uri> computeTarget) { Debug.Assert(action != null, "action != null"); if (!isAlwaysAvailable || this.interpreter.ShouldIncludeOperationMetadata(PayloadMetadataKind.Operation.Target, () => false)) { Debug.Assert(computeTarget != null, "computeTarget != null"); action.Target = computeTarget(); } }
public void CreateEntry_Calls_CreateODataActions() { // Arrange ODataAction[] actions = new ODataAction[] { new ODataAction(), new ODataAction() }; EntityInstanceContext entityInstanceContext = new EntityInstanceContext(); Mock<ODataEntityTypeSerializer> serializer = new Mock<ODataEntityTypeSerializer>(_serializer.EdmType, new DefaultODataSerializerProvider()); serializer.CallBase = true; serializer.Setup(s => s.CreateODataActions(entityInstanceContext, _writeContext)).Returns(actions).Verifiable(); serializer.Setup(s => s.CreateStructuralPropertyBag(entityInstanceContext, _writeContext)); // Act ODataEntry entry = serializer.Object.CreateEntry(entityInstanceContext, _writeContext); // Assert serializer.Verify(); Assert.Same(actions, entry.Actions); }
internal void CheckForUnmodifiedTarget(ODataAction action, Func<Uri> computeOriginalTarget) { if (!this.interpreter.ShouldIncludeOperationMetadata(PayloadMetadataKind.Operation.Target, () => !ReferenceEquals(action.Target, computeOriginalTarget()))) { action.Target = null; } }
private static ODataOperation CreateODataOperation(IEdmOperation operation, ProcedureLinkBuilder builder, EntityInstanceContext entityInstanceContext) { Contract.Assert(operation != null); Contract.Assert(builder != null); Contract.Assert(entityInstanceContext != null); ODataMetadataLevel metadataLevel = entityInstanceContext.SerializerContext.MetadataLevel; IEdmModel model = entityInstanceContext.EdmModel; if (ShouldOmitOperation(operation, builder, metadataLevel)) { return null; } Uri target = builder.BuildLink(entityInstanceContext); if (target == null) { return null; } Uri baseUri = new Uri(entityInstanceContext.Url.CreateODataLink(new MetadataPathSegment())); Uri metadata = new Uri(baseUri, "#" + CreateMetadataFragment(operation)); ODataOperation odataOperation; if (operation is IEdmAction) { odataOperation = new ODataAction(); } else { odataOperation = new ODataFunction(); } odataOperation.Metadata = metadata; // Always omit the title in minimal/no metadata modes. if (metadataLevel == ODataMetadataLevel.FullMetadata) { EmitTitle(model, operation, odataOperation); } // Omit the target in minimal/no metadata modes unless it doesn't follow conventions. if (!builder.FollowsConventions || metadataLevel == ODataMetadataLevel.FullMetadata) { odataOperation.Target = target; } return odataOperation; }
public void CreateStructuralPropertyBag_Calls_CreateStructuralProperty_ForAllStructuralProperties() { // Arrange var instance = new object(); IEdmStructuralProperty[] structuralProperties = new[] { new Mock<IEdmStructuralProperty>().Object, new Mock<IEdmStructuralProperty>().Object }; ODataProperty[] oDataProperties = new[] { new ODataProperty(), new ODataProperty() }; ODataAction[] actions = new ODataAction[] { new ODataAction(), new ODataAction() }; EntityInstanceContext entityInstanceContext = new EntityInstanceContext { EntityInstance = instance }; Mock<IEdmEntityType> entityType = new Mock<IEdmEntityType>(); entityType.Setup(e => e.DeclaredProperties).Returns(structuralProperties); Mock<ODataEntityTypeSerializer> serializer = new Mock<ODataEntityTypeSerializer>( new EdmEntityTypeReference(entityType.Object, isNullable: false), new DefaultODataSerializerProvider()); serializer.CallBase = true; serializer.Setup(s => s.CreateStructuralProperty(structuralProperties[0], instance, _writeContext)).Returns(oDataProperties[0]).Verifiable(); serializer.Setup(s => s.CreateStructuralProperty(structuralProperties[1], instance, _writeContext)).Returns(oDataProperties[1]).Verifiable(); // Act IEnumerable<ODataProperty> propertyValues = serializer.Object.CreateStructuralPropertyBag(entityInstanceContext, _writeContext); // Assert serializer.Verify(); }
public void TestSetTitleAnnotation_UsesNameIfNoTitleAnnotationIsPresent() { // Arrange IEdmActionImport action = CreateFakeActionImport(CreateFakeContainer("Container"), "Action"); IEdmDirectValueAnnotationsManager annonationsManager = CreateFakeAnnotationsManager(); IEdmModel model = CreateFakeModel(annonationsManager); ODataAction odataAction = new ODataAction(); // Act ODataEntityTypeSerializer.EmitTitle(model, action.Operation, odataAction); // Assert Assert.Equal(action.Operation.Name, odataAction.Title); }
public void ValidateOperationShouldThrowWhenOperationMetadataIsOpenAndOperationTargetIsNotNull() { ODataOperation operation = new ODataAction {Metadata = new Uri("http://www.example.com/foo#baz"), Target = new Uri("http://www.example.com")}; Action action = () => ODataJsonLightValidationUtils.ValidateOperation(metadataDocumentUri, operation); action.ShouldThrow<ODataException>().WithMessage(ErrorStrings.ODataJsonLightValidationUtils_OpenMetadataReferencePropertyNotSupported("http://www.example.com/foo#baz", metadataDocumentUri.AbsoluteUri)); }
public virtual ODataAction CreateODataAction(IEdmAction action, EntityInstanceContext entityInstanceContext) { if (action == null) { throw Error.ArgumentNull("action"); } if (entityInstanceContext == null) { throw Error.ArgumentNull("entityInstanceContext"); } ODataMetadataLevel metadataLevel = entityInstanceContext.SerializerContext.MetadataLevel; IEdmModel model = entityInstanceContext.EdmModel; ActionLinkBuilder builder = model.GetActionLinkBuilder(action); if (builder == null) { return null; } if (ShouldOmitAction(action, builder, metadataLevel)) { return null; } Uri target = builder.BuildActionLink(entityInstanceContext); if (target == null) { return null; } Uri baseUri = new Uri(entityInstanceContext.Url.CreateODataLink(new MetadataPathSegment())); Uri metadata = new Uri(baseUri, "#" + CreateMetadataFragment(action)); ODataAction odataAction = new ODataAction { Metadata = metadata, }; bool alwaysIncludeDetails = metadataLevel == ODataMetadataLevel.FullMetadata; // Always omit the title in minimal/no metadata modes. if (alwaysIncludeDetails) { EmitTitle(model, action, odataAction); } // Omit the target in minimal/no metadata modes unless it doesn't follow conventions. if (alwaysIncludeDetails || !builder.FollowsConventions) { odataAction.Target = target; } return odataAction; }
public void CreateEntry_Calls_CreateODataAction_ForEachSelectAction() { // Arrange ODataAction[] actions = new ODataAction[] { new ODataAction(), new ODataAction() }; SelectExpandNode selectExpandNode = new SelectExpandNode { SelectedActions = { new Mock<IEdmAction>().Object, new Mock<IEdmAction>().Object } }; Mock<ODataEntityTypeSerializer> serializer = new Mock<ODataEntityTypeSerializer>(_serializerProvider); serializer.CallBase = true; serializer.Setup(s => s.CreateODataAction(selectExpandNode.SelectedActions.ElementAt(0), _entityInstanceContext)).Returns(actions[0]).Verifiable(); serializer.Setup(s => s.CreateODataAction(selectExpandNode.SelectedActions.ElementAt(1), _entityInstanceContext)).Returns(actions[1]).Verifiable(); // Act ODataEntry entry = serializer.Object.CreateEntry(selectExpandNode, _entityInstanceContext); // Assert Assert.Equal(actions, entry.Actions); serializer.Verify(); }
public void ActionAndFunctionTest() { // <m:action Metadata=URI title?="title" target=URI /> Uri actionMetadata = new Uri("http://odata.org/test/$metadata#defaultAction"); Uri actionMetadata2 = new Uri("#action escaped relative metadata", UriKind.Relative); Uri actionMetadata3 = new Uri("../#action escaped relative metadata", UriKind.Relative); string actionTitle = "Default Action"; Uri actionTarget = new Uri("http://odata.org/defaultActionTarget"); Uri actionTarget2 = new Uri("http://odata.org/defaultActionTarget2"); ODataAction action_r1_t1 = new ODataAction() { Metadata = actionMetadata, Title = actionTitle, Target = actionTarget }; ODataAction action_r1_t2 = new ODataAction() { Metadata = actionMetadata, Title = actionTitle, Target = actionTarget2 }; ODataAction action_r2_t1 = new ODataAction() { Metadata = actionMetadata2, Title = actionTitle, Target = actionTarget }; ODataAction action_r3_t1 = new ODataAction() { Metadata = actionMetadata3, Title = actionTitle, Target = actionTarget }; Uri functionMetadata = new Uri("http://odata.org/test/$metadata#defaultFunction"); Uri functionMetadata2 = new Uri("#function escaped relative metadata", UriKind.Relative); Uri functionMetadata3 = new Uri("\\#function escaped relative metadata", UriKind.Relative); string functionTitle = "Default Function"; Uri functionTarget = new Uri("http://odata.org/defaultFunctionTarget"); Uri functionTarget2 = new Uri("http://odata.org/defaultFunctionTarget2"); ODataFunction function_r1_t1 = new ODataFunction() { Metadata = functionMetadata, Title = functionTitle, Target = functionTarget }; ODataFunction function_r1_t2 = new ODataFunction() { Metadata = functionMetadata, Title = functionTitle, Target = functionTarget2 }; ODataFunction function_r2_t1 = new ODataFunction() { Metadata = functionMetadata2, Title = functionTitle, Target = functionTarget }; ODataFunction function_r3_t1 = new ODataFunction() { Metadata = functionMetadata3, Title = functionTitle, Target = functionTarget }; var actionCases = new[] { new { ODataActions = new ODataAction[] { action_r1_t1 }, Atom = GetAtom(action_r1_t1), JsonLight = GetJsonLightForRelGroup(action_r1_t1), }, new { ODataActions = new ODataAction[] { action_r1_t1, action_r1_t2 }, Atom = GetAtom(action_r1_t1) + GetAtom(action_r1_t2), JsonLight = GetJsonLightForRelGroup(action_r1_t1, action_r1_t2), }, new { ODataActions = new ODataAction[] { action_r1_t1, action_r2_t1 }, Atom = GetAtom(action_r1_t1) + GetAtom(action_r2_t1), JsonLight = GetJsonLightForRelGroup(action_r1_t1) + "," + GetJsonLightForRelGroup(action_r2_t1), }, new { ODataActions = new ODataAction[] { action_r1_t1, action_r2_t1, action_r1_t2 }, Atom = GetAtom(action_r1_t1) + GetAtom(action_r2_t1) + GetAtom(action_r1_t2), JsonLight = GetJsonLightForRelGroup(action_r1_t1, action_r1_t2) + "," + GetJsonLightForRelGroup(action_r2_t1), }, new { ODataActions = new ODataAction[] { action_r3_t1 }, Atom = GetAtom(action_r3_t1), JsonLight = GetJsonLightForRelGroup(action_r3_t1), }, }; var functionCases = new[] { new { ODataFunctions = new ODataFunction[] { function_r1_t1 }, Atom = GetAtom(function_r1_t1), JsonLight = GetJsonLightForRelGroup(function_r1_t1), }, new { ODataFunctions = new ODataFunction[] { function_r1_t1, function_r1_t2 }, Atom = GetAtom(function_r1_t1) + GetAtom(function_r1_t2), JsonLight = GetJsonLightForRelGroup(function_r1_t1, function_r1_t2), }, new { ODataFunctions = new ODataFunction[] { function_r1_t1, function_r2_t1 }, Atom = GetAtom(function_r1_t1) + GetAtom(function_r2_t1), JsonLight = GetJsonLightForRelGroup(function_r1_t1) + "," + GetJsonLightForRelGroup(function_r2_t1), }, new { ODataFunctions = new ODataFunction[] { function_r1_t1, function_r2_t1, function_r1_t2 }, Atom = GetAtom(function_r1_t1) + GetAtom(function_r2_t1) + GetAtom(function_r1_t2), JsonLight = GetJsonLightForRelGroup(function_r1_t1, function_r1_t2) + "," + GetJsonLightForRelGroup(function_r2_t1), }, new { ODataFunctions = new ODataFunction[] { function_r3_t1 }, Atom = GetAtom(function_r3_t1), JsonLight = GetJsonLightForRelGroup(function_r3_t1), }, }; var queryResults = from actionCase in actionCases from functionCase in functionCases select new { actionCase.ODataActions, functionCase.ODataFunctions, Atom = string.Concat(actionCase.Atom, functionCase.Atom), JsonLight = string.Join(",", new[] { actionCase.JsonLight, functionCase.JsonLight }.Where(x => x != null)) }; EdmModel model = new EdmModel(); EdmEntityType edmEntityTypeCustomer = model.EntityType("Customer", "TestModel"); EdmEntityContainer edmEntityContainer = model.EntityContainer("DefaultContainer","TestModel" ); EdmEntitySet edmEntitySetCustermors = model.EntitySet("Customers", edmEntityTypeCustomer); var testDescriptors = queryResults.Select(testCase => { ODataEntry entry = ObjectModelUtils.CreateDefaultEntry("TestModel.Customer"); if (testCase.ODataActions != null) { foreach (var action in testCase.ODataActions) { entry.AddAction(action); } } if (testCase.ODataFunctions != null) { foreach (var function in testCase.ODataFunctions) { entry.AddFunction(function); } } return new PayloadWriterTestDescriptor<ODataItem>( this.Settings, entry, (testConfiguration) => { if (testConfiguration.Format == ODataFormat.Atom) { return new AtomWriterTestExpectedResults(this.Settings.ExpectedResultSettings) { Xml = "<ODataOperations>" + testCase.Atom + "</ODataOperations>", ExpectedException2 = entry.Actions != null && entry.Actions.Contains(null) ? ODataExpectedExceptions.ODataException("ValidationUtils_EnumerableContainsANullItem", "ODataEntry.Actions") : testConfiguration.IsRequest && entry.Actions != null && entry.Actions.Any() ? ODataExpectedExceptions.ODataException("WriterValidationUtils_OperationInRequest", GetFirstOperationMetadata(entry)) : entry.Functions != null && entry.Functions.Contains(null) ? ODataExpectedExceptions.ODataException("ValidationUtils_EnumerableContainsANullItem", "ODataEntry.Functions") : testConfiguration.IsRequest && entry.Functions != null && entry.Functions.Any() ? ODataExpectedExceptions.ODataException("WriterValidationUtils_OperationInRequest", GetFirstOperationMetadata(entry)) : null, FragmentExtractor = (result) => { var actions = result.Elements(TestAtomConstants.ODataMetadataXNamespace + "action"); var functions = result.Elements(TestAtomConstants.ODataMetadataXNamespace + "function"); result = new XElement("ODataOperations", actions, functions); if (result.FirstNode == null) { result.Add(string.Empty); } return result; } }; } else if (testConfiguration.Format == ODataFormat.Json) { return new JsonWriterTestExpectedResults(this.Settings.ExpectedResultSettings) { Json = string.Join( "$(NL)", "{", testCase.JsonLight, "}"), ExpectedException2 = entry.Actions != null && entry.Actions.Contains(null) ? ODataExpectedExceptions.ODataException("ValidationUtils_EnumerableContainsANullItem", "ODataEntry.Actions") : testConfiguration.IsRequest && entry.Actions != null && entry.Actions.Any() ? ODataExpectedExceptions.ODataException("WriterValidationUtils_OperationInRequest", GetFirstOperationMetadata(entry)) : entry.Actions != null && entry.Actions.Any(a => !a.Metadata.IsAbsoluteUri && !a.Metadata.OriginalString.StartsWith("#")) ? ODataExpectedExceptions.ODataException("ValidationUtils_InvalidMetadataReferenceProperty", entry.Actions.First(a => a.Metadata.OriginalString.Contains(" ")).Metadata.OriginalString) : entry.Functions != null && entry.Functions.Contains(null) ? ODataExpectedExceptions.ODataException("ValidationUtils_EnumerableContainsANullItem", "ODataEntry.Functions") : testConfiguration.IsRequest && entry.Functions != null && entry.Functions.Any() ? ODataExpectedExceptions.ODataException("WriterValidationUtils_OperationInRequest", GetFirstOperationMetadata(entry)) : entry.Functions != null && entry.Functions.Any(f => !f.Metadata.IsAbsoluteUri && !f.Metadata.OriginalString.StartsWith("#")) ? ODataExpectedExceptions.ODataException("ValidationUtils_InvalidMetadataReferenceProperty", entry.Functions.First(f => f.Metadata.OriginalString.Contains(" ")).Metadata.OriginalString) : null, FragmentExtractor = (result) => { var actionsAndFunctions = result.Object().Properties.Where(p => p.Name.Contains("#")).ToList(); var jsonResult = new JsonObject(); actionsAndFunctions.ForEach(p => { // NOTE we remove all annotations here and in particular the text annotations to be able to easily compare // against the expected results. This however means that we do not distinguish between the indented and non-indented case here. p.RemoveAllAnnotations(true); jsonResult.Add(p); }); return jsonResult; } }; } else { string formatName = testConfiguration.Format == null ? "null" : testConfiguration.Format.GetType().Name; throw new NotSupportedException("Invalid format detected: " + formatName); } }); }); this.CombinatorialEngineProvider.RunCombinations( testDescriptors.PayloadCases(WriterPayloads.EntryPayloads), this.WriterTestConfigurationProvider.ExplicitFormatConfigurationsWithIndent, (testDescriptor, testConfiguration) => { testConfiguration = testConfiguration.Clone(); testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri); if (testConfiguration.Format == ODataFormat.Json) { if (testDescriptor.IsGeneratedPayload) { return; } // We need a model, entity set and entity type for JSON Light testDescriptor = new PayloadWriterTestDescriptor<ODataItem>(testDescriptor) { Model = model, PayloadEdmElementContainer = edmEntitySetCustermors, PayloadEdmElementType = edmEntityTypeCustomer, }; } TestWriterUtils.WriteAndVerifyODataPayload(testDescriptor, testConfiguration, this.Assert, this.Logger); }); }
public void CreateODataAction_IncludesEverything_ForFullMetadata() { // Arrange string expectedContainerName = "Container"; string expectedNamespace = "NS"; string expectedActionName = "Action"; string expectedTarget = "aa://Target"; string expectedMetadataPrefix = "http://Metadata"; IEdmEntityContainer container = CreateFakeContainer(expectedContainerName); IEdmAction action = CreateFakeAction(expectedNamespace, expectedActionName, isBindable: true); ActionLinkBuilder linkBuilder = new ActionLinkBuilder((a) => new Uri(expectedTarget), followsConventions: true); IEdmDirectValueAnnotationsManager annotationsManager = CreateFakeAnnotationsManager(); annotationsManager.SetActionLinkBuilder(action, linkBuilder); annotationsManager.SetIsAlwaysBindable(action); IEdmModel model = CreateFakeModel(annotationsManager); UrlHelper url = CreateMetadataLinkFactory(expectedMetadataPrefix); EntityInstanceContext context = CreateContext(model, url); context.SerializerContext.MetadataLevel = ODataMetadataLevel.FullMetadata; // Act ODataAction actualAction = _serializer.CreateODataAction(action, context); // Assert string expectedMetadata = expectedMetadataPrefix + "#" + expectedNamespace + "." + expectedActionName; ODataAction expectedAction = new ODataAction { Metadata = new Uri(expectedMetadata), Target = new Uri(expectedTarget), Title = expectedActionName }; AssertEqual(expectedAction, actualAction); }
private static bool AppendToLinks(OperationWrapper serviceAction, object resourceInstance, bool resourceInstanceInFeed, ref ODataAction actionToSerialize) { actionToSerialize.Metadata = new Uri(actionToSerialize.Metadata.OriginalString + "/SomethingThatWasAppended"); actionToSerialize.Target = new Uri(actionToSerialize.Target.OriginalString + "/SomethingThatWasAppended"); return true; }
public void TestSetTitleAnnotation() { // Arrange IEdmActionImport action = CreateFakeActionImport(true); IEdmDirectValueAnnotationsManager annonationsManager = CreateFakeAnnotationsManager(); IEdmModel model = CreateFakeModel(annonationsManager); string expectedTitle = "The title"; model.SetOperationTitleAnnotation(action.Operation, new OperationTitleAnnotation(expectedTitle)); ODataAction odataAction = new ODataAction(); // Act ODataEntityTypeSerializer.EmitTitle(model, action.Operation, odataAction); // Assert Assert.Equal(expectedTitle, odataAction.Title); }
private static bool AlwaysAdvertiseActions(OperationWrapper serviceAction, object resourceInstance, bool resourceInstanceInFeed, ref ODataAction actionToSerialize) { // the links should always be provided and always be absolute, even if they will be written relative in JSON-Light. actionToSerialize.Metadata.Should().NotBeNull().And.Subject.As<Uri>().IsAbsoluteUri.Should().BeTrue(); actionToSerialize.Target.Should().NotBeNull().And.Subject.As<Uri>().IsAbsoluteUri.Should().BeTrue(); return true; }
private static void AssertEqual(ODataAction expected, ODataAction actual) { if (expected == null) { Assert.Null(actual); return; } Assert.NotNull(actual); AssertEqual(expected.Metadata, actual.Metadata); AssertEqual(expected.Target, actual.Target); Assert.Equal(expected.Title, actual.Title); }
/// <summary> /// Adds the specified action to the current entry. /// </summary> /// <param name="action">The action whcih is fully populated with the data from the payload.</param> public void AddActionToEntry(ODataAction action) { Debug.Assert(action != null, "action != null"); this.entry.AddAction(action); }
public bool AdvertiseServiceAction(DataServiceOperationContext operationContext, ServiceAction serviceAction, object resourceInstance, bool resourceInstanceInFeed, ref ODataAction actionToSerialize) { throw new NotImplementedException(); }
public void ValidateOperationShouldThrowWhenOperationMetadataIsNull() { ODataOperation operation = new ODataAction(); Action action = () => ODataJsonLightValidationUtils.ValidateOperation(metadataDocumentUri, operation); action.ShouldThrow<ODataException>().WithMessage(ErrorStrings.ValidationUtils_ActionsAndFunctionsMustSpecifyMetadata(operation.GetType().Name)); }
/// <summary> /// Reads a an m:action or m:function in atom:entry. /// </summary> /// <param name="entryState">The reader entry state for the entry being read.</param> /// <returns>true, if the m:action or m:function was read succesfully, false otherwise.</returns> /// <remarks> /// Pre-Condition: XmlNodeType.Element m:action|m:function - The m:action or m:function element to read. /// Post-Condition: Any - The node after the m:action or m:function element if it was read by this method. /// XmlNodeType.Element m:action|m:function - The m:action or m:function element to read if it was not read by this method. /// </remarks> private bool TryReadOperation(IODataAtomReaderEntryState entryState) { Debug.Assert(entryState != null, "entryState != null"); this.XmlReader.AssertNotBuffering(); this.AssertXmlCondition(XmlNodeType.Element); Debug.Assert( this.XmlReader.NamespaceURI == AtomConstants.ODataMetadataNamespace, "The XML reader must be on a metadata (m:*) element for this method to work."); bool isAction = false; if (this.XmlReader.LocalNameEquals(this.ODataActionElementName)) { // m:action isAction = true; } else if (!this.XmlReader.LocalNameEquals(this.ODataFunctionElementName)) { // not an m:function either return false; } ODataOperation operation; if (isAction) { operation = new ODataAction(); entryState.Entry.AddAction((ODataAction)operation); } else { operation = new ODataFunction(); entryState.Entry.AddFunction((ODataFunction)operation); } string operationName = this.XmlReader.LocalName; // for error reporting while (this.XmlReader.MoveToNextAttribute()) { if (this.XmlReader.NamespaceEquals(this.EmptyNamespace)) { string attributeValue = this.XmlReader.Value; if (this.XmlReader.LocalNameEquals(this.ODataOperationMetadataAttribute)) { // For metadata, if the URI is relative we don't attempt to make it absolute using the service // base URI, because the ODataOperation metadata URI is relative to $metadata. operation.Metadata = this.ProcessUriFromPayload(attributeValue, this.XmlReader.XmlBaseUri, /*makeAbsolute*/ false); } else if (this.XmlReader.LocalNameEquals(this.ODataOperationTargetAttribute)) { operation.Target = this.ProcessUriFromPayload(attributeValue, this.XmlReader.XmlBaseUri); } else if (this.XmlReader.LocalNameEquals(this.ODataOperationTitleAttribute)) { operation.Title = this.XmlReader.Value; } // skip unknown attributes } } if (operation.Metadata == null) { throw new ODataException(ODataErrorStrings.ODataAtomEntryAndFeedDeserializer_OperationMissingMetadataAttribute(operationName)); } if (operation.Target == null) { throw new ODataException(ODataErrorStrings.ODataAtomEntryAndFeedDeserializer_OperationMissingTargetAttribute(operationName)); } // skip the content of m:action/m:function this.XmlReader.Skip(); return true; }
public virtual ODataAction CreateODataAction(IEdmFunctionImport action, EntityInstanceContext entityInstanceContext, ODataMetadataLevel metadataLevel) { if (action == null) { throw Error.ArgumentNull("action"); } if (entityInstanceContext == null) { throw Error.ArgumentNull("entityInstanceContext"); } IEdmModel model = entityInstanceContext.EdmModel; ActionLinkBuilder builder = model.GetActionLinkBuilder(action); if (builder == null) { return null; } if (ShouldOmitAction(action, model, builder, metadataLevel)) { return null; } Uri target = builder.BuildActionLink(entityInstanceContext); if (target == null) { return null; } Uri baseUri = new Uri(entityInstanceContext.Url.ODataLink(new MetadataPathSegment())); Uri metadata = new Uri(baseUri, "#" + CreateMetadataFragment(action, model, metadataLevel)); ODataAction odataAction = new ODataAction { Metadata = metadata, }; bool alwaysIncludeDetails = metadataLevel == ODataMetadataLevel.Default || metadataLevel == ODataMetadataLevel.FullMetadata; // Always omit the title in minimal/no metadata modes (it isn't customizable and thus always follows // conventions). if (alwaysIncludeDetails) { odataAction.Title = action.Name; } // Omit the target in minimal/no metadata modes unless it doesn't follow conventions. if (alwaysIncludeDetails || !builder.FollowsConventions) { odataAction.Target = target; } return odataAction; }
public void ValidateOperationShouldThrowWhenOperationMetadataIsNotMetadataReferenceProperty() { ODataOperation operation = new ODataAction {Metadata = new Uri("foobaz", UriKind.Relative)}; Action action = () => ODataJsonLightValidationUtils.ValidateOperation(metadataDocumentUri, operation); action.ShouldThrow<ODataException>().WithMessage(ErrorStrings.ValidationUtils_InvalidMetadataReferenceProperty("foobaz")); }