/// <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>
        /// 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);
        }
        public void RequestInfoShouldCreateTunneledPatchRequestMessagePostMethodAndPatchInHttpXMethodHeader(HttpRequestTransportMode requestTransportMode)
        {
            bool previousPostTunnelingValue = ctx.UsePostTunneling;

            ctx.UsePostTunneling         = true;
            ctx.HttpRequestTransportMode = requestTransportMode;
            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 = testSubject.CreateRequestMessage(buildingRequestArgs);

            requestMessage.GetHeader(XmlConstants.HttpXMethod).Should().Be("PATCH");
            requestMessage.Method.Should().Be("PATCH");
            if (requestTransportMode == HttpRequestTransportMode.HttpClient)
            {
                ((HttpClientRequestMessage)requestMessage).HttpRequestMessage.Method.Should().Be(HttpMethod.Post);
            }
            else
            {
                ((HttpWebRequestMessage)requestMessage).HttpWebRequest.Method.Should().Be("POST");
            }

            // undoing change so this is applicable only for this test.
            ctx.UsePostTunneling = previousPostTunnelingValue;
        }
 private void AddAssetDeleteUriParameter(object sender, BuildingRequestEventArgs e)
 {
     UriBuilder builder = new UriBuilder(e.RequestUri);
     var namevalue = "keepcontainer=" + _keepAzureStorageContainer.ToString().ToLower();
     builder.Query = String.IsNullOrEmpty(e.RequestUri.Query) ? namevalue :"&" + namevalue;
     e.RequestUri = builder.Uri;
 }
        public void HeaderShouldBeCaseInsensitive()
        {
            HeaderCollection headers = new HeaderCollection();

            headers.SetHeader("Accept", MimeType);
            headers.SetHeader("Content-Type", MimeType);

            BuildingRequestEventArgs            requestEventArgs = new BuildingRequestEventArgs("GET", new Uri("http://localhost"), headers, null, HttpStack.Auto);
            DataServiceClientRequestMessageArgs args             = new DataServiceClientRequestMessageArgs(
                requestEventArgs.Method,
                requestEventArgs.RequestUri,
                false,
                false,
                requestEventArgs.Headers);

            HttpWebRequestMessage request      = new HttpWebRequestMessage(args);
            const int             maxPageSize  = 10;
            ODataPreferenceHeader preferHeader = new ODataPreferenceHeader(request);

            preferHeader.MaxPageSize = maxPageSize;

            Assert.Equal(maxPageSize, preferHeader.MaxPageSize);
            string expected = $"{MaxPageSizePreference}={maxPageSize}";

            Assert.Equal(expected, request.GetHeader("pReFer"));
            Assert.Equal(MimeType, request.GetHeader("accepT"));
        }
Exemple #6
0
 private void Client_BuildingRequest(object sender, BuildingRequestEventArgs e)
 {
     if (e.RequestUri != null)
     {
         e.RequestUri = RewriteRequestUri((DataServiceContext)sender, options.DynamicsApiEndpoint ?? null !, e.RequestUri);
     }
 }
 /// <summary>
 /// Attach authorization, version and other context information before sending request.
 /// </summary>
 /// <param name="sender">Event source.</param>
 /// <param name="args">Request arguments.</param>
 internal void OnBuildingRequest(object sender, BuildingRequestEventArgs args)
 {
     // Add the data contract version as a query argument
     args.RequestUri = GetRequestUriWithDataContractVersion(args.RequestUri, StringConstants.GraphServiceVersion);
     // Add an Authorization header that contains an OAuth WRAP access token to the request.
     string authzHeader = String.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", authenticationToken.TokenType, " ", authenticationToken.AccessToken);
     args.Headers.Add("Authorization", authzHeader);
 }
