private static Action WriteServiceDocumentShouldError(ODataServiceDocument serviceDocument, IODataUrlResolver resolver = null)
        {
            MemoryStream memoryStream = new MemoryStream();
            ODataAtomServiceDocumentSerializer serializer = CreateAtomOutputContext(memoryStream, resolver);

            return(new Action(() => serializer.WriteServiceDocument(serviceDocument)));
        }
        public void QueryServiceDocument()
        {
            string[] types = new string[]
            {
                "text/html, application/xhtml+xml, */*",
                MimeTypes.ApplicationJson + MimeTypes.ODataParameterFullMetadata,
                MimeTypes.ApplicationJson + MimeTypes.ODataParameterMinimalMetadata,
                MimeTypes.ApplicationJson + MimeTypes.ODataParameterNoMetadata,
            };

            ODataMessageReaderSettings readerSettings = new ODataMessageReaderSettings()
            {
                BaseUri = ServiceBaseUri
            };

            foreach (var mimeType in types)
            {
                var requestMessage = new HttpWebRequestMessage(new Uri(ServiceBaseUri.AbsoluteUri, UriKind.Absolute));
                requestMessage.SetHeader("Accept", mimeType);
                var responseMessage = requestMessage.GetResponse();
                Assert.AreEqual(200, responseMessage.StatusCode);

                if (!mimeType.Contains(MimeTypes.ODataParameterNoMetadata))
                {
                    using (var messageReader = new ODataMessageReader(responseMessage, readerSettings, Model))
                    {
                        ODataServiceDocument workSpace = messageReader.ReadServiceDocument();

                        Assert.IsNotNull(workSpace.EntitySets.Single(c => c.Name == "People"));
                    }
                }
            }
        }
        public void ServiceDocument()
        {
            string[] types = new string[]
            {
                MimeTypes.ApplicationJson + MimeTypes.ODataParameterFullMetadata,
                MimeTypes.ApplicationJson + MimeTypes.ODataParameterMinimalMetadata,
                MimeTypes.ApplicationJson + MimeTypes.ODataParameterNoMetadata,
            };

            ODataMessageReaderSettings readerSettings = new ODataMessageReaderSettings()
            {
                BaseUri = ServiceBaseUri
            };

            foreach (var mimeType in types)
            {
                var requestMessage = new HttpWebRequestMessage(new Uri(ServiceBaseUri.AbsoluteUri, UriKind.Absolute));
                requestMessage.SetHeader("Accept", mimeType);
                var responseMessage = requestMessage.GetResponse();
                Assert.Equal(200, responseMessage.StatusCode);

                if (!mimeType.Contains(MimeTypes.ODataParameterNoMetadata))
                {
                    using (var messageReader = new ODataMessageReader(responseMessage, readerSettings, Model))
                    {
                        ODataServiceDocument workSpace = messageReader.ReadServiceDocument();
                        Assert.NotNull(workSpace.EntitySets.Single(c => c.Name == "Trucks"));
                        Assert.Equal("GetDefaultOutsideGeoFenceAlarm", workSpace.FunctionImports.First().Name);
                    }
                }
            }
        }
        public void GetODataServiceDocumentOnMetadataController_ReturnsODataODataServiceDocument()
        {
            // Arrange
            EdmModel           model     = new EdmModel();
            EdmEntityType      entity    = new EdmEntityType("NS", "Entity");
            EdmEntityContainer container = new EdmEntityContainer("NS", "Default");

            container.AddSingleton("me", entity);
            model.AddElement(entity);
            model.AddElement(container);

            HttpRequest reqest = RequestFactory.Create(model);

            MetadataController metadataController = new MetadataController();

            metadataController.ControllerContext.HttpContext = reqest.HttpContext;

            // Act
            ODataServiceDocument actual = metadataController.GetServiceDocument();

            // Assert
            Assert.NotNull(actual);
            Assert.Empty(actual.EntitySets);
            Assert.Empty(actual.FunctionImports);
            ODataSingletonInfo singletonInfo = Assert.Single(actual.Singletons);

            Assert.Equal("me", singletonInfo.Name);
        }
        /// <summary>
        /// Read a service document. 
        /// This method reads the service document from the input and returns 
        /// an <see cref="ODataServiceDocument"/> that represents the read service document.
        /// </summary>
        /// <returns>An <see cref="ODataServiceDocument"/> representing the read service document.</returns>
        /// <remarks>
        /// Pre-Condition:  JsonNodeType.None:        assumes that the JSON reader has not been used yet.
        /// Post-Condition: JsonNodeType.EndOfInput  
        /// </remarks>
        internal ODataServiceDocument ReadServiceDocument()
        {
            Debug.Assert(this.JsonReader.NodeType == JsonNodeType.None, "Pre-Condition: expected JsonNodeType.None, the reader must not have been used yet.");
            this.JsonReader.AssertNotBuffering();

            // We use this to store annotations and check for duplicate annotation names, but we don't really store properties in it.
            DuplicatePropertyNamesChecker duplicatePropertyNamesChecker = this.CreateDuplicatePropertyNamesChecker();

            // Position the reader on the first node
            this.ReadPayloadStart(
                ODataPayloadKind.ServiceDocument,
                duplicatePropertyNamesChecker,
                /*isReadingNestedPayload*/false,
                /*allowEmptyPayload*/false);

            ODataServiceDocument serviceDocument = this.ReadServiceDocumentImplementation(duplicatePropertyNamesChecker);

            // Read the end of the response.
            this.ReadPayloadEnd(/*isReadingNestedPayload*/ false);

            Debug.Assert(this.JsonReader.NodeType == JsonNodeType.EndOfInput, "Post-Condition: expected JsonNodeType.EndOfInput");
            this.JsonReader.AssertNotBuffering();

            return serviceDocument;
        }
        public async Task WriteServiceDocumentAsync()
        {
            var serviceDocument = new ODataServiceDocument
            {
                EntitySets = new List <ODataEntitySetInfo>
                {
                    new ODataEntitySetInfo {
                        Name = "Orders", Title = "Orders", Url = new Uri($"{ServiceUri}/Orders")
                    },
                    new ODataEntitySetInfo {
                        Name = "Customers", Title = "Customers", Url = new Uri($"{ServiceUri}/Customers")
                    }
                }
            };

            var result = await SetupJsonLightOutputContextAndRunTestAsync(
                (jsonLightOutputContext) => jsonLightOutputContext.WriteServiceDocumentAsync(serviceDocument));

            Assert.Equal(
                "{\"@odata.context\":\"http://tempuri.org/$metadata\"," +
                "\"value\":[" +
                "{\"name\":\"Orders\",\"kind\":\"EntitySet\",\"url\":\"http://tempuri.org/Orders\"}," +
                "{\"name\":\"Customers\",\"kind\":\"EntitySet\",\"url\":\"http://tempuri.org/Customers\"}]}",
                result);
        }
