예제 #1
0
        internal ODataWorkspace ReadServiceDocument()
        {
            base.ReadPayloadStart();
            if (!base.XmlReader.NamespaceEquals(this.AtomPublishingNamespace) || !base.XmlReader.LocalNameEquals(this.AtomPublishingServiceElementName))
            {
                throw new ODataException(Strings.ODataAtomServiceDocumentDeserializer_ServiceDocumentRootElementWrongNameOrNamespace(base.XmlReader.LocalName, base.XmlReader.NamespaceURI));
            }
            ODataWorkspace workspace = null;

            if (!base.XmlReader.IsEmptyElement)
            {
                base.XmlReader.Read();
                workspace = this.ReadWorkspace();
            }
            if (workspace == null)
            {
                throw new ODataException(Strings.ODataAtomServiceDocumentDeserializer_MissingWorkspaceElement);
            }
            this.SkipToElementInAtomPublishingNamespace();
            if (base.XmlReader.NodeType == XmlNodeType.Element)
            {
                if (base.XmlReader.LocalNameEquals(this.AtomPublishingWorkspaceElementName))
                {
                    throw new ODataException(Strings.ODataAtomServiceDocumentDeserializer_MultipleWorkspaceElementsFound);
                }
                throw new ODataException(Strings.ODataAtomServiceDocumentDeserializer_UnexpectedElementInServiceDocument(base.XmlReader.LocalName));
            }
            base.XmlReader.Read();
            base.ReadPayloadEnd();
            return(workspace);
        }
예제 #2
0
        internal void WriteServiceDocument(ODataWorkspace defaultWorkspace)
        {
            IEnumerable <ODataResourceCollectionInfo> collections = defaultWorkspace.Collections;

            base.WritePayloadStart();
            base.XmlWriter.WriteStartElement(string.Empty, "service", "http://www.w3.org/2007/app");
            if (base.MessageWriterSettings.BaseUri != null)
            {
                base.XmlWriter.WriteAttributeString("base", "http://www.w3.org/XML/1998/namespace", base.MessageWriterSettings.BaseUri.AbsoluteUri);
            }
            base.XmlWriter.WriteAttributeString("xmlns", "http://www.w3.org/2000/xmlns/", "http://www.w3.org/2007/app");
            base.XmlWriter.WriteAttributeString("atom", "http://www.w3.org/2000/xmlns/", "http://www.w3.org/2005/Atom");
            base.XmlWriter.WriteStartElement(string.Empty, "workspace", "http://www.w3.org/2007/app");
            this.atomServiceDocumentMetadataSerializer.WriteWorkspaceMetadata(defaultWorkspace);
            if (collections != null)
            {
                foreach (ODataResourceCollectionInfo info in collections)
                {
                    ValidationUtils.ValidateResourceCollectionInfo(info);
                    base.XmlWriter.WriteStartElement(string.Empty, "collection", "http://www.w3.org/2007/app");
                    base.XmlWriter.WriteAttributeString("href", base.UriToUrlAttributeValue(info.Url));
                    this.atomServiceDocumentMetadataSerializer.WriteResourceCollectionMetadata(info);
                    base.XmlWriter.WriteEndElement();
                }
            }
            base.XmlWriter.WriteEndElement();
            base.XmlWriter.WriteEndElement();
            base.WritePayloadEnd();
        }
        /// <summary>
        /// Read a service document.
        /// This method reads the service document from the input and returns
        /// an <see cref="ODataWorkspace"/> that represents the read service document.
        /// </summary>
        /// <returns>A task which returns an <see cref="ODataWorkspace"/> 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 <ODataWorkspace> ReadServiceDocumentAsync()
        {
            DebugUtils.CheckNoExternalCallers();
            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
            return(this.ReadPayloadStartAsync(
                       ODataPayloadKind.ServiceDocument,
                       duplicatePropertyNamesChecker,
                       /*isReadingNestedPayload*/ false,
                       /*allowEmptyPayload*/ false)

                   .FollowOnSuccessWith(t =>
            {
                ODataWorkspace resultWorkspace = 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 resultWorkspace;
            }));
        }
예제 #4
0
 internal override Task WriteServiceDocumentAsync(ODataWorkspace defaultWorkspace)
 {
     return(TaskUtils.GetTaskForSynchronousOperationReturningTask(delegate {
         this.WriteServiceDocumentImplementation(defaultWorkspace);
         return this.FlushAsync();
     }));
 }
예제 #5
0
        public void WriteServiceDocument()
        {
            var msgWriter   = new ODataMessageWriter(_response, _writerSettings, _map.Model);
            var collections = new List <ODataResourceCollectionInfo>();

            foreach (
                var entityContainer in
                _map.Model.EntityContainers().Where(ec => _map.Model.IsDefaultEntityContainer(ec)))
            {
                foreach (var es in entityContainer.EntitySets())
                {
                    var collectionInfo = new ODataResourceCollectionInfo {
                        Url = new Uri(es.Name, UriKind.Relative)
                    };
                    var metadata = new AtomResourceCollectionMetadata {
                        Title = es.Name
                    };
                    collectionInfo.SetAnnotation(metadata);
                    collections.Add(collectionInfo);
                }
            }
            var workspace = new ODataWorkspace {
                Collections = collections
            };

            msgWriter.WriteServiceDocument(workspace);
        }
        internal void WriteWorkspaceMetadata(ODataWorkspace workspace)
        {
            DebugUtils.CheckNoExternalCallers();
            Debug.Assert(workspace != null, "workspace != null");

            AtomWorkspaceMetadata metadata = workspace.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);
            }
        }
