Пример #1
0
        /// <summary>
        /// Create a request message for a batch part from the batch writer. This method copies request headers
        /// from <paramref name="requestMessageArgs"/> in addition to the method and Uri.
        /// </summary>
        /// <param name="batchWriter">ODataBatchWriter instance to build operation message from.</param>
        /// <param name="requestMessageArgs">RequestMessageArgs for the request.</param>
        /// <param name="requestInfo">RequestInfo instance.</param>
        /// <param name="contentId">The Content-ID value to write in ChangeSet head.</param>
        /// <param name="isRelativeUri">If the request is using a relative uri.</param>
        /// <returns>an instance of ODataRequestMessageWrapper.</returns>
        internal static ODataRequestMessageWrapper CreateBatchPartRequestMessage(
            ODataBatchWriter batchWriter,
            BuildingRequestEventArgs requestMessageArgs,
            RequestInfo requestInfo,
            string contentId,
            bool isRelativeUri)
        {
            IODataRequestMessage requestMessage;

            requestMessage = batchWriter.CreateOperationRequestMessage(
                requestMessageArgs.Method,
                requestMessageArgs.RequestUri,
                contentId,
                isRelativeUri ? BatchPayloadUriOption.RelativeUri : BatchPayloadUriOption.AbsoluteUri);

            foreach (var h in requestMessageArgs.Headers)
            {
                requestMessage.SetHeader(h.Key, h.Value);
            }

            var clientRequestMessage = new InternalODataRequestMessage(requestMessage, false /*allowGetStream*/);
            ODataRequestMessageWrapper messageWrapper = new InnerBatchRequestMessageWrapper(clientRequestMessage, requestMessage, requestInfo, requestMessageArgs.Descriptor);

            return(messageWrapper);
        }
        /// <summary>
        /// Instantiates a new Serializer class and calls WriteEntry method on it.
        /// </summary>
        /// <param name="dataServiceContext"></param>
        /// <returns></returns>
        private static Person SetupSerializerAndCallWriteEntry(DataServiceContext dataServiceContext)
        {
            Person person = new Person();
            Address address = new Address();
            Car car1 = new Car();
            person.Cars.Add(car1);
            person.HomeAddress = address;

            dataServiceContext.AttachTo("Cars", car1);
            dataServiceContext.AttachTo("Addresses", address);

            var requestInfo = new RequestInfo(dataServiceContext);
            var serializer = new Serializer(requestInfo);
            var headers = new HeaderCollection();
            var clientModel = new ClientEdmModel(ODataProtocolVersion.V4);
            var entityDescriptor = new EntityDescriptor(clientModel);
            entityDescriptor.State = EntityStates.Added;
            entityDescriptor.Entity = person;
            var requestMessageArgs = new BuildingRequestEventArgs("POST", new Uri("http://www.foo.com/Northwind"), headers, entityDescriptor, HttpStack.Auto);
            var linkDescriptors = new LinkDescriptor[] { new LinkDescriptor(person, "Cars", car1, clientModel), new LinkDescriptor(person, "HomeAddress", address, clientModel) };
            var odataRequestMessageWrapper = ODataRequestMessageWrapper.CreateRequestMessageWrapper(requestMessageArgs, requestInfo);

            serializer.WriteEntry(entityDescriptor, linkDescriptors, odataRequestMessageWrapper);
            return person;
        }
        /// <summary>
        /// Returns an instance of the IODataRequestMessage
        /// </summary>
        /// <param name="requestMessageArgs">Arguments for creating the request message.</param>
        /// <returns>an instance of the IODataRequestMessage </returns>
        internal DataServiceClientRequestMessage CreateRequestMessage(BuildingRequestEventArgs requestMessageArgs)
        {
            var headersDictionary = requestMessageArgs.HeaderCollection.UnderlyingDictionary;

            // We are implementing the PostTunneling logic here. The reason for doing this is
            // 1> In this public class, the Method property returns the actual method (PUT, PATCH, DELETE),
            //    and not the verb that goes in the wire. So this class needs to know about
            //    actual verb since it will be using this verb to send over http.
            if (this.UsePostTunneling)
            {
                bool setXHttpMethodHeader = false;
                if (string.CompareOrdinal(XmlConstants.HttpMethodGet, requestMessageArgs.Method) != 0 &&
                    string.CompareOrdinal(XmlConstants.HttpMethodPost, requestMessageArgs.Method) != 0)
                {
                    setXHttpMethodHeader = true;
                }

                // Setting the actual method in the header
                if (setXHttpMethodHeader)
                {
                    headersDictionary[XmlConstants.HttpXMethod] = requestMessageArgs.Method;
                }

                // Set the Content-length of a Delete to 0. Important for post tunneling when its a post, content-length must be zero in this case.
                if (string.CompareOrdinal(XmlConstants.HttpMethodDelete, requestMessageArgs.Method) == 0)
                {
                    headersDictionary[XmlConstants.HttpContentLength] = "0";

#if DEBUG
                    if (!this.UserModifiedRequestInBuildingRequest)
                    {
                        Debug.Assert(!requestMessageArgs.HeaderCollection.HasHeader(XmlConstants.HttpContentType), "Content-Type header must not be set for DELETE requests");
                    }
#endif
                }
            }

#if !ASTORIA_LIGHT
            var clientRequestMessageArgs = new DataServiceClientRequestMessageArgs(requestMessageArgs.Method, requestMessageArgs.RequestUri, this.UseDefaultCredentials, this.UsePostTunneling, headersDictionary);
#else
            var clientRequestMessageArgs = new DataServiceClientRequestMessageArgs(requestMessageArgs.Method, requestMessageArgs.RequestUri, this.UsePostTunneling, this.UseDefaultCredentials, headersDictionary, requestMessageArgs.ClientHttpStack);
#endif

            DataServiceClientRequestMessage clientRequestMessage;
            if (this.Configurations.RequestPipeline.OnMessageCreating != null)
            {
                clientRequestMessage = this.Configurations.RequestPipeline.OnMessageCreating(clientRequestMessageArgs);
                if (clientRequestMessage == null)
                {
                    throw Error.InvalidOperation(Strings.Context_OnMessageCreatingReturningNull);
                }
            }
            else
            {
                clientRequestMessage = new HttpWebRequestMessage(clientRequestMessageArgs);
            }

            return(clientRequestMessage);
        }