Exemple #8
0
        private void AddAssetDeleteUriParameter(object sender, BuildingRequestEventArgs e)
        {
            UriBuilder builder   = new UriBuilder(e.RequestUri);
            var        namevalue = "keepcontainer=" + _keepAzureStorageContainer.ToString().ToLower();

            builder.Query = String.IsNullOrEmpty(e.RequestUri.Query) ? namevalue :"&" + namevalue;
            e.RequestUri  = builder.Uri;
        }
        /// <summary>
        /// Attach authorization, version and other context information before sending request.
        /// </summary>
        /// <param name="sender">Event source.</param>
        /// <param name="args">Request arguments.</param>
        internal void OnBuildingRequest(object sender, BuildingRequestEventArgs args)
        {
            // Add the data contract version as a query argument
            args.RequestUri = GetRequestUriWithDataContractVersion(args.RequestUri, StringConstants.GraphServiceVersion);
            // Add an Authorization header that contains an OAuth WRAP access token to the request.
            string authzHeader = String.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", authenticationToken.TokenType, " ", authenticationToken.AccessToken);

            args.Headers.Add("Authorization", authzHeader);
        }
        private void OdataClient_BuildingRequest(object sender, BuildingRequestEventArgs e)
        {
            // here you can see actual request
            var uri = e.RequestUri;

            Console.WriteLine("path: {0}", uri.AbsolutePath);
            Console.WriteLine("params: {0}", uri.Query);
            Debugger.Break();
        }
        /// <summary>
        /// Attach authorization, version and other context information before sending request.
        /// </summary>
        /// <param name="sender">Event source.</param>
        /// <param name="args">Request arguments.</param>
        internal void OnBuildingRequest(object sender, BuildingRequestEventArgs args)
        {
            // Add the data contract version as a query argument
            args.RequestUri = GetRequestUriWithDataContractVersion(args.RequestUri, StringConstants.GraphServiceVersion);

            // Add an Authorization header that contains an OAuth WRAP access token to the request.
            string authzHeader = _authenticationResult.CreateAuthorizationHeader();

            args.Headers.Add("Authorization", authzHeader);
        }
        private void SetCrossCompany(object sender, BuildingRequestEventArgs e)
        {
            if (this.EnableCrossCompany)
            {
                string queryPartPrefix = string.IsNullOrEmpty(e.RequestUri.Query) ? "?" : "&";

                e.RequestUri = new Uri(string.Format("{0}{1}{2}",
                                                     e.RequestUri.AbsoluteUri, queryPartPrefix, "cross-company=true"));
            }
        }
        //Trick to make OData "Add" operations work in the context of the chosen company. None of the generated OData "add" methods have these
        //context aware URLs... But then we might just as well follow the BC advice to do almost all requests in the context of a specific
        //company even though it is not technically necessary. For add operations it clearly IS !!!

        /// <summary>
        /// Extend the BaseURL dynamically to include the current company.
        /// </summary>
        /// <param name="e">OData properties for the request that is about to be built: you can change them now.</param>
        private void IncludeCompanyInUrl(BuildingRequestEventArgs e)
        {
            string url = e.RequestUri.AbsoluteUri;

            if (InCompanyContext && !url.Contains("/companies("))
            {
                string leftpart        = BaseURL.AbsoluteUri;
                string companiesclause = "/companies(" + CompanyId + ")";
                string rightpart       = url.Substring(leftpart.Length);
                url          = leftpart + companiesclause + rightpart;
                e.RequestUri = new Uri(url);
            }
        }
        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\"}");
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var current = request.RequestUri;
            ServiceFeignClientPipelineBuilder serviceFeignClientPipeline = _globalFeignClientPipeline?.GetServicePipeline(_feignClient.ServiceId);

            try
            {
                #region BuildingRequest
                BuildingRequestEventArgs buildingArgs = new BuildingRequestEventArgs(_feignClient, request.Method.ToString(), request.RequestUri, new Dictionary <string, string>());

                serviceFeignClientPipeline?.OnBuildingRequest(_feignClient, buildingArgs);
                _globalFeignClientPipeline?.OnBuildingRequest(_feignClient, buildingArgs);
                //request.Method = new HttpMethod(buildingArgs.Method);
                request.RequestUri = buildingArgs.RequestUri;
                if (buildingArgs.Headers != null && buildingArgs.Headers.Count > 0)
                {
                    foreach (var item in buildingArgs.Headers)
                    {
                        request.Headers.TryAddWithoutValidation(item.Key, item.Value);
                    }
                }
                #endregion
                request.RequestUri = LookupService(request.RequestUri);
                #region SendingRequest
                SendingRequestEventArgs sendingArgs = new SendingRequestEventArgs(_feignClient, request);
                serviceFeignClientPipeline?.OnSendingRequest(_feignClient, sendingArgs);
                _globalFeignClientPipeline?.OnSendingRequest(_feignClient, sendingArgs);
                request = sendingArgs.RequestMessage;
                #endregion

                #region CannelRequest
                CancelRequestEventArgs cancelArgs = new CancelRequestEventArgs(_feignClient, cancellationToken);
                serviceFeignClientPipeline?.OnCancelRequest(_feignClient, cancelArgs);
                _globalFeignClientPipeline?.OnCancelRequest(_feignClient, cancelArgs);
                #endregion

                return(await base.SendAsync(request, cancellationToken));
            }
            catch (Exception e)
            {
                _logger?.LogDebug(e, "Exception during SendAsync()");
                throw;
            }
            finally
            {
                request.RequestUri = current;
            }
        }
        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)\"]}");
        }