예제 #7
0
        /// <summary>
        /// Writes a service document with the specified <paramref name="defaultWorkspace"/>
        /// as message payload.
        /// </summary>
        /// <param name="defaultWorkspace">The default workspace to write in the service document.</param>
        /// <remarks>It is the responsibility of this method to flush the output before the method returns.</remarks>
        internal override void WriteServiceDocument(ODataWorkspace defaultWorkspace)
        {
            DebugUtils.CheckNoExternalCallers();
            this.AssertSynchronous();

            this.WriteServiceDocumentImplementation(defaultWorkspace);
            this.Flush();
        }
        /// <summary>
        /// Reads a service document.
        /// This method reads the service document from the input and returns
        /// an <see cref="ODataWorkspace"/> that represents the read service document.
        /// </summary>
        /// <returns>An <see cref="ODataWorkspace"/> 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 ODataWorkspace ReadServiceDocument()
        {
            DebugUtils.CheckNoExternalCallers();
            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));
            }

            ODataWorkspace workspace = null;

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

            if (workspace == 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 workspace 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(workspace);
        }
예제 #9
0
        public dynamic Execute(dynamic parameters, INancyModule module)
        {
            NuGetODataModelBuilderODataPackage builder = new NuGetODataModelBuilderODataPackage();

            builder.Build();

            IODataResponseMessage      message        = new MemoryResponseMessage();
            ODataMessageWriterSettings writerSettings = new ODataMessageWriterSettings();

            var url = module.Request.Url.ToString();

            if (!url.EndsWith("/"))
            {
                url += "/";
            }

            writerSettings.BaseUri = new Uri(url);


            using (var msgWriter = new ODataMessageWriter(message, writerSettings, builder.Model))
            {
                var workspace = new ODataWorkspace
                {
                    Collections = new List <ODataResourceCollectionInfo>
                    {
                        new ODataResourceCollectionInfo
                        {
                            Name = "Packages",
                            Url  = new Uri("Packages", UriKind.Relative)
                        }
                    }
                };

                msgWriter.WriteServiceDocument(workspace);

                var msgStream = message.GetStream();

                msgStream.Seek(0, SeekOrigin.Begin);

                StreamReader reader = new StreamReader(msgStream);

                string text = reader.ReadToEnd();

                return(new Response
                {
                    ContentType = "application/xml; charset=utf-8",
                    Contents = contentStream =>
                    {
                        var byteData = Encoding.UTF8.GetBytes(text);
                        contentStream.Write(byteData, 0, byteData.Length);
                        msgStream.Dispose();
                        reader.Dispose();
                    }
                });
            }
        }
예제 #10
0
        /// <summary>
        /// Asynchronously writes a service document with the specified <paramref name="defaultWorkspace"/>
        /// as message payload.
        /// </summary>
        /// <param name="defaultWorkspace">The default workspace to write in the service document.</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(ODataWorkspace defaultWorkspace)
        {
            DebugUtils.CheckNoExternalCallers();
            this.AssertAsynchronous();

            return(TaskUtils.GetTaskForSynchronousOperationReturningTask(
                       () =>
            {
                this.WriteServiceDocumentImplementation(defaultWorkspace);
                return this.FlushAsync();
            }));
        }
예제 #11
0
        public static AtomWorkspaceMetadata Atom(this ODataWorkspace workspace)
        {
            ExceptionUtils.CheckArgumentNotNull <ODataWorkspace>(workspace, "workspace");
            AtomWorkspaceMetadata annotation = workspace.GetAnnotation <AtomWorkspaceMetadata>();

            if (annotation == null)
            {
                annotation = new AtomWorkspaceMetadata();
                workspace.SetAnnotation <AtomWorkspaceMetadata>(annotation);
            }
            return(annotation);
        }
        public ODataWorkspace GetServiceDocument()
        {
            IEdmModel model = GetModel();
            ODataWorkspace workspace = new ODataWorkspace();
            IEdmEntityContainer container = model.EntityContainers().Single();
            IEnumerable<IEdmEntitySet> entitysets = container.EntitySets();

            IEnumerable<ODataResourceCollectionInfo> collections = entitysets.Select(
                e => GetODataResourceCollectionInfo(model.GetEntitySetUrl(e).ToString(), e.Name));
            workspace.Collections = collections;

            return workspace;
        }
예제 #13
0
        /// <summary>
        /// Extension method to get the <see cref="AtomWorkspaceMetadata"/> for an annotatable workspace.
        /// </summary>
        /// <param name="workspace">The workspace to get the annotation from.</param>
        /// <returns>An <see cref="AtomWorkspaceMetadata" /> instance or null if no annotation of that type exists.</returns>
        public static AtomWorkspaceMetadata Atom(this ODataWorkspace workspace)
        {
            ExceptionUtils.CheckArgumentNotNull(workspace, "workspace");

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

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

            return(workspaceMetadata);
        }
예제 #14
0
        public ODataWorkspace GetServiceDocument()
        {
            IEdmModel                   model      = GetModel();
            ODataWorkspace              workspace  = new ODataWorkspace();
            IEdmEntityContainer         container  = model.EntityContainers().Single();
            IEnumerable <IEdmEntitySet> entitysets = container.EntitySets();

            IEnumerable <ODataResourceCollectionInfo> collections = entitysets.Select(
                e => GetODataResourceCollectionInfo(model.GetEntitySetUrl(e).ToString(), e.Name));

            workspace.Collections = collections;

            return(workspace);
        }
예제 #15
0
        public HttpResponseMessage GetServiceDocument()
        {
            IEdmModel          model;
            MediaTypeFormatter odataFormatter = GetFormatter(typeof(ODataWorkspace), out model);

            ODataWorkspace              workspace  = new ODataWorkspace();
            IEdmEntityContainer         container  = model.EntityContainers().Single();
            IEnumerable <IEdmEntitySet> entitysets = container.EntitySets();

            IEnumerable <ODataResourceCollectionInfo> collections = entitysets.Select(e => GetODataResourceCollectionInfo(model.GetEntitySetUrl(e).ToString(), e.Name));

            workspace.Collections = collections;

            // This controller requires and supports only the OData formatter.
            return(Request.CreateResponse(HttpStatusCode.OK, workspace, odataFormatter));
        }
        internal void WriteServiceDocument(DataServiceProviderWrapper provider)
        {
            ODataWorkspace defaultWorkspace = new ODataWorkspace {
                Collections = provider.GetResourceSets().Select <ResourceSetWrapper, ODataResourceCollectionInfo>(delegate(ResourceSetWrapper rs) {
                    ODataResourceCollectionInfo info = new ODataResourceCollectionInfo {
                        Url = new Uri(rs.Name, UriKind.RelativeOrAbsolute)
                    };
                    AtomResourceCollectionMetadata annotation = new AtomResourceCollectionMetadata();
                    AtomTextConstruct construct = new AtomTextConstruct {
                        Text = rs.Name
                    };
                    annotation.Title = construct;
                    info.SetAnnotation <AtomResourceCollectionMetadata>(annotation);
                    return(info);
                })
            };

            this.writer.WriteServiceDocument(defaultWorkspace);
        }