Пример #4
0
        /// <summary>
        /// Create a request message for a non-batch requests and outer $batch request. This method copies request headers
        /// from <paramref name="requestMessageArgs"/> in addition to the method and Uri.
        /// </summary>
        /// <param name="requestMessageArgs">RequestMessageArgs for the request.</param>
        /// <param name="requestInfo">RequestInfo instance.</param>
        /// <returns>an instance of ODataRequestMessageWrapper.</returns>
        internal static ODataRequestMessageWrapper CreateRequestMessageWrapper(BuildingRequestEventArgs requestMessageArgs, RequestInfo requestInfo)
        {
            Debug.Assert(requestMessageArgs != null, "requestMessageArgs != null");

            var requestMessage = requestInfo.CreateRequestMessage(requestMessageArgs);

            if (null != requestInfo.Credentials)
            {
                requestMessage.Credentials = requestInfo.Credentials;
            }

#if !ASTORIA_LIGHT && !PORTABLELIB // Timeout not available
            if (0 != requestInfo.Timeout)
            {
                requestMessage.Timeout = requestInfo.Timeout;
            }
#endif

            return(new TopLevelRequestMessageWrapper(requestMessage, requestInfo, requestMessageArgs.Descriptor));
        }
Пример #5
0
        /// <summary>
        /// Create a request message for a non-batch requests and outer $batch request. This method copies request headers
        /// from <paramref name="requestMessageArgs"/> in addition to the method and Uri.
        /// </summary>
        /// <param name="requestMessageArgs">RequestMessageArgs for the request.</param>
        /// <param name="requestInfo">RequestInfo instance.</param>
        /// <returns>an instance of ODataRequestMessageWrapper.</returns>
        internal static ODataRequestMessageWrapper CreateRequestMessageWrapper(BuildingRequestEventArgs requestMessageArgs, RequestInfo requestInfo)
        {
            Debug.Assert(requestMessageArgs != null, "requestMessageArgs != null");

            var requestMessage = requestInfo.CreateRequestMessage(requestMessageArgs);

            if (requestInfo.Credentials != null)
            {
                requestMessage.Credentials = requestInfo.Credentials;
            }

            if (requestInfo.Timeout != 0)
            {
                requestMessage.Timeout = requestInfo.Timeout;
            }

            if (requestInfo.ReadWriteTimeout != 0)
            {
                requestMessage.ReadWriteTimeout = requestInfo.ReadWriteTimeout;
            }

            return(new TopLevelRequestMessageWrapper(requestMessage, requestInfo, requestMessageArgs.Descriptor));
        }