Exemple #17
0
 private void _context_BuildingRequest(object sender, BuildingRequestEventArgs e)
 {
     if (!DebuggingService.Debug)
     {
         Logger.Debug($"Request Scheme: {e.RequestUri.Scheme}");
         if (e.RequestUri.Scheme != Uri.UriSchemeHttps)
         {
             UriBuilder ub = new UriBuilder(e.RequestUri)
             {
                 Scheme = Uri.UriSchemeHttps,
                 Port   = 443
             };
             e.RequestUri = ub.Uri;
             Logger.Debug($"Updated Uri: {e.RequestUri}");
         }
     }
 }
        private string SerializeEntity <T>(string entitySetName, T entityObject)
        {
            this.context.AddObject(entitySetName, entityObject);
            var requestInfo      = new RequestInfo(this.context);
            var serializer       = new Serializer(requestInfo);
            var headers          = new HeaderCollection();
            var entityDescriptor = new EntityDescriptor(this.clientEdmModel);

            entityDescriptor.State  = EntityStates.Added;
            entityDescriptor.Entity = entityObject;
            var requestMessageArgs         = new BuildingRequestEventArgs("POST", new Uri("http://tempuri.org"), headers, entityDescriptor, HttpStack.Auto);
            var odataRequestMessageWrapper = ODataRequestMessageWrapper.CreateRequestMessageWrapper(requestMessageArgs, requestInfo);
            var linkDescriptors            = new LinkDescriptor[0];

            serializer.WriteEntry(entityDescriptor, linkDescriptors, odataRequestMessageWrapper);

            var stream       = (MemoryStream)odataRequestMessageWrapper.CachedRequestStream.Stream;
            var streamReader = new StreamReader(stream);
            var body         = streamReader.ReadToEnd();

            return(body);
        }
        public void RequestInfoShouldCreateTunneledDeleteRequestMessageDeleteMethodAndDeleteInHttpXMethodHeader()
        {
            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);

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

            requestMessage.GetHeader(XmlConstants.HttpXMethod).Should().Be("DELETE");
            requestMessage.GetHeader(XmlConstants.HttpContentLength).Should().Be("0");
            requestMessage.GetHeader(XmlConstants.HttpContentType).Should().BeNull();
            requestMessage.Method.Should().Be("DELETE");
            requestMessage.HttpWebRequest.Method.Should().Be("POST");

            // undoing change so this is applicable only for this test.
            ctx.UsePostTunneling = previousPostTunnelingValue;
        }
        /// <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));
        }
        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;
        }
 private void CoreServiceOnBuildingRequest(object sender, BuildingRequestEventArgs buildingRequestEventArgs)
 {
     var tenantId = HttpContext.Current.Request.Headers.Get(_tenantIdHeaderKey);
     buildingRequestEventArgs.Headers.Add(_tenantIdHeaderKey, tenantId);
 }
 private void CoreServiceOnBuildingRequest(object sender, BuildingRequestEventArgs buildingRequestEventArgs)
 {
     buildingRequestEventArgs.Headers.Add(TenantIdHeaderKey, TenantId);
 }
 /// <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));
 }
Exemple #25
0
 protected internal virtual void OnBuildingRequest(BuildingRequestEventArgs <TService> e)
 {
     _serviceFeignClientPipeline?.OnBuildingRequest(this, e);
     _serviceIdFeignClientPipeline?.OnBuildingRequest(this, e);
     _globalFeignClientPipeline?.OnBuildingRequest(this, e);
 }
Exemple #26
0
 private void HandleBuildingRequest(object sender, BuildingRequestEventArgs e)
 {
     logger.Info($"Building request, uri: ${e.Method} ${e.RequestUri}");
 }