예제 #17
0
        /// <summary>
        /// Writes a service document in JSON format.
        /// </summary>
        /// <param name="jsonWriter">The <see cref="JsonWriter"/> to write to.</param>
        /// <param name="metadata">The metadata provider to use or null if no metadata is available.</param>
        /// <param name="defaultWorkspace">The default workspace to write in the service document.</param>
        internal static void WriteServiceDocument(
            JsonWriter jsonWriter,
            DataServiceMetadataProviderWrapper metadata,
            ODataWorkspace defaultWorkspace)
        {
            DebugUtils.CheckNoExternalCallers();
            Debug.Assert(jsonWriter != null, "jsonWriter != null");
            Debug.Assert(defaultWorkspace != null, "defaultWorkspace != null");

            IEnumerable <ODataResourceCollectionInfo> collections =
                ValidationUtils.ValidateWorkspace(metadata == null ? null : metadata.ResourceSets, defaultWorkspace);

            Debug.Assert(collections != null, "collections != null");

            WriteDataWrapper(
                jsonWriter,
                true,
                () =>
            {
                // "{"
                jsonWriter.StartObjectScope();

                // "EntitySets":
                jsonWriter.WriteName(JsonConstants.ODataServiceDocumentEntitySetsName);

                // "["
                jsonWriter.StartArrayScope();

                foreach (ODataResourceCollectionInfo collectionInfo in collections)
                {
                    ValidationUtils.ValidateResourceCollectionInfo(collectionInfo);

                    // <collection name>
                    jsonWriter.WriteValue(collectionInfo.Name);
                }

                // "]"
                jsonWriter.EndArrayScope();

                // "}"
                jsonWriter.EndObjectScope();
            });
        }
        internal void WriteServiceDocument(ODataWorkspace defaultWorkspace)
        {
            IEnumerable <ODataResourceCollectionInfo> collections = defaultWorkspace.Collections;

            base.WriteTopLevelPayload(delegate {
                this.JsonWriter.StartObjectScope();
                this.JsonWriter.WriteName("EntitySets");
                this.JsonWriter.StartArrayScope();
                if (collections != null)
                {
                    foreach (ODataResourceCollectionInfo info in collections)
                    {
                        ValidationUtils.ValidateResourceCollectionInfo(info);
                        this.JsonWriter.WriteValue(UriUtilsCommon.UriToString(info.Url));
                    }
                }
                this.JsonWriter.EndArrayScope();
                this.JsonWriter.EndObjectScope();
            });
        }
예제 #19
0
        /// <inheritdoc/>
        public override void WriteObject(object graph, Type type, ODataMessageWriter messageWriter, ODataSerializerContext writeContext)
        {
            if (messageWriter == null)
            {
                throw Error.ArgumentNull("messageWriter");
            }
            if (graph == null)
            {
                throw Error.ArgumentNull("graph");
            }

            ODataWorkspace workspace = graph as ODataWorkspace;

            if (workspace == null)
            {
                throw new SerializationException(Error.Format(SRResources.CannotWriteType, GetType().Name, type.Name));
            }

            messageWriter.WriteServiceDocument(workspace);
        }
        /// <summary>
        /// Writes a service document in JSON format.
        /// </summary>
        /// <param name="defaultWorkspace">The default workspace to write in the service document.</param>
        internal void WriteServiceDocument(ODataWorkspace defaultWorkspace)
        {
            DebugUtils.CheckNoExternalCallers();
            Debug.Assert(defaultWorkspace != null, "defaultWorkspace != null");

            IEnumerable <ODataResourceCollectionInfo> collections = defaultWorkspace.Collections;

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

                // "EntitySets":
                this.JsonWriter.WriteName(JsonConstants.ODataServiceDocumentEntitySetsName);

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

                if (collections != null)
                {
                    foreach (ODataResourceCollectionInfo collectionInfo in collections)
                    {
                        // validate that the collection has a non-null url.
                        ValidationUtils.ValidateResourceCollectionInfo(collectionInfo);

                        // Note that this is an exception case; if the Base URI is missing we will still write the relative URI.
                        // We allow this because collections are specified to be the entity set names in JSON and
                        // there is no base Uri in JSON.
                        this.JsonWriter.WriteValue(UriUtilsCommon.UriToString(collectionInfo.Url));
                    }
                }

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

                // "}"
                this.JsonWriter.EndObjectScope();
            });
        }
        /// <summary>
        /// Writes a service document in JSON format.
        /// </summary>
        /// <param name="defaultWorkspace">The default workspace to write in the service document.</param>
        internal void WriteServiceDocument(ODataWorkspace defaultWorkspace)
        {
            DebugUtils.CheckNoExternalCallers();
            Debug.Assert(defaultWorkspace != null, "defaultWorkspace != null");

            IEnumerable<ODataResourceCollectionInfo> collections = defaultWorkspace.Collections;

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

                    // "EntitySets":
                    this.JsonWriter.WriteName(JsonConstants.ODataServiceDocumentEntitySetsName);

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

                    if (collections != null)
                    {
                        foreach (ODataResourceCollectionInfo collectionInfo in collections)
                        {
                            // validate that the collection has a non-null url.
                            ValidationUtils.ValidateResourceCollectionInfo(collectionInfo);

                            // Note that this is an exception case; if the Base URI is missing we will still write the relative URI.
                            // We allow this because collections are specified to be the entity set names in JSON and 
                            // there is no base Uri in JSON.
                            this.JsonWriter.WriteValue(UriUtilsCommon.UriToString(collectionInfo.Url));
                        }
                    }

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

                    // "}"
                    this.JsonWriter.EndObjectScope();
                });
        }
        /// <summary>
        /// Writes the ATOM metadata for a single workspace element.
        /// </summary>
        /// <param name="writer">The <see cref="XmlWriter"/> to write to.</param>
        /// <param name="workspace">The workspace element to get the metadata for and write it.</param>
        internal static void WriteWorkspaceMetadata(XmlWriter writer, ODataWorkspace workspace)
        {
            DebugUtils.CheckNoExternalCallers();
            Debug.Assert(writer != null, "writer != null");
            Debug.Assert(workspace != null, "workspace != null");

            AtomWorkspaceMetadata metadata = workspace.Atom();
            string title = null;

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

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

            // <atom:title>title</atom:title>
            ODataAtomWriterUtils.WriteElementWithTextContent(writer, AtomConstants.NonEmptyAtomNamespacePrefix, AtomConstants.AtomTitleElementName, AtomConstants.AtomNamespace, title);
        }
        internal void WriteWorkspaceMetadata(ODataWorkspace workspace)
        {
            AtomWorkspaceMetadata annotation    = workspace.GetAnnotation <AtomWorkspaceMetadata>();
            AtomTextConstruct     textConstruct = null;

            if (annotation != null)
            {
                textConstruct = annotation.Title;
            }
            if (textConstruct == null)
            {
                textConstruct = new AtomTextConstruct {
                    Text = "Default"
                };
            }
            if (base.UseServerFormatBehavior && (textConstruct.Kind == AtomTextConstructKind.Text))
            {
                base.WriteElementWithTextContent("atom", "title", "http://www.w3.org/2005/Atom", textConstruct.Text);
            }
            else
            {
                base.WriteTextConstruct("atom", "title", "http://www.w3.org/2005/Atom", textConstruct);
            }
        }