Пример #6
0
        public void PostTunnelingDeleteRequestShouldNotHaveContentTypeHeader()
        {
            bool previousPostTunnelingValue = ctx.UsePostTunneling;
            ctx.UsePostTunneling = true;
            HeaderCollection headersCollection = new HeaderCollection();
            var descriptor = new EntityDescriptor(this.clientEdmModel) { ServerTypeName = this.serverTypeName, Entity = new Customer() };
            var buildingRequestArgs = new BuildingRequestEventArgs("DELETE", new Uri("http://localhost/fakeService.svc/"), headersCollection, descriptor, HttpStack.Auto);

            ctx.Configurations.RequestPipeline.OnMessageCreating = (args) =>
            {
                buildingRequestArgs.Headers.Keys.Should().NotContain(XmlConstants.HttpContentType);
                return new HttpWebRequestMessage(args);
            };

            testSubject.CreateRequestMessage(buildingRequestArgs);

            // undoing change so this is applicable only for this test.
            ctx.UsePostTunneling = previousPostTunnelingValue;
            ctx.Configurations.RequestPipeline.OnMessageCreating = null;
        }
Пример #7
0
        public void RequestInfoShouldCreateTunneledPatchRequestMessagePostMethodAndPatchInHttpXMethodHeader()
        {
            bool previousPostTunnelingValue = ctx.UsePostTunneling;
            ctx.UsePostTunneling = true;
            HeaderCollection headersCollection = new HeaderCollection();
            var descriptor = new EntityDescriptor(this.clientEdmModel) { ServerTypeName = this.serverTypeName, Entity = new Customer() };
            var buildingRequestArgs = new BuildingRequestEventArgs("PATCH", new Uri("http://localhost/fakeService.svc/"), headersCollection, descriptor, HttpStack.Auto);

            var requestMessage = (HttpWebRequestMessage)testSubject.CreateRequestMessage(buildingRequestArgs);

            requestMessage.GetHeader(XmlConstants.HttpXMethod).Should().Be("PATCH");
            requestMessage.Method.Should().Be("PATCH");
            requestMessage.HttpWebRequest.Method.Should().Be("POST");

            // undoing change so this is applicable only for this test.
            ctx.UsePostTunneling = previousPostTunnelingValue;
        }
 /// <summary>
 /// Creates a request message with the given arguments.
 /// </summary>
 /// <param name="requestMessageArgs">The request message args.</param>
 /// <returns>Newly created request message.</returns>
 internal ODataRequestMessageWrapper CreateRequestMessage(BuildingRequestEventArgs requestMessageArgs)
 {
     return(ODataRequestMessageWrapper.CreateRequestMessageWrapper(requestMessageArgs, this.requestInfo));
 }
        public void SerializeEnity_EnumProperty()
        {
            MyEntity1 myEntity1 = new MyEntity1()
            {
                ID = 2,
                MyColorValue = MyColor.Yellow,
                MyFlagsColorValue = MyFlagsColor.Blue,
                ComplexValue1Value = new ComplexValue1() { MyColorValue = MyColor.Green, MyFlagsColorValue = MyFlagsColor.Red },
                MyFlagsColorCollection1 = new List<MyFlagsColor>() { MyFlagsColor.Blue, MyFlagsColor.Red, MyFlagsColor.Red },
                MyColorCollection = new List<MyColor?>()
            };

            DataServiceContext dataServiceContext = new DataServiceContext(new Uri("http://www.odata.org/service.svc"));
            dataServiceContext.EnableAtom = true;
            dataServiceContext.Format.UseAtom();
            dataServiceContext.AttachTo("MyEntitySet1", myEntity1);

            var requestInfo = new RequestInfo(dataServiceContext);
            var serializer = new Serializer(requestInfo);
            var headers = new HeaderCollection();
            headers.SetHeader("Content-Type", "application/atom+xml;odata.metadata=minimal");
            var clientModel = new ClientEdmModel(ODataProtocolVersion.V4);
            var entityDescriptor = new EntityDescriptor(clientModel);
            entityDescriptor.State = EntityStates.Added;
            entityDescriptor.Entity = myEntity1;
            var requestMessageArgs = new BuildingRequestEventArgs("POST", new Uri("http://www.foo.com/Northwind"), headers, entityDescriptor, HttpStack.Auto);
            var linkDescriptors = new LinkDescriptor[] { };
            var odataRequestMessageWrapper = ODataRequestMessageWrapper.CreateRequestMessageWrapper(requestMessageArgs, requestInfo);

            serializer.WriteEntry(entityDescriptor, linkDescriptors, odataRequestMessageWrapper);

            // read result:
            MemoryStream stream = (MemoryStream)(odataRequestMessageWrapper.CachedRequestStream.Stream);
            stream.Position = 0;

            string payload = (new StreamReader(stream)).ReadToEnd();
            payload = Regex.Replace(payload, "<updated>[^<]*</updated>", "");
            payload.Should().Be(
                "<?xml version=\"1.0\" encoding=\"utf-8\"?><entry xmlns=\"http://www.w3.org/2005/Atom\" " +
                    "xmlns:d=\"http://docs.oasis-open.org/odata/ns/data\" xmlns:m=\"http://docs.oasis-open.org/odata/ns/metadata\" " +
                    "xmlns:georss=\"http://www.georss.org/georss\" xmlns:gml=\"http://www.opengis.net/gml\">" +
                    "<id />" +
                    "<title />" +
                //"<updated>2013-11-11T19:29:54Z</updated>" +
                    "<author><name /></author>" +
                    "<content type=\"application/xml\">" +
                        "<m:properties>" +
                            "<d:ComplexValue1Value>" +
                                "<d:MyColorValue m:type=\"#AstoriaUnitTests.TDD.Tests.Client.ODataWriterWrapperUnitTests_MyColor\">Green</d:MyColorValue>" +
                                "<d:MyFlagsColorValue m:type=\"#AstoriaUnitTests.TDD.Tests.Client.ODataWriterWrapperUnitTests_MyFlagsColor\">Red</d:MyFlagsColorValue>" +
                                "<d:StringValue m:null=\"true\" />" +
                            "</d:ComplexValue1Value>" +
                            "<d:ID m:type=\"Int64\">2</d:ID>" +
                            "<d:MyColorCollection />" +
                            "<d:MyColorValue m:type=\"#AstoriaUnitTests.TDD.Tests.Client.ODataWriterWrapperUnitTests_MyColor\">Yellow</d:MyColorValue>" +
                            "<d:MyFlagsColorCollection1>" +
                                "<m:element m:type=\"#AstoriaUnitTests.TDD.Tests.Client.ODataWriterWrapperUnitTests+MyFlagsColor\">Blue</m:element>" +
                                "<m:element m:type=\"#AstoriaUnitTests.TDD.Tests.Client.ODataWriterWrapperUnitTests+MyFlagsColor\">Red</m:element>" +
                                "<m:element m:type=\"#AstoriaUnitTests.TDD.Tests.Client.ODataWriterWrapperUnitTests+MyFlagsColor\">Red</m:element>" +
                            "</d:MyFlagsColorCollection1>" +
                            "<d:MyFlagsColorValue m:type=\"#AstoriaUnitTests.TDD.Tests.Client.ODataWriterWrapperUnitTests_MyFlagsColor\">Blue</d:MyFlagsColorValue>" +
                        "</m:properties>" +
                    "</content>" +
                    "</entry>");
        }
        /// <summary>
        /// Create a request message for a non-batch requests and outer $batch request. This method copies request headers
        /// from <paramref name="requestMessageArgs"/> in addition to the method and Uri.
        /// </summary>
        /// <param name="requestMessageArgs">RequestMessageArgs for the request.</param>
        /// <param name="requestInfo">RequestInfo instance.</param>
        /// <returns>an instance of ODataRequestMessageWrapper.</returns>
        internal static ODataRequestMessageWrapper CreateRequestMessageWrapper(BuildingRequestEventArgs requestMessageArgs, RequestInfo requestInfo)
        {
            Debug.Assert(requestMessageArgs != null, "requestMessageArgs != null");

            var requestMessage = requestInfo.CreateRequestMessage(requestMessageArgs);

            if (null != requestInfo.Credentials)
            {
                requestMessage.Credentials = requestInfo.Credentials;
            }

#if !PORTABLELIB // Timeout not available
            if (0 != requestInfo.Timeout)
            {
                requestMessage.Timeout = requestInfo.Timeout;
            }
#endif

            return new TopLevelRequestMessageWrapper(requestMessage, requestInfo, requestMessageArgs.Descriptor);
        }
        /// <summary>
        /// Create a request message for a batch part from the batch writer. This method copies request headers
        /// from <paramref name="requestMessageArgs"/> in addition to the method and Uri.
        /// </summary>
        /// <param name="batchWriter">ODataBatchWriter instance to build operation message from.</param>
        /// <param name="requestMessageArgs">RequestMessageArgs for the request.</param>
        /// <param name="requestInfo">RequestInfo instance.</param>
        /// <param name="contentId">The Content-ID value to write in ChangeSet head.</param>
        /// <returns>an instance of ODataRequestMessageWrapper.</returns>
        internal static ODataRequestMessageWrapper CreateBatchPartRequestMessage(
            ODataBatchWriter batchWriter,
            BuildingRequestEventArgs requestMessageArgs,
            RequestInfo requestInfo,
            string contentId)
        {
            IODataRequestMessage requestMessage = batchWriter.CreateOperationRequestMessage(requestMessageArgs.Method, requestMessageArgs.RequestUri, contentId);

            foreach (var h in requestMessageArgs.Headers)
            {
                requestMessage.SetHeader(h.Key, h.Value);
            }

            var clientRequestMessage = new InternalODataRequestMessage(requestMessage, false /*allowGetStream*/);
            ODataRequestMessageWrapper messageWrapper = new InnerBatchRequestMessageWrapper(clientRequestMessage, requestMessage, requestInfo, requestMessageArgs.Descriptor);
            return messageWrapper;
        }
 /// <summary>
 /// Creates a request message with the given arguments.
 /// </summary>
 /// <param name="requestMessageArgs">The request message args.</param>
 /// <returns>Newly created request message.</returns>
 internal ODataRequestMessageWrapper CreateRequestMessage(BuildingRequestEventArgs requestMessageArgs)
 {
     return ODataRequestMessageWrapper.CreateRequestMessageWrapper(requestMessageArgs, this.requestInfo);
 }