Exemplo n.º 7
0
        public ODataServiceDocument GetServiceDocument()
        {
            IEdmModel            model           = GetModel();
            ODataServiceDocument serviceDocument = new ODataServiceDocument();
            IEdmEntityContainer  container       = model.EntityContainer;

            // Add EntitySets into service document
            serviceDocument.EntitySets = container.EntitySets().Select(
                e => GetODataEntitySetInfo(model.GetNavigationSourceUrl(e).ToString(), e.Name));

            // Add Singletons into the service document
            IEnumerable <IEdmSingleton> singletons = container.Elements.OfType <IEdmSingleton>();

            serviceDocument.Singletons = singletons.Select(
                e => GetODataSingletonInfo(model.GetNavigationSourceUrl(e).ToString(), e.Name));

            // Add FunctionImports into service document
            // ODL spec says:
            // The edm:FunctionImport for a parameterless function MAY include the IncludeInServiceDocument attribute
            // whose Boolean value indicates whether the function import is advertised in the service document.
            // If no value is specified for this attribute, its value defaults to false.

            // Find all parameterless functions with "IncludeInServiceDocument = true"
            IEnumerable <IEdmFunctionImport> functionImports = container.Elements.OfType <IEdmFunctionImport>()
                                                               .Where(f => !f.Function.Parameters.Any() && f.IncludeInServiceDocument);

            serviceDocument.FunctionImports = functionImports.Distinct(new FunctionImportComparer())
                                              .Select(f => GetODataFunctionImportInfo(f.Name));

            return(serviceDocument);
        }
        private static Action WriteServiceDocumentShouldError(ODataServiceDocument serviceDocument, IODataPayloadUriConverter urlResolver = null)
        {
            MemoryStream memoryStream = new MemoryStream();
            var          serializer   = CreateODataJsonLightServiceDocumentSerializer(memoryStream, urlResolver);

            return(() => serializer.WriteServiceDocument(serviceDocument));
        }
        /// <summary>
        /// Asynchronously read a service document.
        /// This method reads the service document from the input and returns
        /// an <see cref="ODataServiceDocument"/> that represents the read service document.
        /// </summary>
        /// <returns>A task which returns an <see cref="ODataServiceDocument"/> representing the read service document.</returns>
        /// <remarks>
        /// Pre-Condition:  JsonNodeType.None:        assumes that the JSON reader has not been used yet.
        /// Post-Condition: JsonNodeType.EndOfInput
        /// </remarks>
        internal async Task <ODataServiceDocument> ReadServiceDocumentAsync()
        {
            Debug.Assert(this.JsonReader.NodeType == JsonNodeType.None, "Pre-Condition: expected JsonNodeType.None, the reader must not have been used yet.");
            this.JsonReader.AssertNotBuffering();

            // We use this to store annotations and check for duplicate annotation names, but we don't really store properties in it.
            PropertyAndAnnotationCollector propertyAndAnnotationCollector = this.CreatePropertyAndAnnotationCollector();

            await this.ReadPayloadStartAsync(
                ODataPayloadKind.ServiceDocument,
                propertyAndAnnotationCollector,
                isReadingNestedPayload : false,
                allowEmptyPayload : false).ConfigureAwait(false);

            ODataServiceDocument serviceDocument = await this.ReadServiceDocumentImplementationAsync(propertyAndAnnotationCollector)
                                                   .ConfigureAwait(false);

            // Read the end of the response.
            await this.ReadPayloadEndAsync(isReadingNestedPayload : false)
            .ConfigureAwait(false);

            Debug.Assert(this.JsonReader.NodeType == JsonNodeType.EndOfInput, "Post-Condition: expected JsonNodeType.EndOfInput");
            this.JsonReader.AssertNotBuffering();

            return(serviceDocument);
        }
        /// <summary>
        /// Writes a service document with the specified <paramref name="serviceDocument"/>
        /// as message payload.
        /// </summary>
        /// <param name="serviceDocument">The service document to write.</param>
        /// <remarks>It is the responsibility of this method to flush the output before the method returns.</remarks>
        internal override void WriteServiceDocument(ODataServiceDocument serviceDocument)
        {
            this.AssertSynchronous();

            this.WriteServiceDocumentImplementation(serviceDocument);
            this.Flush();
        }
        internal void WriteServiceDocumentMetadata(ODataServiceDocument serviceDocument)
        {
            Debug.Assert(serviceDocument != null, "serviceDocument != null");

            AtomWorkspaceMetadata metadata = serviceDocument.GetAnnotation<AtomWorkspaceMetadata>();
            AtomTextConstruct title = null;
            if (metadata != null)
            {
                title = metadata.Title;
            }

            if (title == null)
            {
                title = new AtomTextConstruct { Text = AtomConstants.AtomWorkspaceDefaultTitle };
            }

            if (this.UseServerFormatBehavior && title.Kind == AtomTextConstructKind.Text)
            {
                // For WCF DS server we must not write the type attribute, just a simple <atom:title>Default<atom:title>
                this.WriteElementWithTextContent(
                    AtomConstants.NonEmptyAtomNamespacePrefix,
                    AtomConstants.AtomTitleElementName,
                    AtomConstants.AtomNamespace,
                    title.Text);
            }
            else
            {
                // <atom:title>title</atom:title>
                this.WriteTextConstruct(AtomConstants.NonEmptyAtomNamespacePrefix, AtomConstants.AtomTitleElementName, AtomConstants.AtomNamespace, title);
            }
        }
        internal void WriteServiceDocumentMetadata(ODataServiceDocument serviceDocument)
        {
            Debug.Assert(serviceDocument != null, "serviceDocument != null");

            AtomWorkspaceMetadata metadata = serviceDocument.GetAnnotation <AtomWorkspaceMetadata>();
            AtomTextConstruct     title    = null;

            if (metadata != null)
            {
                title = metadata.Title;
            }

            if (title == null)
            {
                title = new AtomTextConstruct {
                    Text = AtomConstants.AtomWorkspaceDefaultTitle
                };
            }

            if (this.UseServerFormatBehavior && title.Kind == AtomTextConstructKind.Text)
            {
                // For WCF DS server we must not write the type attribute, just a simple <atom:title>Default<atom:title>
                this.WriteElementWithTextContent(
                    AtomConstants.NonEmptyAtomNamespacePrefix,
                    AtomConstants.AtomTitleElementName,
                    AtomConstants.AtomNamespace,
                    title.Text);
            }
            else
            {
                // <atom:title>title</atom:title>
                this.WriteTextConstruct(AtomConstants.NonEmptyAtomNamespacePrefix, AtomConstants.AtomTitleElementName, AtomConstants.AtomNamespace, title);
            }
        }
        /// <summary>
        /// Read a service document.
        /// This method reads the service document from the input and returns
        /// an <see cref="ODataServiceDocument"/> that represents the read service document.
        /// </summary>
        /// <returns>A task which returns an <see cref="ODataServiceDocument"/> representing the read service document.</returns>
        /// <remarks>
        /// Pre-Condition:  JsonNodeType.None:        assumes that the JSON reader has not been used yet.
        /// Post-Condition: JsonNodeType.EndOfInput
        /// </remarks>
        internal Task <ODataServiceDocument> ReadServiceDocumentAsync()
        {
            Debug.Assert(this.JsonReader.NodeType == JsonNodeType.None, "Pre-Condition: expected JsonNodeType.None, the reader must not have been used yet.");
            this.JsonReader.AssertNotBuffering();

            // We use this to store annotations and check for duplicate annotation names, but we don't really store properties in it.
            PropertyAndAnnotationCollector propertyAndAnnotationCollector = this.CreatePropertyAndAnnotationCollector();

            // Position the reader on the first node
            return(this.ReadPayloadStartAsync(
                       ODataPayloadKind.ServiceDocument,
                       propertyAndAnnotationCollector,
                       /*isReadingNestedPayload*/ false,
                       /*allowEmptyPayload*/ false)

                   .FollowOnSuccessWith(t =>
            {
                ODataServiceDocument serviceDocument = this.ReadServiceDocumentImplementation(propertyAndAnnotationCollector);

                // Read the end of the response.
                this.ReadPayloadEnd(/*isReadingNestedPayload*/ false);

                Debug.Assert(this.JsonReader.NodeType == JsonNodeType.EndOfInput, "Post-Condition: expected JsonNodeType.EndOfInput");
                this.JsonReader.AssertNotBuffering();

                return serviceDocument;
            }));
        }
