/// <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);
        }
        private static HttpWebRequest CreateRequest(string method, Uri requestUrl, DataServiceClientRequestMessageArgs args)
        {
            HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(requestUrl);

            // KeepAlive not available
            httpRequest.KeepAlive = true;
            httpRequest.Method    = method;
            return(httpRequest);
        }
        public CustomizedRequestMessage(DataServiceClientRequestMessageArgs args, ConnectionProperties properties)
            : base(args)
        {
            HttpWebRequest.Proxy = properties.GetWebProxy();
            HttpWebRequest.Headers.Add(properties.GetCustomHeaders());

            var cert = properties.GetClientCertificate();
            if (cert != null)
            {
                HttpWebRequest.ClientCertificates.Add(cert);
            }
        }
        /// <summary>
        /// Creates 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 CreateMessage(DataServiceClientRequestMessageArgs requestMessageArgs)
        {
            var requestMessage = this.getRequestMessage();
            requestMessage.Url = requestMessageArgs.RequestUri;
            requestMessage.Method = requestMessageArgs.Method;
            
            foreach (var header in requestMessageArgs.Headers)
            {
                requestMessage.SetHeader(header.Key, header.Value);
            }

            return new TestDataServiceClientRequestMessage(requestMessage, getResponseMessage);
        }
Пример #5
0
        private static HttpWebRequest CreateRequest(string method, Uri requestUrl, DataServiceClientRequestMessageArgs args)
        {
            HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(requestUrl);

#if PORTABLELIB
            // Set same default as Silverlight when running silverlight in .Net Portable
            if (IsRunningOnSilverlight)
            {
                httpRequest.UseDefaultCredentials = args.UseDefaultCredentials;
            }
#else
            // KeepAlive not available
            httpRequest.KeepAlive = true;
#endif
            httpRequest.Method = method;
            return(httpRequest);
        }
Пример #6
0
        /// <summary>
        /// Constructor for HttpClientRequestMessage.
        /// Initializes the <see cref="HttpClientRequestMessage"/> class.
        /// The args.ActualMethod is the actual method. In post tunneling situations method will be POST instead of the specified verb method.
        /// The args.method is the specified verb method
        /// </summary>
        /// </summary>
        public HttpClientRequestMessage(DataServiceClientRequestMessageArgs args)
            : base(args.ActualMethod)
        {
            _messageStream           = new MemoryStream();
            _handler                 = new HttpClientHandler();
            _client                  = new HttpClient(_handler, disposeHandler: true);
            _contentHeaderValueCache = new Dictionary <string, string>();
            _effectiveHttpMethod     = args.Method;
            _requestUrl              = args.RequestUri;
            _requestMessage          = new HttpRequestMessage(new HttpMethod(this.ActualMethod), _requestUrl);

            // Now set the headers.
            foreach (KeyValuePair <string, string> keyValue in args.Headers)
            {
                this.SetHeader(keyValue.Key, keyValue.Value);
            }
        }
        public HttpWebRequestMessage(DataServiceClientRequestMessageArgs args)
            : base(args.ActualMethod)
        {
            Util.CheckArgumentNull(args, "args");
            Debug.Assert(args.RequestUri.IsAbsoluteUri, "request uri is not absolute uri");
            Debug.Assert(
                args.RequestUri.Scheme.Equals("http", StringComparison.OrdinalIgnoreCase) ||
                args.RequestUri.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase),
                "request uri is not for HTTP");
            this.effectiveHttpMethod = args.Method;
            this.requestUrl          = args.RequestUri;

            this.httpRequest = HttpWebRequestMessage.CreateRequest(this.ActualMethod, this.Url, args);

            // Now set the headers.
            foreach (var keyValue in args.Headers)
            {
                this.SetHeader(keyValue.Key, keyValue.Value);
            }
        }
        public void ChangeMergeToPatch()
        {
            Func<DataServiceClientRequestMessageArgs, DataServiceClientRequestMessage> addHeader = 
                (args) =>
                {
                    if (args.Method == "MERGE")
                    {
                        var newArgs = new DataServiceClientRequestMessageArgs("PATCH", args.RequestUri, true, args.UsePostTunneling, args.Headers);

                        // PATCH verb not supported in V1 or V2
                        newArgs.Headers.Remove("DataServiceVersion");
                        newArgs.Headers.Add("DataServiceVersion", "3.0");

                        return new HttpWebRequestMessage(newArgs);
                    }

                    return new HttpWebRequestMessage(args);
                };

            var ctx = this.CreateContext(addHeader);

            Product product = null;
            var query = ctx.Context.Product.Take(1) as DataServiceQuery<Product>;
            var ar = query.BeginExecute(null, null).EnqueueWait(this);
            product = query.EndExecute(ar).Single();

            this.lastRequestMessage = null;

            product.Description = "New Description " + Guid.NewGuid().ToString();
            ctx.UpdateObject(product);

            var ar2 = ctx.BeginSaveChanges(null, null).EnqueueWait(this);
            ctx.EndSaveChanges(ar2);

            Assert.IsNotNull(this.lastRequestMessage, "No request sent");
            Assert.AreEqual("PATCH", this.lastRequestMessage.Method);
        }