Пример #13
0
        /// <summary>
        /// Returns an instance of the IODataRequestMessage 
        /// </summary>
        /// <param name="requestMessageArgs">Arguments for creating the request message.</param>
        /// <returns>an instance of the IODataRequestMessage </returns>
        internal DataServiceClientRequestMessage CreateRequestMessage(BuildingRequestEventArgs requestMessageArgs)
        {
            var headersDictionary = requestMessageArgs.HeaderCollection.UnderlyingDictionary;

            // We are implementing the PostTunneling logic here. The reason for doing this is
            // 1> In this public class, the Method property returns the actual method (PUT, PATCH, DELETE),
            //    and not the verb that goes in the wire. So this class needs to know about
            //    actual verb since it will be using this verb to send over http.     
            if (this.UsePostTunneling)
            {
                bool setXHttpMethodHeader = false;
                if (string.CompareOrdinal(XmlConstants.HttpMethodGet, requestMessageArgs.Method) != 0 &&
                    string.CompareOrdinal(XmlConstants.HttpMethodPost, requestMessageArgs.Method) != 0)
                {
                    setXHttpMethodHeader = true;
                }

                // Setting the actual method in the header
                if (setXHttpMethodHeader)
                {
                    headersDictionary[XmlConstants.HttpXMethod] = requestMessageArgs.Method;
                }

                // Set the Content-length of a Delete to 0. Important for post tunneling when its a post, content-length must be zero in this case.
                if (string.CompareOrdinal(XmlConstants.HttpMethodDelete, requestMessageArgs.Method) == 0)
                {
                    headersDictionary[XmlConstants.HttpContentLength] = "0";

#if DEBUG
                    if (!this.UserModifiedRequestInBuildingRequest)
                    {
                        Debug.Assert(!requestMessageArgs.HeaderCollection.HasHeader(XmlConstants.HttpContentType), "Content-Type header must not be set for DELETE requests");
                    }
#endif
                }
            }

            var clientRequestMessageArgs = new DataServiceClientRequestMessageArgs(requestMessageArgs.Method, requestMessageArgs.RequestUri, this.UseDefaultCredentials, this.UsePostTunneling, headersDictionary);
            DataServiceClientRequestMessage clientRequestMessage;
            if (this.Configurations.RequestPipeline.OnMessageCreating != null)
            {
                clientRequestMessage = this.Configurations.RequestPipeline.OnMessageCreating(clientRequestMessageArgs);
                if (clientRequestMessage == null)
                {
                    throw Error.InvalidOperation(Strings.Context_OnMessageCreatingReturningNull);
                }
            }
            else
            {
                clientRequestMessage = new HttpWebRequestMessage(clientRequestMessageArgs);
            }

            return clientRequestMessage;
        }