Exemplo n.º 14
0
        private void TestEntitySetInServiceDocument(ODataServiceDocument serviceDocument)
        {
            Assert.NotNull(serviceDocument.EntitySets);
            var entitySet = Assert.Single(serviceDocument.EntitySets);

            Assert.Equal("entityset", entitySet.Name);
            Assert.Equal("http://service/entityset", entitySet.Url.ToString());
        }
Exemplo n.º 15
0
        public void PropertySettersNullTest()
        {
            ODataServiceDocument serviceDocument = new ODataServiceDocument();

            serviceDocument.EntitySets = null;

            this.Assert.IsNull(serviceDocument.EntitySets, "Expected null value for property 'EntitySets'.");
        }
        public void ShouldWriteServiceDocumentAsyncWithoutModel()
        {
            ODataServiceDocument serviceDocument = new ODataServiceDocument();

            serviceDocument.EntitySets = new ODataEntitySetInfo[] { new ODataEntitySetInfo {
                                                                        Name = "Customers", Url = new Uri("http://host/Customers")
                                                                    } };
            WriteAndValidate(outputContext => outputContext.WriteServiceDocumentAsync(serviceDocument).Wait(), "{\"@odata.context\":\"http://odata.org/test/$metadata\",\"value\":[{\"name\":\"Customers\",\"kind\":\"EntitySet\",\"url\":\"http://host/Customers\"}]}", writingResponse: true, synchronous: false);
        }
        private void TestEntitySetInServiceDocument(ODataServiceDocument serviceDocument)
        {
            serviceDocument.EntitySets.Should().NotBeNull();
            var entitySets = serviceDocument.EntitySets.ToList();

            entitySets.Count.Should().Be(1);
            entitySets[0].Name.Should().Be("entityset");
            entitySets[0].Url.ToString().Should().Be("http://service/entityset");
        }