예제 #24
0
        /// <summary>
        /// Writes a service document with the specified <paramref name="defaultWorkspace"/> 
        /// as message payload.
        /// </summary>
        /// <param name="defaultWorkspace">The default workspace to write in the service document.</param>
        /// <returns>A func which performs the actual writing given the stream to write to.</returns>
        private Func<Stream, AsyncWriter> WriteServiceDocumentImplementation(ODataWorkspace defaultWorkspace)
        {
            this.VerifyWriterNotUsed();
            ExceptionUtils.CheckArgumentNotNull(defaultWorkspace, "defaultWorkspace");

            if (!this.writingResponse)
            {
                throw new ODataException(Strings.ODataMessageWriter_ServiceDocumentInRequest);
            }

            // Set the content type header here since all headers have to be set before getting the stream
            this.SetOrVerifyHeaders(ODataPayloadKind.ServiceDocument);

            return (stream) => this.WriteServiceDocument(stream, defaultWorkspace);
        }
예제 #25
0
        /// <summary>
        /// Write a service document with the specified <paramref name="defaultWorkspace"/>to the given stream. 
        /// This method creates an async buffered stream, writes the service document to it and returns 
        /// an <see cref="AsyncWriter"/> that can be used to flush and close/dispose the stream.
        /// </summary>
        /// <param name="stream">The stream to write to.</param>
        /// <param name="defaultWorkspace">The default workspace to write in the service document.</param>
        /// <returns>An <see cref="AsyncWriter"/> that can be used to flush and close/dispose the stream.</returns>
        private AsyncWriter WriteServiceDocument(Stream stream, ODataWorkspace defaultWorkspace)
        {
            Debug.Assert(this.writerPayloadKind != ODataPayloadKind.Unsupported, "Expected payload kind, format and encoding to be set by now.");

            return this.WriteTopLevelContent(
                stream,
                (xmlWriter) => ODataAtomWriterUtils.WriteServiceDocument(xmlWriter, this.metadataProvider, defaultWorkspace, this.settings.BaseUri),
                (jsonWriter) => ODataJsonWriterUtils.WriteServiceDocument(jsonWriter, this.metadataProvider, defaultWorkspace),
                Strings.ODataMessageWriter_InvalidContentTypeForWritingServiceDocument,
                InternalErrorCodes.ODataMessageWriter_WriteServiceDocument);
        }
예제 #26
0
 /// <summary>
 /// Writes a service document with the specified <paramref name="defaultWorkspace"/> 
 /// as message payload.
 /// </summary>
 /// <param name="defaultWorkspace">The default workspace to write in the service document.</param>
 public void WriteServiceDocument(ODataWorkspace defaultWorkspace)
 {
     this.WriteToStream(this.WriteServiceDocumentImplementation(defaultWorkspace));
 }
예제 #27
0
 /// <summary>
 /// Asynchronously writes a service document with the specified <paramref name="defaultWorkspace"/> 
 /// as message payload.
 /// </summary>
 /// <param name="defaultWorkspace">The default workspace to write in the service document.</param>
 /// <returns>A task representing the asynchronous operation of writing the service document.</returns>
 public Task WriteServiceDocumentAsync(ODataWorkspace defaultWorkspace)
 {
     return this.WriteToStreamAsync(this.WriteServiceDocumentImplementation(defaultWorkspace));
 }
예제 #28
0
        /// <summary>
        /// Writes a service document with the specified <paramref name="defaultWorkspace"/>
        /// as message payload.
        /// </summary>
        /// <param name="defaultWorkspace">The default workspace to write in the service document.</param>
        private void WriteServiceDocumentImplementation(ODataWorkspace defaultWorkspace)
        {
            ODataVerboseJsonServiceDocumentSerializer jsonServiceDocumentSerializer = new ODataVerboseJsonServiceDocumentSerializer(this);

            jsonServiceDocumentSerializer.WriteServiceDocument(defaultWorkspace);
        }