Пример #14
0
 public static void onBuildingRequest(object sender, Microsoft.OData.Client.BuildingRequestEventArgs e)
 {
     e.Headers.Add("Authorization", "Bearer " + Token);
 }
        public void SerializeEnity_NullableEnumProperty()
        {
            MyEntity1 myEntity1 = new MyEntity1()
            {
                ID = 2,
                MyColorValue = null,
                MyFlagsColorValue = MyFlagsColor.Blue,
                ComplexValue1Value = new ComplexValue1() { MyColorValue = MyColor.Green, MyFlagsColorValue = MyFlagsColor.Red },
                MyFlagsColorCollection1 = new List<MyFlagsColor>() { MyFlagsColor.Blue, MyFlagsColor.Red, MyFlagsColor.Red },
                MyColorCollection = new List<MyColor?> { MyColor.Green, null } 
            };

            DataServiceContext dataServiceContext = new DataServiceContext(new Uri("http://www.odata.org/service.svc"));
            dataServiceContext.EnableAtom = true;
            dataServiceContext.Format.UseAtom();
            dataServiceContext.AttachTo("MyEntitySet1", myEntity1);

            var requestInfo = new RequestInfo(dataServiceContext);
            var serializer = new Serializer(requestInfo);
            var headers = new HeaderCollection();
            var clientModel = new ClientEdmModel(ODataProtocolVersion.V4);
            var entityDescriptor = new EntityDescriptor(clientModel);
            entityDescriptor.State = EntityStates.Added;
            entityDescriptor.Entity = myEntity1;
            var requestMessageArgs = new BuildingRequestEventArgs("POST", new Uri("http://www.foo.com/Northwind"), headers, entityDescriptor, HttpStack.Auto);
            var linkDescriptors = new LinkDescriptor[] { };
            var odataRequestMessageWrapper = ODataRequestMessageWrapper.CreateRequestMessageWrapper(requestMessageArgs, requestInfo);

            serializer.WriteEntry(entityDescriptor, linkDescriptors, odataRequestMessageWrapper);

            // read result:
            MemoryStream stream = (MemoryStream)(odataRequestMessageWrapper.CachedRequestStream.Stream);
            stream.Position = 0;

            string payload = (new StreamReader(stream)).ReadToEnd();
            payload = Regex.Replace(payload, "<updated>[^<]*</updated>", "");
            payload.Should().Be(
                "{\"ComplexValue1Value\":{\"MyColorValue\":\"Green\",\"MyFlagsColorValue\":\"Red\",\"StringValue\":null},\"ID\":2,\"MyColorCollection\":[\"Green\",null],\"MyColorValue\":null,\"MyFlagsColorCollection1\":[\"Blue\",\"Red\",\"Red\"],\"MyFlagsColorValue\":\"Blue\"}");
        }