Exemplo n.º 18
0
        /// <summary>
        /// Reads a service document.
        /// This method reads the service document from the input and returns
        /// an <see cref="ODataServiceDocument"/> that represents the read service document.
        /// </summary>
        /// <returns>An <see cref="ODataServiceDocument"/> representing the read service document.</returns>
        /// <remarks>
        /// Pre-Condition:   XmlNodeType.Element - The start element of the service document.
        /// Post-Condtion:   XmlNodeType.None    - The reader must be at the end of the input.
        /// </remarks>
        internal ODataServiceDocument ReadServiceDocument()
        {
            Debug.Assert(this.ReadingResponse, "Service document can only appear in a response message");
            Debug.Assert(this.XmlReader != null, "this.XmlReader != null");

            this.ReadPayloadStart();
            this.AssertXmlCondition(XmlNodeType.Element);

            // read the 'service' element.
            if (!this.XmlReader.NamespaceEquals(this.AtomPublishingNamespace) ||
                !this.XmlReader.LocalNameEquals(this.AtomPublishingServiceElementName))
            {
                throw new ODataException(Strings.ODataAtomServiceDocumentDeserializer_ServiceDocumentRootElementWrongNameOrNamespace(
                                             this.XmlReader.LocalName, this.XmlReader.NamespaceURI));
            }

            ODataServiceDocument serviceDocument = null;

            if (!this.XmlReader.IsEmptyElement)
            {
                // read over the start tag of the 'service' element.
                this.XmlReader.Read();
                serviceDocument = this.ReadWorkspace();
            }

            if (serviceDocument == null)
            {
                throw new ODataException(Strings.ODataAtomServiceDocumentDeserializer_MissingWorkspaceElement);
            }

            // skip anything which is not in the ATOM publishing namespace.
            this.SkipToElementInAtomPublishingNamespace();

            this.AssertXmlCondition(XmlNodeType.Element, XmlNodeType.EndElement);

            // When we reach here, we should be at the end-tag of the service element.
            if (this.XmlReader.NodeType == XmlNodeType.Element)
            {
                Debug.Assert(this.XmlReader.NamespaceEquals(this.AtomPublishingNamespace), "The current Xml element should have been in the 'app' namespace");

                // We only support a single serviceDocument inside a service document.
                if (this.XmlReader.LocalNameEquals(this.AtomPublishingWorkspaceElementName))
                {
                    throw new ODataException(Strings.ODataAtomServiceDocumentDeserializer_MultipleWorkspaceElementsFound);
                }

                // Throw error, if we encounter any other element in the ATOM publishing namespace.
                throw new ODataException(Strings.ODataAtomServiceDocumentDeserializer_UnexpectedElementInServiceDocument(this.XmlReader.LocalName));
            }

            // read over the end tag of the 'service' element.
            this.XmlReader.Read();

            this.ReadPayloadEnd();

            return(serviceDocument);
        }
Exemplo n.º 19
0
        public async Task WriteServiceDocumentAsync_WritesExpectedOutput(ODataServiceDocument serviceDocument, string expected)
        {
            var result = await SetupJsonLightServiceDocumentSerializerAndRunTestAsync(
                (jsonLightServiceDocumentSerializer) =>
            {
                return(jsonLightServiceDocumentSerializer.WriteServiceDocumentAsync(serviceDocument));
            });

            Assert.Equal(expected, result);
        }
Exemplo n.º 20
0
        public void CategoryMetadataOnWorkspaceCollectionCategoriesWriterTest()
        {
            var testCases = this.CreateAtomCategoryTestCases();

            // Convert test cases to test descriptions
            var testDescriptors = testCases.Select(testCase =>
            {
                AtomResourceCollectionMetadata metadata = new AtomResourceCollectionMetadata
                {
                    Categories = new AtomCategoriesMetadata
                    {
                        Categories = new[] { testCase.Category }
                    }
                };

                ODataEntitySetInfo collection = new ODataEntitySetInfo {
                    Url = new Uri("http://odata.org/collection")
                };
                collection.SetAnnotation(metadata);
                ODataServiceDocument serviceDocument = new ODataServiceDocument {
                    EntitySets = new[] { collection }
                };

                return(new PayloadWriterTestDescriptor <ODataServiceDocument>(
                           this.Settings,
                           serviceDocument,
                           testConfiguration =>
                           new AtomWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                {
                    Xml = testCase.Xml,
                    ExpectedException2 = testCase.ExpectedException,
                    FragmentExtractor = result => result
                                        .Element(TestAtomConstants.AtomPublishingXNamespace + TestAtomConstants.AtomPublishingWorkspaceElementName)
                                        .Element(TestAtomConstants.AtomPublishingXNamespace + TestAtomConstants.AtomPublishingCollectionElementName)
                                        .Element(TestAtomConstants.AtomPublishingXNamespace + TestAtomConstants.AtomPublishingCategoriesElementName)
                                        .Element(TestAtomConstants.AtomXNamespace + TestAtomConstants.AtomCategoryElementName)
                }));
            });

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.WriterTestConfigurationProvider.AtomFormatConfigurations.Where(tc => !tc.IsRequest),
                (testDescriptor, testConfiguration) =>
            {
                testConfiguration = testConfiguration.Clone();
                testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);

                TestWriterUtils.WriteAndVerifyTopLevelContent(
                    testDescriptor,
                    testConfiguration,
                    (messageWriter) => messageWriter.WriteServiceDocument(testDescriptor.PayloadItems.Single()),
                    this.Assert,
                    baselineLogger: this.Logger);
            });
        }