예제 #29
0
        /// <summary>
        /// Writes a service document in ATOM/XML format.
        /// </summary>
        /// <param name="writer">The <see cref="XmlWriter"/> to write to.</param>
        /// <param name="metadata">The metadata provider to use or null if no metadata is available.</param>
        /// <param name="defaultWorkspace">The default workspace to write in the service document.</param>
        /// <param name="baseUri">The base Uri specified in the writer settings for writing the service document.</param>
        internal static void WriteServiceDocument(
            XmlWriter writer,
            DataServiceMetadataProviderWrapper metadata,
            ODataWorkspace defaultWorkspace,
            Uri baseUri)
        {
            DebugUtils.CheckNoExternalCallers();
            Debug.Assert(writer != null, "writer != null");
            Debug.Assert(defaultWorkspace != null, "defaultWorkspace != null");

            if (baseUri == null)
            {
                // We require a base Uri for writing service documents in Xml format since the Uris for resource collections/entity sets
                // will be relative.
                throw new ODataException(Strings.ODataAtomWriterUtils_BaseUriRequiredForWritingServiceDocument);
            }

            IEnumerable<ODataResourceCollectionInfo> collections =
                ValidationUtils.ValidateWorkspace(metadata == null ? null : metadata.ResourceSets, defaultWorkspace);

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

            // xml:base=...
            writer.WriteAttributeString(AtomConstants.XmlBaseAttributeName, AtomConstants.XmlNamespace, baseUri.AbsoluteUri);

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

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

            // <app:workspace>
            writer.WriteStartElement(string.Empty, AtomConstants.AtomPublishingWorkspaceElementName, AtomConstants.AtomPublishingNamespace);

            ODataAtomWriterMetadataUtils.WriteWorkspaceMetadata(writer, defaultWorkspace);

            foreach (ODataResourceCollectionInfo collectionInfo in collections)
            {
                // <app:collection>
                writer.WriteStartElement(string.Empty, AtomConstants.AtomPublishingCollectionElementName, AtomConstants.AtomPublishingNamespace);

                // The name of the collection is the entity set name; The href of the <app:collection> element must be the link for the entity set.
                // Since we model the collection as having a 'Name' (for JSON) we require a base Uri for Atom/Xml.
                writer.WriteAttributeString(AtomConstants.AtomHRefAttributeName, Uri.EscapeUriString(collectionInfo.Name));

                ODataAtomWriterMetadataUtils.WriteCollectionMetadata(writer, collectionInfo);

                // </app:collection>
                writer.WriteEndElement();
            }

            // </app:workspace>
            writer.WriteEndElement();

            // </app:service>
            writer.WriteEndElement();
        }
예제 #30
0
 internal override void WriteServiceDocument(ODataWorkspace defaultWorkspace)
 {
     this.WriteServiceDocumentImplementation(defaultWorkspace);
     this.Flush();
 }