Пример #16
0
        /// <summary>
        /// Loads the metadata and converts it into an EdmModel that is then used by a dataservice context
        /// This allows the user to use the DataServiceContext directly without having to manually pass an IEdmModel in the Format
        /// </summary>
        /// <returns>A service model to be used in format tracking</returns>
        internal IEdmModel LoadServiceModelFromNetwork()
        {
            HttpWebRequestMessage    httpRequest;
            BuildingRequestEventArgs requestEventArgs = null;

            // test hook for injecting a network request to use instead of the default
            if (InjectMetadataHttpNetworkRequest != null)
            {
                httpRequest = InjectMetadataHttpNetworkRequest();
            }
            else
            {
                requestEventArgs = new BuildingRequestEventArgs(
                    "GET",
                    context.GetMetadataUri(),
                    null,
                    null,
                    context.HttpStack);

                // fire the right events if they exist to allow user to modify the request
                if (context.HasBuildingRequestEventHandlers)
                {
                    requestEventArgs = context.CreateRequestArgsAndFireBuildingRequest(
                        requestEventArgs.Method,
                        requestEventArgs.RequestUri,
                        requestEventArgs.HeaderCollection,
                        requestEventArgs.ClientHttpStack,
                        requestEventArgs.Descriptor);
                }

                DataServiceClientRequestMessageArgs args = new DataServiceClientRequestMessageArgs(
                    requestEventArgs.Method,
                    requestEventArgs.RequestUri,
                    context.UseDefaultCredentials,
                    context.UsePostTunneling,
                    requestEventArgs.Headers);

                httpRequest = new HttpWebRequestMessage(args);
            }

            Descriptor descriptor = requestEventArgs != null ? requestEventArgs.Descriptor : null;

            // fire the right events if they exist
            if (context.HasSendingRequest2EventHandlers)
            {
                SendingRequest2EventArgs eventArgs = new SendingRequest2EventArgs(
                    httpRequest,
                    descriptor,
                    false);

                context.FireSendingRequest2(eventArgs);
            }

            Task <IODataResponseMessage> asyncResponse =
                Task <IODataResponseMessage> .Factory.FromAsync(httpRequest.BeginGetResponse, httpRequest.EndGetResponse,
                                                                httpRequest);

            IODataResponseMessage response = asyncResponse.GetAwaiter().GetResult();

            ReceivingResponseEventArgs responseEvent = new ReceivingResponseEventArgs(response, descriptor);

            context.FireReceivingResponseEvent(responseEvent);

            using (StreamReader streamReader = new StreamReader(response.GetStream()))
                using (XmlReader xmlReader = XmlReader.Create(streamReader))
                {
                    return(CsdlReader.Parse(xmlReader));
                }
        }