Exemplo n.º 21
0
 /// <summary>
 /// Writes a service document with the specified <paramref name="serviceDocument"/>
 /// as message payload.
 /// </summary>
 /// <param name="serviceDocument">The default serviceDocument to write in the service document.</param>
 public void WriteServiceDocument(ODataServiceDocument serviceDocument)
 {
     if (this.testConfiguration.Synchronous)
     {
         this.messageWriter.WriteServiceDocument(serviceDocument);
     }
     else
     {
         this.messageWriter.WriteServiceDocumentAsync(serviceDocument).Wait();
     }
 }
        private static void WriteServiceDocumentVerifyOutput(ODataServiceDocument serviceDocument, string expectedOutput)
        {
            MemoryStream memoryStream = new MemoryStream();
            var          serializer   = CreateODataJsonLightServiceDocumentSerializer(memoryStream);

            serializer.WriteServiceDocument(serviceDocument);
            serializer.JsonWriter.Flush();
            string actualResult = Encoding.UTF8.GetString(memoryStream.ToArray());

            Assert.Equal(expectedOutput, actualResult);
        }
Exemplo n.º 23
0
        public async Task WriteServiceDocumentAsync_ThrowsException(ODataServiceDocument serviceDocument, string exceptionMessage)
        {
            var exception = await Assert.ThrowsAsync <ODataException>(
                () => SetupJsonLightServiceDocumentSerializerAndRunTestAsync(
                    (jsonLightServiceDocumentSerializer) =>
            {
                return(jsonLightServiceDocumentSerializer.WriteServiceDocumentAsync(serviceDocument));
            }));

            Assert.Equal(exceptionMessage, exception.Message);
        }
Exemplo n.º 24
0
        /// <inheritdoc/>
        public override Task WriteObjectAsync(object graph, Type type, ODataMessageWriter messageWriter, ODataSerializerContext writeContext)
        {
            if (messageWriter == null)
            {
                throw Error.ArgumentNull("messageWriter");
            }

            ODataServiceDocument serviceDocument = GetServiceDocument(graph, type);

            return(messageWriter.WriteServiceDocumentAsync(serviceDocument));
        }
        /// <summary>
        /// Asynchronously writes a service document with the specified <paramref name="serviceDocument"/>
        /// as message payload.
        /// </summary>
        /// <param name="serviceDocument">The service document to write.</param>
        /// <returns>A task representing the asynchronous operation of writing the service document.</returns>
        /// <remarks>It is the responsibility of this method to flush the output before the task finishes.</remarks>
        internal override Task WriteServiceDocumentAsync(ODataServiceDocument serviceDocument)
        {
            this.AssertAsynchronous();

            return(TaskUtils.GetTaskForSynchronousOperationReturningTask(
                       () =>
            {
                this.WriteServiceDocumentImplementation(serviceDocument);
                return this.FlushAsync();
            }));
        }