Exemple #27
0
        private void CoreServiceOnBuildingRequest(object sender, BuildingRequestEventArgs buildingRequestEventArgs)
        {
            var tenantId = HttpContext.Current.Request.Headers.Get(_tenantIdHeaderKey);

            buildingRequestEventArgs.Headers.Add(_tenantIdHeaderKey, tenantId);
        }
        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>");
        }
 protected internal override void OnBuildingRequest(BuildingRequestEventArgs e)
 {
     _serviceTypeFeignClientPipeline?.OnBuildingRequest(this, e);
     base.OnBuildingRequest(e);
 }
Exemple #30
0
 private static void OnBuildingRequest(object sender, BuildingRequestEventArgs e)
 {
     e.Headers.Add("Authorization", "Bearer " + TOKEN);
 }
Exemple #31
0
 private void CoreServiceOnBuildingRequest(object sender, BuildingRequestEventArgs buildingRequestEventArgs)
 {
     buildingRequestEventArgs.Headers.Add(TenantIdHeaderKey, TenantId);
 }
Exemple #32
0
 private void RequestLogger(object eventSender, BuildingRequestEventArgs eventArgs)
 {
     eventArgs.ToString();
 }
        /// <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()
        {
            DataServiceClientRequestMessage 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 HttpClientRequestMessage(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));
                }
        }
        async Task <HttpResponseMessage> SendInternalAsync(FeignHttpRequestMessage request, CancellationToken cancellationToken)
        {
            var current = request.RequestUri;
            CancellationTokenSource cts = null;

            try
            {
                #region BuildingRequest
                BuildingRequestEventArgs <TService> buildingArgs = new BuildingRequestEventArgs <TService>(_feignClient, request.Method.ToString(), request.RequestUri, new Dictionary <string, string>(), request.FeignClientRequest);
                _feignClient.OnBuildingRequest(buildingArgs);
                //request.Method = new HttpMethod(buildingArgs.Method);
                request.RequestUri = buildingArgs.RequestUri;
                if (buildingArgs.Headers != null && buildingArgs.Headers.Count > 0)
                {
                    foreach (var item in buildingArgs.Headers)
                    {
                        request.Headers.TryAddWithoutValidation(item.Key, item.Value);
                    }
                }
                #endregion
                request.RequestUri = LookupRequestUri(request);
                #region SendingRequest
                SendingRequestEventArgs <TService> sendingArgs = new SendingRequestEventArgs <TService>(_feignClient, request, cancellationToken);
                _feignClient.OnSendingRequest(sendingArgs);

                if (sendingArgs.IsTerminated)
                {
                    //请求被终止
                    throw new TerminatedRequestException();
                }
                if (sendingArgs._cancellationTokenSource != null)
                {
                    cts = sendingArgs._cancellationTokenSource;
                    cancellationToken = cts.Token;
                }
                request = sendingArgs.RequestMessage;
                if (request == null)
                {
                    _logger?.LogError($"SendingRequest is null;");
                    return(new HttpResponseMessage(System.Net.HttpStatusCode.ExpectationFailed)
                    {
                        Content = new StringContent(""),
                        //Headers = new System.Net.Http.Headers.HttpResponseHeaders(),
                        RequestMessage = request
                    });
                }
                #endregion

                #region CannelRequest
                CancelRequestEventArgs <TService> cancelArgs = new CancelRequestEventArgs <TService>(_feignClient, request, cancellationToken);
                _feignClient.OnCancelRequest(cancelArgs);
                #endregion

                return(await base.SendAsync(request, cancelArgs.CancellationToken)
#if CONFIGUREAWAIT_FALSE
                       .ConfigureAwait(false)
#endif
                       );
            }
            catch (Exception e)
            {
                if (!e.IsSkipLog())
                {
                    _logger?.LogError(e, "Exception during SendAsync()");
                }
                if (e is HttpRequestException)
                {
                    FeignHttpRequestException feignHttpRequestException = new FeignHttpRequestException(_feignClient, request, (HttpRequestException)e);
                    ExceptionDispatchInfo     exceptionDispatchInfo     = ExceptionDispatchInfo.Capture(feignHttpRequestException);
                    exceptionDispatchInfo.Throw();
                }
                throw;
            }
            finally
            {
                request.RequestUri = current;
                if (cts != null)
                {
                    cts.Dispose();
                }
            }
        }