Пример #9
0
        public HttpWebRequestMessage(DataServiceClientRequestMessageArgs args) 
            : base(args.ActualMethod)
        {
            Util.CheckArgumentNull(args, "args");
            Debug.Assert(args.RequestUri.IsAbsoluteUri, "request uri is not absolute uri");
            Debug.Assert(
                args.RequestUri.Scheme.Equals("http", StringComparison.OrdinalIgnoreCase) ||
                args.RequestUri.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase),
                "request uri is not for HTTP");
            this.effectiveHttpMethod = args.Method;
            this.requestUrl = args.RequestUri;

            this.httpRequest = HttpWebRequestMessage.CreateRequest(this.ActualMethod, this.Url, args);
            
            // Now set the headers.
            foreach (var keyValue in args.Headers)
            {
                this.SetHeader(keyValue.Key, keyValue.Value);
            }
        }
Пример #10
0
 public TestHttpWebRequestMessage(
     DataServiceClientRequestMessageArgs args,
     Action<HttpWebRequestMessage> sendRequest,
     Action<HttpWebResponseMessage> sendResponse,
     Func<Stream, Stream> wrapRequestStream,
     Func<Stream, Stream> wrapResponseStream) : base(args)
 {
     this.SendRequest = sendRequest;
     this.SendResponse = sendResponse;
     this.WrapRequestStream = wrapRequestStream;
     this.WrapResponseStream = wrapResponseStream;
 }
Пример #11
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));
                }
        }
            protected virtual InMemoryMessage CreateRequestMessage(DataServiceClientRequestMessageArgs requestMessageArgs)
            {
                var requestMessage = new InMemoryMessage { Url = requestMessageArgs.RequestUri, Method = requestMessageArgs.Method, Stream = new MemoryStream() };

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

                return requestMessage;
            }
 protected override InMemoryMessage CreateRequestMessage(DataServiceClientRequestMessageArgs requestMessageArgs)
 {
     this.lastMessageCreated = base.CreateRequestMessage(requestMessageArgs);
     return this.lastMessageCreated;
 }
Пример #14
0
        public void HttpMergeIsNoLongerSupported()
        {
            Func<DataServiceClientRequestMessageArgs, DataServiceClientRequestMessage> addHeader =
                (args) =>
                {
                    if (args.Method == "PATCH")
                    {
                        // use Merge
                        var newArgs = new DataServiceClientRequestMessageArgs("MERGE", args.RequestUri, true, args.UsePostTunneling, args.Headers);
                        // use V4 since Merge is removed only in V4
                        newArgs.Headers["DataServiceVersion"] = "4.0";

                        return new HttpWebRequestMessage(newArgs);
                    }
                    return new HttpWebRequestMessage(args);
                };

            var ctx = this.CreateContext(addHeader);

            Product product = null;
            var query = ctx.Context.Product.Take(1) as DataServiceQuery<Product>;
            var ar = query.BeginExecute(null, null).EnqueueWait(this);
            product = query.EndExecute(ar).Single();

            product.Description = "New Description " + Guid.NewGuid().ToString();
            ctx.UpdateObject(product);

            try
            {
                var ar2 = ctx.BeginSaveChanges(null, null).EnqueueWait(this);
                ctx.EndSaveChanges(ar2);
                Assert.Fail("Expected error not thrown");
            }
            catch (DataServiceRequestException e)
            {
#if !PORTABLELIB && !SILVERLIGHT
                StringResourceUtil.VerifyDataServicesClientString(e.Message, "DataServiceException_GeneralError");
#else
                Assert.IsNotNull(e);
#endif
            }
        }