Exemplo n.º 26
0
        /// <summary>
        /// Visits a serviceDocument.
        /// </summary>
        /// <param name="serviceDocument">The serviceDocument to visit.</param>
        protected virtual void VisitServiceDocument(ODataServiceDocument serviceDocument)
        {
            IEnumerable <ODataEntitySetInfo> collections = serviceDocument.EntitySets;

            if (collections != null)
            {
                foreach (ODataEntitySetInfo collection in collections)
                {
                    this.Visit(collection);
                }
            }
        }
        public void WriteFunctionImportShouldBeWrittenCorrectly()
        {
            var serviceDocument = new ODataServiceDocument()
            {
                FunctionImports = new ODataFunctionImportInfo[] {new ODataFunctionImportInfo() { Name = "functionImport", Url = new Uri("http://service/functionimport") }}
            };

            // Verifying the Href and name are written in the function Import element
            WriteServiceDocumentVerifyOutput(
                serviceDocument,
@"<?xml version=""1.0"" encoding=""utf-8""?><service xmlns=""http://www.w3.org/2007/app"" xmlns:atom=""http://www.w3.org/2005/Atom"" xmlns:m=""http://docs.oasis-open.org/odata/ns/metadata""><workspace><atom:title type=""text"">Default</atom:title><m:function-import href=""http://service/functionimport""><atom:title type=""text"">functionImport</atom:title></m:function-import></workspace></service>");
        }
        public void WriteNullFunctionImportShouldThrow()
        {
            var functionImports = new List<ODataFunctionImportInfo>();
            functionImports.Add(null);
            var serviceDocument = new ODataServiceDocument()
            {
                FunctionImports = functionImports
            };

            //Note: Only testing one of three exceptions that occurs in the Validate ServiceDocumentElements because if one throws then we know that the code path is going through
            // the validation method. If the validation method is changed then in the future two exception tests might be needed.
            WriteServiceDocumentShouldError(serviceDocument).ShouldThrow<ODataException>().WithMessage(ODataStrings.ValidationUtils_WorkspaceResourceMustNotContainNullItem);
        }
        public void WriteNullFunctionImportShouldThrow()
        {
            var functionImports = new List <ODataFunctionImportInfo>();

            functionImports.Add(null);
            var serviceDocument = new ODataServiceDocument()
            {
                FunctionImports = functionImports
            };

            //Note: Only testing one of three exceptions that occurs in the Validate ServiceDocumentElements because if one throws then we know that the code path is going through
            // the validation method. If the validation method is changed then in the future two exception tests might be needed.
            WriteServiceDocumentShouldError(serviceDocument).Throws <ODataException>(Strings.ValidationUtils_WorkspaceResourceMustNotContainNullItem);
        }
        private static void WriteServiceDocumentVerifyOutput(ODataServiceDocument serviceDocument, string expectedoutput = null, IODataUrlResolver resolver = null)
        {
            MemoryStream memoryStream = new MemoryStream();
            ODataAtomServiceDocumentSerializer serializer = CreateAtomOutputContext(memoryStream, resolver);

            serializer.WriteServiceDocument(serviceDocument);
            serializer.XmlWriter.Flush();
            var resultsWritten = Encoding.UTF8.GetString(memoryStream.GetBuffer());

            if (expectedoutput != null)
            {
                resultsWritten.Should().Be(expectedoutput);
            }
        }
Exemplo n.º 31
0
        /// <summary>Determines an extension method to get the <see cref="T:System.Data.OData.Atom.AtomWorkspaceMetadata" /> for an annotatable serviceDocument.</summary>
        /// <returns>An <see cref="T:Microsoft.OData.Core.Atom.AtomWorkspaceMetadata" /> instance or null if no annotation of that type exists.</returns>
        /// <param name="serviceDocument">The serviceDocument to get the annotation from.</param>
        public static AtomWorkspaceMetadata Atom(this ODataServiceDocument serviceDocument)
        {
            ExceptionUtils.CheckArgumentNotNull(serviceDocument, "serviceDocument");

            AtomWorkspaceMetadata workspaceMetadata = serviceDocument.GetAnnotation <AtomWorkspaceMetadata>();

            if (workspaceMetadata == null)
            {
                workspaceMetadata = new AtomWorkspaceMetadata();
                serviceDocument.SetAnnotation(workspaceMetadata);
            }

            return(workspaceMetadata);
        }