Пример #17
0
        /// <summary>
        /// Returns the request message to write the headers and payload into.
        /// </summary>
        /// <param name="method">Http method for the request.</param>
        /// <param name="requestUri">Base Uri for the request.</param>
        /// <param name="headers">Request headers.</param>
        /// <param name="httpStack">HttpStack to use.</param>
        /// <param name="descriptor">Descriptor for the request, if there is one.</param>
        /// <param name="contentId">Content-ID header that could be used in batch request.</param>
        /// <returns>an instance of IODataRequestMessage.</returns>
        protected override ODataRequestMessageWrapper CreateRequestMessage(string method, Uri requestUri, HeaderCollection headers, HttpStack httpStack, Descriptor descriptor, string contentId)
        {
            BuildingRequestEventArgs args = this.RequestInfo.CreateRequestArgsAndFireBuildingRequest(method, requestUri, headers, this.RequestInfo.HttpStack, descriptor);

            return(ODataRequestMessageWrapper.CreateBatchPartRequestMessage(this.batchWriter, args, this.RequestInfo, contentId));
        }
        public void SerializeEnity_TwoNavigationLinksInJsonFormat()
        {
            var person = new Person
            {
                ID = 100,
                Name = "Bing",
            };

            var car1 = new Car { ID = 1001 };
            var car2 = new Car { ID = 1002 };

            DataServiceContext dataServiceContext = new DataServiceContext(new Uri("http://www.odata.org/service.svc"));
            dataServiceContext.AttachTo("Persons", person);
            dataServiceContext.AttachTo("Cars", car1);
            dataServiceContext.AttachTo("Cars", car2);
            dataServiceContext.AddLink(person, "Cars", car1);
            dataServiceContext.AddLink(person, "Cars", car2);

            var requestInfo = new RequestInfo(dataServiceContext);
            var serializer = new Serializer(requestInfo);
            var headers = new HeaderCollection();
            var clientModel = new ClientEdmModel(ODataProtocolVersion.V4);
            var entityDescriptor = new EntityDescriptor(clientModel);
            entityDescriptor.State = EntityStates.Added;
            entityDescriptor.Entity = person;
            entityDescriptor.EditLink = new Uri("http://www.foo.com/custom");
            var requestMessageArgs = new BuildingRequestEventArgs("POST", new Uri("http://www.foo.com/Northwind"), headers, entityDescriptor, HttpStack.Auto);
            var linkDescriptors = new LinkDescriptor[] { new LinkDescriptor(person, "Cars", car1, clientModel), new LinkDescriptor(person, "Cars", car2, clientModel)};
            var odataRequestMessageWrapper = ODataRequestMessageWrapper.CreateRequestMessageWrapper(requestMessageArgs, requestInfo);

            serializer.WriteEntry(entityDescriptor, linkDescriptors, odataRequestMessageWrapper);

            // read result:
            MemoryStream stream = (MemoryStream)(odataRequestMessageWrapper.CachedRequestStream.Stream);
            stream.Position = 0;

            string payload = (new StreamReader(stream)).ReadToEnd();
            payload.Should().Be(
                "{\"ID\":100,\"Name\":\"Bing\",\"[email protected]\":[\"http://www.odata.org/service.svc/Cars(1001)\",\"http://www.odata.org/service.svc/Cars(1002)\"]}");
        }