Пример #15
0
 private TestHttpWebRequestMessage OnMessageCreating(DataServiceClientRequestMessageArgs args)
 {
     this.testMessage = new TestHttpWebRequestMessage(args, this.SendRequest, this.SendResponse, this.GetRequestWrappingStream, this.GetResponseWrappingStream);
     return this.testMessage;
 }
Пример #16
0
 public ExtendedHttpWebRequestMessage(DataServiceClientRequestMessageArgs args) : base(args)
 {
 }
Пример #17
0
        private static HttpWebRequest CreateRequest(string method, Uri requestUrl, DataServiceClientRequestMessageArgs args)
        {
            HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(requestUrl);
#if PORTABLELIB
            // Set same default as Silverlight when running silverlight in .Net Portable
            if (IsRunningOnSilverlight)
            {
                httpRequest.UseDefaultCredentials = args.UseDefaultCredentials;
            }
#else
            // KeepAlive not available
            httpRequest.KeepAlive = true;
#endif
            httpRequest.Method = method;
            return httpRequest;
        }
 public CustomizedHttpWebRequestMessage(DataServiceClientRequestMessageArgs args, string response, Dictionary<string, string> headers)
     : base(args)
 {
     this.Response = response;
     this.CutomizedHeaders = headers;
 }
 public CustomizedHttpWebRequestMessage(DataServiceClientRequestMessageArgs args)
     : base(args)
 {
 }
Пример #20
0
        public void QueryWithFormat()
        {
            Dictionary<string, string> testCases = new Dictionary<string, string>()
            {
                {"People?$format=application/json", "application/json"},
                // ODL Bug: https://github.com/OData/odata.net/issues/313
                ////{"People?$format=application/json;odata.metadata=full", "application/json; odata.metadata=full"},
                {"People?$format=json", "application/json"},
            };

            ODataMessageReaderSettings readerSettings = new ODataMessageReaderSettings() { BaseUri = ServiceBaseUri };
            foreach (var testCase in testCases)
            {
                DataServiceClientRequestMessageArgs args = new DataServiceClientRequestMessageArgs(
                    "GET",
                    new Uri(ServiceBaseUri.AbsoluteUri + testCase.Key, UriKind.Absolute),
                    false, false, new Dictionary<string, string>() { });

                var requestMessage = new HttpWebRequestMessage(args);
                using (var responseMessage = requestMessage.GetResponse() as HttpWebResponseMessage)
                {
                    Assert.Equal(200, responseMessage.StatusCode);

                    string contentType = responseMessage.Headers.FirstOrDefault(x => x.Key.Equals("Content-Type")).Value;
                    Assert.True(contentType.StartsWith(testCase.Value));

                    using (var messageReader = new ODataMessageReader(
                        responseMessage,
                        readerSettings,
                        this.TestClientContext.Format.LoadServiceModel()))
                    {
                        var reader = messageReader.CreateODataFeedReader();

                        while (reader.Read())
                        {
                            if (reader.State == ODataReaderState.EntryEnd)
                            {
                                ODataEntry entry = reader.Item as ODataEntry;
                                Assert.NotNull(entry.Properties.Single(p => p.Name == "PersonId").Value);
                            }
                            else if (reader.State == ODataReaderState.FeedEnd)
                            {
                                Assert.NotNull(reader.Item as ODataFeed);
                            }
                        }

                        Assert.Equal(ODataReaderState.Completed, reader.State);
                    }
                }
            }
        }
 internal TestHttpRequestMessage(DataServiceClientRequestMessageArgs args, Func<Stream, Stream> requestStreamInterceptor, Func<Stream, Stream> responseStreamInterceptor) : base(args)
 {
     this.requestStreamInterceptor = requestStreamInterceptor;
     this.responseStreamInterceptor = responseStreamInterceptor;
 }
Пример #22
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;
        }
 /// <summary>
 /// Creates a new instance of HttpWebRequestMessage.
 /// </summary>
 /// <param name="args">Arguments for creating the request message.</param>
 /// <param name="requestInfo">RequestInfo instance.</param>
 internal HttpWebRequestMessage(DataServiceClientRequestMessageArgs args, RequestInfo requestInfo)
     : this(args)
 {
     Debug.Assert(requestInfo != null, "requestInfo != null");
     this.requestInfo = requestInfo;
 }
Пример #24
0
 public AnnotationRequestMessage(DataServiceClientRequestMessageArgs args)
     : base(args)
 {
 }