Exemplo n.º 32
0
        public void PropertyGettersAndSettersTest()
        {
            ODataEntitySetInfo collection1 = new ODataEntitySetInfo();
            ODataEntitySetInfo collection2 = new ODataEntitySetInfo();
            ODataEntitySetInfo collection3 = new ODataEntitySetInfo();

            ODataEntitySetInfo[] collections = new ODataEntitySetInfo[] { collection1, collection2, collection3 };

            ODataServiceDocument serviceDocument = new ODataServiceDocument()
            {
                EntitySets = collections
            };

            this.Assert.AreSame(collections, serviceDocument.EntitySets, "Expected reference equal values for property 'EntitySets'.");
        }
        /// <summary>
        /// Writes a service document with the specified <paramref name="serviceDocument"/>
        /// as message payload.
        /// </summary>
        /// <param name="serviceDocument">The default serviceDocument to write in the service document.</param>
        public void WriteServiceDocument(ODataServiceDocument serviceDocument)
        {
            if (this.testConfiguration.Synchronous)
            {
                this.messageWriter.WriteServiceDocument(serviceDocument);
            }
            else
            {
#if SILVERLIGHT
                throw new TaupoNotSupportedException("This test is not supported in aSynchronous mode in Silverlight");
#else
                this.messageWriter.WriteServiceDocumentAsync(serviceDocument).Wait();
#endif
            }
        }
        public void EnsureNonNullODataUrlResolverExecutedWhenWritingFunctionImportInServiceDocument()
        {
            var serviceDocument = new ODataServiceDocument()
            {
                FunctionImports = new ODataFunctionImportInfo[] { new ODataFunctionImportInfo() { Name = "functionImport", Url = new Uri("http://service/functionimport") } }
            };

            bool invoked = false;
            var resolver = new ServiceDocumentTestUrlResolver();
            resolver.ResolveUrlFunc = (uri, uri1) => 
            { 
                invoked = true;
                return uri;
            };

            WriteServiceDocumentVerifyOutput(serviceDocument, null, resolver);
            invoked.Should().BeTrue();
        }
        private static Action WriteServiceDocumentShouldError(ODataServiceDocument serviceDocument, IODataUrlResolver urlResolver = null)
        {
            MemoryStream memoryStream = new MemoryStream();
            var serializer = CreateODataJsonLightServiceDocumentSerializer(memoryStream, urlResolver);

            return () => serializer.WriteServiceDocument(serviceDocument);
        }
        private static void WriteServiceDocumentVerifyOutput(ODataServiceDocument serviceDocument, string expectedOutput)
        {
            MemoryStream memoryStream = new MemoryStream();
            var serializer = CreateODataJsonLightServiceDocumentSerializer(memoryStream);

            serializer.WriteServiceDocument(serviceDocument);
            serializer.JsonWriter.Flush();
            string actualResult = Encoding.UTF8.GetString(memoryStream.ToArray());
            actualResult.Should().Be(expectedOutput);
        }
        /// <summary>
        /// Writes a service document in ATOM/XML format.
        /// </summary>
        /// <param name="serviceDocument">The service document to write.</param>
        internal void WriteServiceDocument(ODataServiceDocument serviceDocument)
        {
            Debug.Assert(serviceDocument != null, "serviceDocument != null");

            this.WritePayloadStart();

            // <app:service>
            this.XmlWriter.WriteStartElement(string.Empty, AtomConstants.AtomPublishingServiceElementName, AtomConstants.AtomPublishingNamespace);

            // xml:base=...
            if (this.MessageWriterSettings.PayloadBaseUri != null)
            {
                this.XmlWriter.WriteAttributeString(AtomConstants.XmlBaseAttributeName, AtomConstants.XmlNamespace, this.MessageWriterSettings.PayloadBaseUri.AbsoluteUri);
            }

            // xmlns=http://www.w3.org/2007/app
            this.XmlWriter.WriteAttributeString(AtomConstants.XmlnsNamespacePrefix, AtomConstants.XmlNamespacesNamespace, AtomConstants.AtomPublishingNamespace);

            // xmlns:atom="http://www.w3.org/2005/Atom"
            this.XmlWriter.WriteAttributeString(
                AtomConstants.NonEmptyAtomNamespacePrefix,
                AtomConstants.XmlNamespacesNamespace,
                AtomConstants.AtomNamespace);

            this.XmlWriter.WriteAttributeString(
                AtomConstants.ODataMetadataNamespacePrefix,
                AtomConstants.XmlNamespacesNamespace,
                AtomConstants.ODataMetadataNamespace);

            // metadata:context=...
            this.WriteContextUriProperty(this.contextUriBuilder.BuildContextUri(ODataPayloadKind.ServiceDocument));

            // <app:serviceDocument>
            this.XmlWriter.WriteStartElement(string.Empty, AtomConstants.AtomPublishingWorkspaceElementName, AtomConstants.AtomPublishingNamespace);

            this.atomServiceDocumentMetadataSerializer.WriteServiceDocumentMetadata(serviceDocument);

            if (serviceDocument.EntitySets != null)
            {
                foreach (ODataEntitySetInfo collectionInfo in serviceDocument.EntitySets)
                {
                    this.WriteEntitySetInfo(collectionInfo);
                }
            }

            if (serviceDocument.Singletons != null)
            {
                foreach (ODataSingletonInfo singletonInfo in serviceDocument.Singletons)
                {
                    this.WriteSingletonInfo(singletonInfo);
                }
            }

            HashSet<string> functionImportsWritten = new HashSet<string>(StringComparer.Ordinal);

            if (serviceDocument.FunctionImports != null)
            {
                foreach (ODataFunctionImportInfo functionImportInfo in serviceDocument.FunctionImports)
                {
                    if (functionImportInfo == null)
                    {
                        throw new ODataException(Strings.ValidationUtils_WorkspaceResourceMustNotContainNullItem);
                    }

                    if (!functionImportsWritten.Contains(functionImportInfo.Name))
                    {
                        functionImportsWritten.Add(functionImportInfo.Name);
                        this.WriteFunctionImportInfo(functionImportInfo);
                    }
                }
            }

            // </app:serviceDocument>
            this.XmlWriter.WriteEndElement();

            // </app:service>
            this.XmlWriter.WriteEndElement();

            this.WritePayloadEnd();
        }
        /// <summary>
        /// Writes a service document with the specified <paramref name="serviceDocument"/> 
        /// as message payload.
        /// </summary>
        /// <param name="serviceDocument">The service dcument to write.</param>
        /// <remarks>It is the responsibility of this method to flush the output before the method returns.</remarks>
        internal override void WriteServiceDocument(ODataServiceDocument serviceDocument)
        {
            this.AssertSynchronous();

            this.WriteServiceDocumentImplementation(serviceDocument);
            this.Flush();
        }
        /// <summary>
        /// Writes a service document in JsonLight format.
        /// </summary>
        /// <param name="serviceDocument">The service document to write.</param>
        internal void WriteServiceDocument(ODataServiceDocument serviceDocument)
        {
            Debug.Assert(serviceDocument != null, "serviceDocument != null");

            this.WriteTopLevelPayload(
                () =>
                {
                    // "{"
                    this.JsonWriter.StartObjectScope();

                    // "@odata.context":...
                    this.WriteContextUriProperty(ODataPayloadKind.ServiceDocument);

                    // "value":
                    this.JsonWriter.WriteValuePropertyName();

                    // "["
                    this.JsonWriter.StartArrayScope();

                    if (serviceDocument.EntitySets != null)
                    {
                        foreach (ODataEntitySetInfo collectionInfo in serviceDocument.EntitySets)
                        {
                            this.WriteServiceDocumentElement(collectionInfo, JsonLightConstants.ServiceDocumentEntitySetKindName);
                        }
                    }

                    if (serviceDocument.Singletons != null)
                    {
                        foreach (ODataSingletonInfo singletonInfo in serviceDocument.Singletons)
                        {
                            this.WriteServiceDocumentElement(singletonInfo, JsonLightConstants.ServiceDocumentSingletonKindName);
                        }
                    }

                    HashSet<string> functionImportsWritten = new HashSet<string>(StringComparer.Ordinal);

                    if (serviceDocument.FunctionImports != null)
                    {
                        foreach (ODataFunctionImportInfo functionImportInfo in serviceDocument.FunctionImports)
                        {
                            if (functionImportInfo == null)
                            {
                                throw new ODataException(Strings.ValidationUtils_WorkspaceResourceMustNotContainNullItem);
                            }

                            if (!functionImportsWritten.Contains(functionImportInfo.Name))
                            {
                                functionImportsWritten.Add(functionImportInfo.Name);
                                this.WriteServiceDocumentElement(functionImportInfo, JsonLightConstants.ServiceDocumentFunctionImportKindName);
                            }
                        }
                    }

                    // "]"
                    this.JsonWriter.EndArrayScope();

                    // "}"
                    this.JsonWriter.EndObjectScope();
                });
        }
        /// <summary>
        /// Asynchronously writes a service document with the specified <paramref name="serviceDocument"/> 
        /// as message payload.
        /// </summary>
        /// <param name="serviceDocument">The service document to write.</param>
        /// <returns>A task representing the asynchronous operation of writing the service document.</returns>
        /// <remarks>It is the responsibility of this method to flush the output before the task finishes.</remarks>
        internal override Task WriteServiceDocumentAsync(ODataServiceDocument serviceDocument)
        {
            this.AssertAsynchronous();

            return TaskUtils.GetTaskForSynchronousOperationReturningTask(
                () =>
                {
                    this.WriteServiceDocumentImplementation(serviceDocument);
                    return this.FlushAsync();
                });
        }
        private static void WriteServiceDocumentVerifyOutput(ODataServiceDocument serviceDocument, string expectedoutput = null, IODataUrlResolver resolver = null)
        {
            MemoryStream memoryStream = new MemoryStream();
            ODataAtomServiceDocumentSerializer serializer = CreateAtomOutputContext(memoryStream, resolver);

            serializer.WriteServiceDocument(serviceDocument);
            serializer.XmlWriter.Flush();
            var resultsWritten = Encoding.UTF8.GetString(memoryStream.GetBuffer());
            if (expectedoutput != null)
            {
                resultsWritten.Should().Be(expectedoutput);
            }
        }