예제 #31
0
        /// <summary>
        /// Writes a service document in ATOM/XML format.
        /// </summary>
        /// <param name="writer">The <see cref="XmlWriter"/> to write to.</param>
        /// <param name="metadata">The metadata provider to use or null if no metadata is available.</param>
        /// <param name="defaultWorkspace">The default workspace to write in the service document.</param>
        /// <param name="baseUri">The base Uri specified in the writer settings for writing the service document.</param>
        internal static void WriteServiceDocument(
            XmlWriter writer,
            DataServiceMetadataProviderWrapper metadata,
            ODataWorkspace defaultWorkspace,
            Uri baseUri)
        {
            DebugUtils.CheckNoExternalCallers();
            Debug.Assert(writer != null, "writer != null");
            Debug.Assert(defaultWorkspace != null, "defaultWorkspace != null");

            if (baseUri == null)
            {
                // We require a base Uri for writing service documents in Xml format since the Uris for resource collections/entity sets
                // will be relative.
                throw new ODataException(Strings.ODataAtomWriterUtils_BaseUriRequiredForWritingServiceDocument);
            }

            IEnumerable <ODataResourceCollectionInfo> collections =
                ValidationUtils.ValidateWorkspace(metadata == null ? null : metadata.ResourceSets, defaultWorkspace);

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

            // xml:base=...
            writer.WriteAttributeString(AtomConstants.XmlBaseAttributeName, AtomConstants.XmlNamespace, baseUri.AbsoluteUri);

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

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

            // <app:workspace>
            writer.WriteStartElement(string.Empty, AtomConstants.AtomPublishingWorkspaceElementName, AtomConstants.AtomPublishingNamespace);

            ODataAtomWriterMetadataUtils.WriteWorkspaceMetadata(writer, defaultWorkspace);

            foreach (ODataResourceCollectionInfo collectionInfo in collections)
            {
                // <app:collection>
                writer.WriteStartElement(string.Empty, AtomConstants.AtomPublishingCollectionElementName, AtomConstants.AtomPublishingNamespace);

                // The name of the collection is the entity set name; The href of the <app:collection> element must be the link for the entity set.
                // Since we model the collection as having a 'Name' (for JSON) we require a base Uri for Atom/Xml.
                writer.WriteAttributeString(AtomConstants.AtomHRefAttributeName, Uri.EscapeUriString(collectionInfo.Name));

                ODataAtomWriterMetadataUtils.WriteCollectionMetadata(writer, collectionInfo);

                // </app:collection>
                writer.WriteEndElement();
            }

            // </app:workspace>
            writer.WriteEndElement();

            // </app:service>
            writer.WriteEndElement();
        }
        /// <summary>
        /// Writes a service document in ATOM/XML format.
        /// </summary>
        /// <param name="defaultWorkspace">The default workspace to write in the service document.</param>
        internal void WriteServiceDocument(ODataWorkspace defaultWorkspace)
        {
            DebugUtils.CheckNoExternalCallers();
            Debug.Assert(defaultWorkspace != null, "defaultWorkspace != null");

            IEnumerable<ODataResourceCollectionInfo> collections = defaultWorkspace.Collections;

            this.WritePayloadStart();

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

            // xml:base=...
            if (this.MessageWriterSettings.BaseUri != null)
            {
                this.XmlWriter.WriteAttributeString(AtomConstants.XmlBaseAttributeName, AtomConstants.XmlNamespace, this.MessageWriterSettings.BaseUri.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);

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

            this.atomServiceDocumentMetadataSerializer.WriteWorkspaceMetadata(defaultWorkspace);

            if (collections != null)
            {
                foreach (ODataResourceCollectionInfo collectionInfo in collections)
                {
                    // validate that the collection has a non-null url.
                    ValidationUtils.ValidateResourceCollectionInfo(collectionInfo);

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

                    // The name of the collection is the entity set name; The href of the <app:collection> element must be the link for the entity set.
                    // Since we model the collection as having a 'Name' (for JSON) we require a base Uri for Atom/Xml.
                    this.XmlWriter.WriteAttributeString(AtomConstants.AtomHRefAttributeName, this.UriToUrlAttributeValue(collectionInfo.Url));

                    this.atomServiceDocumentMetadataSerializer.WriteResourceCollectionMetadata(collectionInfo);

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

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

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

            this.WritePayloadEnd();
        }
        /// <summary>
        /// Writes a service document in JsonLight format.
        /// </summary>
        /// <param name="defaultWorkspace">The default workspace to write in the service document.</param>
        internal void WriteServiceDocument(ODataWorkspace defaultWorkspace)
        {
            DebugUtils.CheckNoExternalCallers();
            Debug.Assert(defaultWorkspace != null, "defaultWorkspace != null");

            IEnumerable <ODataResourceCollectionInfo> collections = defaultWorkspace.Collections;

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

                // "odata.metadata":...
                Uri metadataUri;
                if (this.metadataUriBuilder.TryBuildServiceDocumentMetadataUri(out metadataUri))
                {
                    this.WriteMetadataUriProperty(metadataUri);
                }

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

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

                if (collections != null)
                {
                    foreach (ODataResourceCollectionInfo collectionInfo in collections)
                    {
                        // validate that the collection has a non-null url.
                        ValidationUtils.ValidateResourceCollectionInfo(collectionInfo);

                        if (string.IsNullOrEmpty(collectionInfo.Name))
                        {
                            throw new ODataException(Strings.ODataJsonLightServiceDocumentSerializer_ResourceCollectionMustSpecifyName);
                        }

                        // "{"
                        this.JsonWriter.StartObjectScope();

                        // "name": ...
                        this.JsonWriter.WriteName(JsonLightConstants.ODataWorkspaceCollectionNameName);
                        this.JsonWriter.WriteValue(collectionInfo.Name);

                        // "url": ...
                        this.JsonWriter.WriteName(JsonLightConstants.ODataWorkspaceCollectionUrlName);
                        this.JsonWriter.WriteValue(this.UriToString(collectionInfo.Url));

                        // "}"
                        this.JsonWriter.EndObjectScope();
                    }
                }

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

                // "}"
                this.JsonWriter.EndObjectScope();
            });
        }
 /// <summary>
 /// Writes a service document with the specified <paramref name="defaultWorkspace"/> 
 /// as message payload.
 /// </summary>
 /// <param name="defaultWorkspace">The default workspace to write in the service document.</param>
 private void WriteServiceDocumentImplementation(ODataWorkspace defaultWorkspace)
 {
     ODataAtomServiceDocumentSerializer atomServiceDocumentSerializer = new ODataAtomServiceDocumentSerializer(this);
     atomServiceDocumentSerializer.WriteServiceDocument(defaultWorkspace);
 }
        /// <summary>
        /// Asynchronously writes a service document with the specified <paramref name="defaultWorkspace"/> 
        /// as message payload.
        /// </summary>
        /// <param name="defaultWorkspace">The default workspace to write in the service document.</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(ODataWorkspace defaultWorkspace)
        {
            DebugUtils.CheckNoExternalCallers();
            this.AssertAsynchronous();

            return TaskUtils.GetTaskForSynchronousOperationReturningTask(
                () =>
                {
                    this.WriteServiceDocumentImplementation(defaultWorkspace);
                    return this.FlushAsync();
                });
        }
        //// ATOM format doesn't support parameter payloads

        /// <summary>
        /// Writes a service document with the specified <paramref name="defaultWorkspace"/> 
        /// as message payload.
        /// </summary>
        /// <param name="defaultWorkspace">The default workspace to write in the service document.</param>
        /// <remarks>It is the responsibility of this method to flush the output before the method returns.</remarks>
        internal override void WriteServiceDocument(ODataWorkspace defaultWorkspace)
        {
            DebugUtils.CheckNoExternalCallers();
            this.AssertSynchronous();

            this.WriteServiceDocumentImplementation(defaultWorkspace);
            this.Flush();
        }
        /// <summary>
        /// Reads a workspace of a service document.
        /// </summary>
        /// <returns>An <see cref="ODataWorkspace"/> representing the workspace of a service document.</returns>
        /// <remarks>
        /// Pre-Condition:  Any    - the next node after the service element.
        /// Post-Condition: Any    - The next node after the workspace element.
        /// </remarks>
        private ODataWorkspace ReadWorkspace()
        {
            Debug.Assert(this.XmlReader != null, "this.XmlReader != null");

            bool enableAtomMetadataReading = this.AtomInputContext.MessageReaderSettings.EnableAtomMetadataReading;

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

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

            // if we already found an EndElement, it means that there is no workspace.
            if (this.XmlReader.NodeType == XmlNodeType.EndElement)
            {
                return(null);
            }

            this.AssertXmlCondition(XmlNodeType.Element);
            Debug.Assert(this.XmlReader.NamespaceEquals(this.AtomPublishingNamespace), "The current element should have been in the Atom publishing namespace.");

            if (!this.XmlReader.LocalNameEquals(this.AtomPublishingWorkspaceElementName))
            {
                throw new ODataException(Strings.ODataAtomServiceDocumentDeserializer_UnexpectedElementInServiceDocument(this.XmlReader.LocalName));
            }

            List <ODataResourceCollectionInfo> collections = new List <ODataResourceCollectionInfo>();
            AtomWorkspaceMetadata workspaceMetadata        = null;

            if (enableAtomMetadataReading)
            {
                workspaceMetadata = new AtomWorkspaceMetadata();
            }

            if (!this.XmlReader.IsEmptyElement)
            {
                // read over the 'workspace' element.
                this.XmlReader.ReadStartElement();

                do
                {
                    this.XmlReader.SkipInsignificantNodes();

                    switch (this.XmlReader.NodeType)
                    {
                    case XmlNodeType.Element:
                        if (this.XmlReader.NamespaceEquals(this.AtomPublishingNamespace))
                        {
                            if (this.XmlReader.LocalNameEquals(this.AtomPublishingCollectionElementName))
                            {
                                ODataResourceCollectionInfo collection = this.ReadCollectionElement();
                                Debug.Assert(collection != null, "collection != null");
                                collections.Add(collection);
                            }
                            else
                            {
                                // Throw error if we find anything other then a 'collection' element in the Atom publishing namespace.
                                throw new ODataException(Strings.ODataAtomServiceDocumentDeserializer_UnexpectedElementInWorkspace(this.XmlReader.LocalName));
                            }
                        }
                        else if (enableAtomMetadataReading && this.XmlReader.NamespaceEquals(this.AtomNamespace))
                        {
                            if (this.XmlReader.LocalNameEquals(this.AtomTitleElementName))
                            {
                                this.ServiceDocumentMetadataDeserializer.ReadTitleElementInWorkspace(workspaceMetadata);
                            }
                            else
                            {
                                this.XmlReader.Skip();
                            }
                        }
                        else
                        {
                            // skip all other elements
                            this.XmlReader.Skip();
                        }

                        break;

                    case XmlNodeType.EndElement:
                        // end of 'workspace' element.
                        break;

                    default:
                        // ignore all other nodes.
                        this.XmlReader.Skip();
                        break;
                    }
                }while (this.XmlReader.NodeType != XmlNodeType.EndElement);
            } // if (!this.XmlReader.IsEmptyElement)

            // read over the end tag of the workspace element or the start tag if the workspace element is empty.
            this.XmlReader.Read();

            ODataWorkspace workspace = new ODataWorkspace
            {
                Collections = new ReadOnlyEnumerable <ODataResourceCollectionInfo>(collections)
            };

            if (enableAtomMetadataReading)
            {
                workspace.SetAnnotation <AtomWorkspaceMetadata>(workspaceMetadata);
            }

            return(workspace);
        }
예제 #38
0
        /// <summary>
        /// Validates a service document.
        /// </summary>
        /// <param name="entitySets">The entity sets used to validate the <paramref name="workspace"/> against.</param>
        /// <param name="workspace">The workspace to validate.</param>
        /// <returns>The set of collections in the specified <paramref name="workspace"/>.</returns>
        internal static IEnumerable <ODataResourceCollectionInfo> ValidateWorkspace(IEnumerable <ResourceSetWrapper> entitySets, ODataWorkspace workspace)
        {
            DebugUtils.CheckNoExternalCallers();
            Debug.Assert(workspace != null, "workspace != null");

            IEnumerable <ODataResourceCollectionInfo>        workspaceCollections = workspace.Collections;
            Dictionary <string, ODataResourceCollectionInfo> collectionDictionary = new Dictionary <string, ODataResourceCollectionInfo>(EqualityComparer <string> .Default);

            if (workspaceCollections != null)
            {
                foreach (ODataResourceCollectionInfo collection in workspaceCollections)
                {
                    if (collection == null)
                    {
                        throw new ODataException(Strings.ODataUtils_WorkspaceCollectionsMustNotContainNullItem);
                    }

                    // validate that resource collection names are not null or empty.
                    ValidationUtils.ValidateResourceCollectionInfo(collection);

                    string collectionName = collection.Name;
                    if (collectionDictionary.ContainsKey(collectionName))
                    {
                        throw new ODataException(Strings.ODataUtils_ResourceCollectionMustHaveUniqueName(collectionName));
                    }

                    collectionDictionary.Add(collectionName, collection);
                }
            }

            // We validate that all entity sets in metadata are reflected as resource collections in the default workspace.
            if (entitySets != null)
            {
                foreach (ResourceSetWrapper entitySet in entitySets)
                {
                    ODataResourceCollectionInfo resourceCollection;
                    if (!collectionDictionary.TryGetValue(entitySet.Name, out resourceCollection))
                    {
                        // missing a resource collection for a resource set that exists in metadata
                        throw new ODataException(Strings.ODataUtils_MissingResourceCollectionForEntitySet(entitySet.Name));
                    }
                }
            }

            return(collectionDictionary.Values);
        }
예제 #39
0
        /// <summary>
        /// Extension method to get the <see cref="AtomWorkspaceMetadata"/> for an annotatable workspace.
        /// </summary>
        /// <param name="workspace">The workspace to get the annotation from.</param>
        /// <returns>An <see cref="AtomWorkspaceMetadata" /> instance or null if no annotation of that type exists.</returns>
        public static AtomWorkspaceMetadata Atom(this ODataWorkspace workspace)
        {
            ExceptionUtils.CheckArgumentNotNull(workspace, "workspace");

            return(workspace.GetAnnotation <AtomWorkspaceMetadata>());
        }
        /// <summary>
        /// Writes the ATOM metadata for a single workspace element.
        /// </summary>
        /// <param name="writer">The <see cref="XmlWriter"/> to write to.</param>
        /// <param name="workspace">The workspace element to get the metadata for and write it.</param>
        internal static void WriteWorkspaceMetadata(XmlWriter writer, ODataWorkspace workspace)
        {
            DebugUtils.CheckNoExternalCallers();
            Debug.Assert(writer != null, "writer != null");
            Debug.Assert(workspace != null, "workspace != null");

            AtomWorkspaceMetadata metadata = workspace.Atom();
            string title = null;
            if (metadata != null)
            {
                title = metadata.Title;
            }

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

            // <atom:title>title</atom:title>
            ODataAtomWriterUtils.WriteElementWithTextContent(writer, AtomConstants.NonEmptyAtomNamespacePrefix, AtomConstants.AtomTitleElementName, AtomConstants.AtomNamespace, title);
        }
        /// <summary>
        /// Writes a service document with the specified <paramref name="defaultWorkspace"/>
        /// as message payload.
        /// </summary>
        /// <param name="defaultWorkspace">The default workspace to write in the service document.</param>
        private void WriteServiceDocumentImplementation(ODataWorkspace defaultWorkspace)
        {
            ODataAtomServiceDocumentSerializer atomServiceDocumentSerializer = new ODataAtomServiceDocumentSerializer(this);

            atomServiceDocumentSerializer.WriteServiceDocument(defaultWorkspace);
        }
예제 #42
0
        /// <summary>
        /// Writes a service document in JSON format.
        /// </summary>
        /// <param name="jsonWriter">The <see cref="JsonWriter"/> to write to.</param>
        /// <param name="metadata">The metadata provider to use or null if no metadata is available.</param>
        /// <param name="defaultWorkspace">The default workspace to write in the service document.</param>
        internal static void WriteServiceDocument(
            JsonWriter jsonWriter,
            DataServiceMetadataProviderWrapper metadata,
            ODataWorkspace defaultWorkspace)
        {
            DebugUtils.CheckNoExternalCallers();
            Debug.Assert(jsonWriter != null, "jsonWriter != null");
            Debug.Assert(defaultWorkspace != null, "defaultWorkspace != null");

            IEnumerable<ODataResourceCollectionInfo> collections =
                ValidationUtils.ValidateWorkspace(metadata == null ? null : metadata.ResourceSets, defaultWorkspace);
            Debug.Assert(collections != null, "collections != null");

            WriteDataWrapper(
                jsonWriter,
                true,
                () =>
                {
                    // "{"
                    jsonWriter.StartObjectScope();

                    // "EntitySets":
                    jsonWriter.WriteName(JsonConstants.ODataServiceDocumentEntitySetsName);

                    // "["
                    jsonWriter.StartArrayScope();

                    foreach (ODataResourceCollectionInfo collectionInfo in collections)
                    {
                        ValidationUtils.ValidateResourceCollectionInfo(collectionInfo);

                        // <collection name>
                        jsonWriter.WriteValue(collectionInfo.Name);
                    }

                    // "]"
                    jsonWriter.EndArrayScope();

                    // "}"
                    jsonWriter.EndObjectScope();
                });
        }
예제 #43
0
        /// <summary>
        /// Writes a service document in ATOM/XML format.
        /// </summary>
        /// <param name="defaultWorkspace">The default workspace to write in the service document.</param>
        internal void WriteServiceDocument(ODataWorkspace defaultWorkspace)
        {
            DebugUtils.CheckNoExternalCallers();
            Debug.Assert(defaultWorkspace != null, "defaultWorkspace != null");

            IEnumerable <ODataResourceCollectionInfo> collections = defaultWorkspace.Collections;

            this.WritePayloadStart();

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

            // xml:base=...
            if (this.MessageWriterSettings.BaseUri != null)
            {
                this.XmlWriter.WriteAttributeString(AtomConstants.XmlBaseAttributeName, AtomConstants.XmlNamespace, this.MessageWriterSettings.BaseUri.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);

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

            this.atomServiceDocumentMetadataSerializer.WriteWorkspaceMetadata(defaultWorkspace);

            if (collections != null)
            {
                foreach (ODataResourceCollectionInfo collectionInfo in collections)
                {
                    // validate that the collection has a non-null url.
                    ValidationUtils.ValidateResourceCollectionInfo(collectionInfo);

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

                    // The name of the collection is the entity set name; The href of the <app:collection> element must be the link for the entity set.
                    // Since we model the collection as having a 'Name' (for JSON) we require a base Uri for Atom/Xml.
                    this.XmlWriter.WriteAttributeString(AtomConstants.AtomHRefAttributeName, this.UriToUrlAttributeValue(collectionInfo.Url));

                    this.atomServiceDocumentMetadataSerializer.WriteResourceCollectionMetadata(collectionInfo);

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

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

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

            this.WritePayloadEnd();
        }
예제 #44
0
        /// <summary>
        /// Validates a service document.
        /// </summary>
        /// <param name="entitySets">The entity sets used to validate the <paramref name="workspace"/> against.</param>
        /// <param name="workspace">The workspace to validate.</param>
        /// <returns>The set of collections in the specified <paramref name="workspace"/>.</returns>
        internal static IEnumerable<ODataResourceCollectionInfo> ValidateWorkspace(IEnumerable<ResourceSetWrapper> entitySets, ODataWorkspace workspace)
        {
            DebugUtils.CheckNoExternalCallers();
            Debug.Assert(workspace != null, "workspace != null");

            IEnumerable<ODataResourceCollectionInfo> workspaceCollections = workspace.Collections;
            Dictionary<string, ODataResourceCollectionInfo> collectionDictionary = new Dictionary<string, ODataResourceCollectionInfo>(EqualityComparer<string>.Default);
            if (workspaceCollections != null)
            {
                foreach (ODataResourceCollectionInfo collection in workspaceCollections)
                {
                    if (collection == null)
                    {
                        throw new ODataException(Strings.ODataUtils_WorkspaceCollectionsMustNotContainNullItem);
                    }

                    // validate that resource collection names are not null or empty.
                    ValidationUtils.ValidateResourceCollectionInfo(collection);

                    string collectionName = collection.Name;
                    if (collectionDictionary.ContainsKey(collectionName))
                    {
                        throw new ODataException(Strings.ODataUtils_ResourceCollectionMustHaveUniqueName(collectionName));
                    }

                    collectionDictionary.Add(collectionName, collection);
                }
            }

            // We validate that all entity sets in metadata are reflected as resource collections in the default workspace.
            if (entitySets != null)
            {
                foreach (ResourceSetWrapper entitySet in entitySets)
                {
                    ODataResourceCollectionInfo resourceCollection;
                    if (!collectionDictionary.TryGetValue(entitySet.Name, out resourceCollection))
                    {
                        // missing a resource collection for a resource set that exists in metadata
                        throw new ODataException(Strings.ODataUtils_MissingResourceCollectionForEntitySet(entitySet.Name));
                    }
                }
            }

            return collectionDictionary.Values;
        }