Exemplo n.º 42
0
 /// <summary>
 /// Writes a service document with the specified <paramref name="serviceDocument"/> 
 /// as message payload.
 /// </summary>
 /// <param name="serviceDocument">The service document to write.</param>
 private void WriteServiceDocumentImplementation(ODataServiceDocument serviceDocument)
 {
     ODataAtomServiceDocumentSerializer atomServiceDocumentSerializer = new ODataAtomServiceDocumentSerializer(this);
     atomServiceDocumentSerializer.WriteServiceDocument(serviceDocument);
 }
        public void ServiceDocument()
        {
            foreach (ODataFormat mimeType in mimeTypes)
            {
                string payload, contentType;

                this.WriteAndValidateContextUri(mimeType, model, omWriter =>
                {
                    ODataServiceDocument serviceDocument = new ODataServiceDocument();
                    serviceDocument.EntitySets = new ODataEntitySetInfo[] { new ODataEntitySetInfo { Name = "People", Url = new Uri(TestBaseUri + "People") } };
                    omWriter.WriteServiceDocument(serviceDocument);
                }, string.Format("\"{0}$metadata\"", TestBaseUri), out payload, out contentType);
                this.ReadPayload(payload, contentType, model, omReader => omReader.ReadServiceDocument());
            }
        }
 private static Action WriteServiceDocumentShouldError(ODataServiceDocument serviceDocument, IODataUrlResolver resolver = null)
 {
     MemoryStream memoryStream = new MemoryStream();
     ODataAtomServiceDocumentSerializer serializer = CreateAtomOutputContext(memoryStream, resolver);
     return new Action(() => serializer.WriteServiceDocument(serviceDocument));
 }
 /// <summary>
 /// Writes a service document with the specified <paramref name="serviceDocument"/> 
 /// as message payload.
 /// </summary>
 /// <param name="serviceDocument">The service document to write.</param>
 private void WriteServiceDocumentImplementation(ODataServiceDocument serviceDocument)
 {
     ODataJsonLightServiceDocumentSerializer jsonLightServiceDocumentSerializer = new ODataJsonLightServiceDocumentSerializer(this);
     jsonLightServiceDocumentSerializer.WriteServiceDocument(serviceDocument);
 }
 private void TestEntitySetInServiceDocument(ODataServiceDocument serviceDocument)
 {
     serviceDocument.EntitySets.Should().NotBeNull();
     var entitySets = serviceDocument.EntitySets.ToList();
     entitySets.Count.Should().Be(1);
     entitySets[0].Name.Should().Be("entityset");
     entitySets[0].Url.ToString().Should().Be("http://service/entityset");
 }
 public void ShouldWriteServiceDocumentAsyncWithoutModel()
 {
     ODataServiceDocument serviceDocument = new ODataServiceDocument();
     serviceDocument.EntitySets = new ODataEntitySetInfo[] { new ODataEntitySetInfo { Name = "Customers", Url = new Uri("http://host/Customers") } };
     WriteAndValidate(outputContext => outputContext.WriteServiceDocumentAsync(serviceDocument).Wait(), "{\"@odata.context\":\"http://odata.org/test/$metadata\",\"value\":[{\"name\":\"Customers\",\"kind\":\"EntitySet\",\"url\":\"http://host/Customers\"}]}", writingResponse: true, synchronous: false);
 }