Exemplo n.º 1
0
        bool PrepareReply(ref Message message)
        {
            bool closeOnReceivedEof = false;

            // null means we're done
            if (message == null)
            {
                // A null message means either a one-way request or that the service operation returned null and
                // hence we can close the HttpOutput. By default we keep the HttpOutput open to allow the writing to the output
                // even after the HttpInput EOF is received and the HttpOutput will be closed only on close of the HttpRequestContext.
                closeOnReceivedEof = true;
                message            = CreateAckMessage(HttpStatusCode.Accepted, string.Empty);
            }

            if (!listener.ManualAddressing)
            {
                if (message.Version.Addressing == AddressingVersion.WSAddressingAugust2004)
                {
                    if (message.Headers.To == null ||
                        listener.AnonymousUriPrefixMatcher == null ||
                        !listener.AnonymousUriPrefixMatcher.IsAnonymousUri(message.Headers.To))
                    {
                        message.Headers.To = message.Version.Addressing.AnonymousUri;
                    }
                }
                else if (message.Version.Addressing == AddressingVersion.WSAddressing10 ||
                         message.Version.Addressing == AddressingVersion.None)
                {
                    if (message.Headers.To != null &&
                        (listener.AnonymousUriPrefixMatcher == null ||
                         !listener.AnonymousUriPrefixMatcher.IsAnonymousUri(message.Headers.To)))
                    {
                        message.Headers.To = null;
                    }
                }
                else
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                              new ProtocolException(SR.GetString(SR.AddressingVersionNotSupported, message.Version.Addressing)));
                }
            }

            message.Properties.AllowOutputBatching = false;
            this.httpOutput = GetHttpOutputCore(message);

            // Reuse the HttpInput we got previously.
            HttpInput input = this.httpPipeline.HttpInput;

            if (input != null)
            {
                HttpDelayedAcceptStream requestStream = input.GetInputStream(false) as HttpDelayedAcceptStream;
                if (requestStream != null && TransferModeHelper.IsRequestStreamed(listener.TransferMode) &&
                    requestStream.EnableDelayedAccept(this.httpOutput, closeOnReceivedEof))
                {
                    return(false);
                }
            }

            return(true);
        }
Exemplo n.º 2
0
        private bool PrepareReply(ref Message message)
        {
            if (message == null)
            {
                message = this.CreateAckMessage(HttpStatusCode.Accepted, string.Empty);
            }
            if (!this.listener.ManualAddressing)
            {
                if (message.Version.Addressing != AddressingVersion.WSAddressingAugust2004)
                {
                    if ((message.Version.Addressing != AddressingVersion.WSAddressing10) && (message.Version.Addressing != AddressingVersion.None))
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ProtocolException(System.ServiceModel.SR.GetString("AddressingVersionNotSupported", new object[] { message.Version.Addressing })));
                    }
                    if ((message.Headers.To != null) && ((this.listener.AnonymousUriPrefixMatcher == null) || !this.listener.AnonymousUriPrefixMatcher.IsAnonymousUri(message.Headers.To)))
                    {
                        message.Headers.To = null;
                    }
                }
                else if (((message.Headers.To == null) || (this.listener.AnonymousUriPrefixMatcher == null)) || !this.listener.AnonymousUriPrefixMatcher.IsAnonymousUri(message.Headers.To))
                {
                    message.Headers.To = message.Version.Addressing.AnonymousUri;
                }
            }
            message.Properties.AllowOutputBatching = false;
            this.httpOutput = this.GetHttpOutput(message);
            HttpDelayedAcceptStream inputStream = this.HttpInput.InputStream as HttpDelayedAcceptStream;

            if (((inputStream != null) && TransferModeHelper.IsRequestStreamed(this.listener.TransferMode)) && inputStream.EnableDelayedAccept(this.httpOutput))
            {
                return(false);
            }
            return(true);
        }
Exemplo n.º 3
0
        public async Task UsesCustomJsonSerializerSettings()
        {
            var config = new HttpOutputConfiguration();

            config.ServiceUri = "http://*****:*****@"
                [
                    {
                        ""Timestamp"":""2018-01-02T14:12:00+00:00"",
                        ""ProviderName"":""HttpOutputTests"",
                        ""Level"":3,
                        ""Keywords"":0,
                        ""Payload"":{""InfinityProperty"":""Infinity""}
                    }
                ]".RemoveAllWhitespace();

            await output.SendEventsAsync(new EventData[] { e }, 78, CancellationToken.None);

            httpClientMock.Verify(client => client.PostAsync(
                                      new Uri("http://*****:*****@"
                [
                    {
                        ""Timestamp"":""2018-01-02T14:12:00+00:00"",
                        ""ProviderName"":""HttpOutputTests"",
                        ""Level"":3,
                        ""Keywords"":0,
                        ""Payload"":{""InfinityProperty"":0.0}
                    }
                ]".RemoveAllWhitespace();

            await output.SendEventsAsync(new EventData[] { e }, 79, CancellationToken.None);

            httpClientMock.Verify(client => client.PostAsync(
                                      new Uri("http://logcollector:1234"),
                                      It.Is <HttpContent>(content => content.ReadAsStringAsync().GetAwaiter().GetResult() == expectedContent)
                                      ), Times.Once());
        }
Exemplo n.º 4
0
        public async Task ProducesJsonLinesIfRequested()
        {
            var config = new HttpOutputConfiguration();

            config.ServiceUri = "http://*****:*****@"
                {
                    ""Timestamp"":""2018-01-02T14:12:00+00:00"",
                    ""ProviderName"":""HttpOutputTests"",
                    ""Level"":4,
                    ""Keywords"":0,
                    ""Payload"":{""Message"":""Hey!""}
                }
                {
                    ""Timestamp"":""2018-01-02T14:14:20+00:00"",
                    ""ProviderName"":""HttpOutputTests"",
                    ""Level"":3,
                    ""Keywords"":0,
                    ""Payload"":{""Message"":""Hey!""}
                }";

            expectedContent = RemoveWhitespace(expectedContent);

            await output.SendEventsAsync(events, 78, CancellationToken.None);

            httpClientMock.Verify(client => client.PostAsync(
                                      new Uri("http://logcollector:1234"),
                                      It.Is <HttpContent>(content => RemoveWhitespace(content.ReadAsStringAsync().GetAwaiter().GetResult()) == expectedContent)
                                      ), Times.Once());
        }
Exemplo n.º 5
0
 public bool EnableDelayedAccept(HttpOutput output)
 {
     if (base.IsAtEof)
     {
         return(false);
     }
     this.httpOutput = output;
     return(true);
 }
            protected virtual void SendReplyCore(Message message, TimeSpan timeout)
            {
                this.TraceProcessResponseStart();
                ThreadTrace.Trace("Begin sending http reply");
                HttpOutput httpOutput = this.GetHttpOutput(message);

                httpOutput.Send(timeout);
                ThreadTrace.Trace("End sending http reply");
                this.TraceProcessResponseStop();
            }
Exemplo n.º 7
0
 protected override HttpOutput GetHttpOutput(Message message)
 {
     if ((this.listenerContext.Request.ContentLength64 == -1L) && !OSEnvironmentHelper.IsVistaOrGreater)
     {
         this.listenerContext.Response.KeepAlive = false;
     }
     else
     {
         this.listenerContext.Response.KeepAlive = base.listener.KeepAliveEnabled;
     }
     return(HttpOutput.CreateHttpOutput(this.listenerContext.Response, base.Listener, message, this.HttpMethod));
 }
Exemplo n.º 8
0
        //通过搜索企业的验证吗
        private bool SimulateLoginEx()
        {
            Console.WriteLine("开始处理当前搜索企业验证码");
            HttpOutput ho   = HttpManager.Instance.ProcessRequest(hi);
            Random     rand = new Random(Environment.TickCount);

            hi.Url = string.Format("http://www.qixin.com/service/gtregister?t=={0}&_={1}", GetTimeLikeJS(), GetTimeLikeJS());
            var postFormat = "geetest_challenge={0}&geetest_validate={1}&geetest_seccode={1}|%7Cjordan&requestType=search_enterprise";
            var validUrl   = "http://www.qixin.com/service/gtvalidate";
            var passResult = geetestHelper.PassGeetest(hi, postFormat, validUrl);

            return(passResult.Status);
        }
Exemplo n.º 9
0
        private bool PrepareReply(ref Message message)
        {
            bool closeOnReceivedEof = false;

            // null means we're done
            if (message == null)
            {
                // A null message means either a one-way request or that the service operation returned null and
                // hence we can close the HttpOutput. By default we keep the HttpOutput open to allow the writing to the output
                // even after the HttpInput EOF is received and the HttpOutput will be closed only on close of the HttpRequestContext.
                closeOnReceivedEof = true;
                message            = CreateAckMessage(HttpStatusCode.Accepted, string.Empty);
            }

            if (!HttpTransportSettings.ManualAddressing)
            {
                if (message.Version.Addressing == AddressingVersion.WSAddressingAugust2004)
                {
                    if (message.Headers.To == null ||
                        (HttpTransportSettings.AnonymousUriPrefixMatcher as HttpAnonymousUriPrefixMatcher) == null ||
                        !(HttpTransportSettings.AnonymousUriPrefixMatcher as HttpAnonymousUriPrefixMatcher).IsAnonymousUri(message.Headers.To))
                    {
                        message.Headers.To = message.Version.Addressing.AnonymousUri;
                    }
                }
                else if (message.Version.Addressing == AddressingVersion.WSAddressing10 ||
                         message.Version.Addressing == AddressingVersion.None)
                {
                    if (message.Headers.To != null &&
                        (HttpTransportSettings.AnonymousUriPrefixMatcher as HttpAnonymousUriPrefixMatcher == null ||
                         !(HttpTransportSettings.AnonymousUriPrefixMatcher as HttpAnonymousUriPrefixMatcher).IsAnonymousUri(message.Headers.To)))
                    {
                        message.Headers.To = null;
                    }
                }
                else
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                              new ProtocolException(SR.Format(SR.AddressingVersionNotSupported, message.Version.Addressing)));
                }
            }

            message.Properties.AllowOutputBatching = false;
            _httpOutput = GetHttpOutputCore(message);

            return(closeOnReceivedEof);
        }
Exemplo n.º 10
0
                public async Task SendRequestAsync(Message message, TimeoutHelper timeoutHelper)
                {
                    _timeoutHelper = timeoutHelper;
                    _factory.ApplyManualAddressing(ref _to, ref _via, message);
                    _httpRequestMessage = await _channel.GetHttpRequestMessageAsync(_to, _via, _timeoutHelper.CancellationToken);

                    Message request = message;

                    try
                    {
                        if (_channel.State != CommunicationState.Opened)
                        {
                            // if we were aborted while getting our request or doing correlation,
                            // we need to abort the web request and bail
                            Cleanup();
                            _channel.ThrowIfDisposedOrNotOpen();
                        }

                        HttpOutput httpOutput = HttpOutput.CreateHttpOutput(_httpRequestMessage, _factory, request, _factory.IsChannelBindingSupportEnabled, _factory.GetHttpClient(), _factory._authenticationScheme, _timeoutHelper);

                        bool success = false;
                        try
                        {
                            _httpResponseMessageTask = await httpOutput.SendAsync(_httpRequestMessage);

                            //this.channelBinding = httpOutput.TakeChannelBinding();
                            await httpOutput.CloseAsync();

                            success = true;
                        }
                        finally
                        {
                            if (!success)
                            {
                                httpOutput.Abort(HttpAbortReason.Aborted);
                            }
                        }
                    }
                    finally
                    {
                        if (!object.ReferenceEquals(request, message))
                        {
                            request.Close();
                        }
                    }
                }
Exemplo n.º 11
0
            public override HttpOutput GetHttpOutput(Message message)
            {
                // TODO: Enable KeepAlive setting
                //if (!_httpBindingElement.KeepAlive)
                //{
                //    aspNetContext.Response.Headers["Connection"] = "close";
                //}

                ICompressedMessageEncoder compressedMessageEncoder = HttpTransportSettings.MessageEncoderFactory.Encoder as ICompressedMessageEncoder;

                if (compressedMessageEncoder != null && compressedMessageEncoder.CompressionEnabled)
                {
                    string acceptEncoding = _aspNetContext.Request.Headers[HttpChannelUtilities.AcceptEncodingHeader];
                    compressedMessageEncoder.AddCompressedMessageProperties(message, acceptEncoding);
                }

                return(HttpOutput.CreateHttpOutput(_aspNetContext, HttpTransportSettings, message, HttpMethod));
            }
Exemplo n.º 12
0
            public override HttpOutput GetHttpOutput(Message message)
            {
                if (HttpTransportSettings.KeepAliveEnabled)
                {
                    _aspNetContext.Response.Headers["Connection"] = "keep-alive";
                }
                else
                {
                    _aspNetContext.Response.Headers["Connection"] = "close";
                }

                if (HttpTransportSettings.MessageEncoderFactory.Encoder is ICompressedMessageEncoder compressedMessageEncoder && compressedMessageEncoder.CompressionEnabled)
                {
                    string acceptEncoding = _aspNetContext.Request.Headers[HttpChannelUtilities.AcceptEncodingHeader];
                    compressedMessageEncoder.AddCompressedMessageProperties(message, acceptEncoding);
                }

                return(HttpOutput.CreateHttpOutput(_aspNetContext, HttpTransportSettings, message, HttpMethod));
            }
Exemplo n.º 13
0
        public async Task ProducesJsonByDefault()
        {
            var config = new HttpOutputConfiguration();

            config.ServiceUri = "http://*****:*****@"
                [
                    {
                        ""Timestamp"":""2018-01-02T14:12:00+00:00"",
                        ""ProviderName"":""HttpOutputTests"",
                        ""Level"":4,
                        ""Keywords"":0,
                        ""Payload"":{""Message"":""Hey!""}
                    },
                    {
                        ""Timestamp"":""2018-01-02T14:14:20+00:00"",
                        ""ProviderName"":""HttpOutputTests"",
                        ""Level"":3,
                        ""Keywords"":0,
                        ""Payload"":{""Message"":""Hey!""}
                    }]";

            expectedContent = RemoveWhitespace(expectedContent);

            await output.SendEventsAsync(events, 78, CancellationToken.None);

            httpClientMock.Verify(client => client.PostAsync(
                                      new Uri("http://logcollector:1234"),
                                      It.Is <HttpContent>(content => content.ReadAsStringAsync().GetAwaiter().GetResult() == expectedContent)
                                      ), Times.Once());
        }
            protected override void SendReplyCore(Message message, TimeSpan timeout)
            {
                this.TraceProcessResponseStart();
                ThreadTrace.Trace("Begin sending http reply");
                HttpOutput httpOutput = this.GetHttpOutput(message);

                HttpResponseMessage response = HttpResponseMessageProperty.GetHttpResponseMessageFromMessage(message);

                if (response != null)
                {
                    httpOutput.Send(response, timeout);
                }
                else
                {
                    httpOutput.Send(timeout);
                }

                ThreadTrace.Trace("End sending http reply");
                this.TraceProcessResponseStop();
            }
Exemplo n.º 15
0
            public override HttpOutput GetHttpOutput(Message message)
            {
                // work around http.sys keep alive bug with chunked requests, see MB 49676, this is fixed in Vista
                if (listenerContext.Request.ContentLength64 == -1 && !OSEnvironmentHelper.IsVistaOrGreater)
                {
                    listenerContext.Response.KeepAlive = false;
                }
                else
                {
                    listenerContext.Response.KeepAlive = listener.KeepAliveEnabled;
                }
                ICompressedMessageEncoder compressedMessageEncoder = listener.MessageEncoderFactory.Encoder as ICompressedMessageEncoder;

                if (compressedMessageEncoder != null && compressedMessageEncoder.CompressionEnabled)
                {
                    string acceptEncoding = listenerContext.Request.Headers[HttpChannelUtilities.AcceptEncodingHeader];
                    compressedMessageEncoder.AddCompressedMessageProperties(message, acceptEncoding);
                }

                return(HttpOutput.CreateHttpOutput(listenerContext.Response, Listener, message, this.HttpMethod));
            }
Exemplo n.º 16
0
        public async Task MethodInfoIsSerializedAsFullyQualifiedName()
        {
            var config = new HttpOutputConfiguration();

            config.ServiceUri = "http://*****:*****@"
                [
                    {
                        ""Timestamp"":""2018-01-02T14:12:00+00:00"",
                        ""ProviderName"":""HttpOutputTests"",
                        ""Level"":3,
                        ""Keywords"":0,
                        ""Payload"":{""Method"":""Microsoft.Diagnostics.EventFlow.Outputs.Tests.HttpOutputTests.MethodInfoIsSerializedAsFullyQualifiedName""}
                    }
                ]".RemoveAllWhitespace();

            await output.SendEventsAsync(new EventData[] { e }, 78, CancellationToken.None);

            httpClientMock.Verify(client => client.PostAsync(
                                      new Uri("http://logcollector:1234"),
                                      It.Is <HttpContent>(content => content.ReadAsStringAsync().GetAwaiter().GetResult() == expectedContent)
                                      ), Times.Once());
        }
Exemplo n.º 17
0
        internal void SendResponseAndClose(HttpResponseMessage httpResponseMessage)
        {
            if (this.TryInitiateReply())
            {
                // Send the response message.
                try
                {
                    if (this.httpOutput == null)
                    {
                        this.httpOutput = this.GetHttpOutputCore(new NullMessage());
                    }
                    this.httpOutput.Send(httpResponseMessage, this.DefaultSendTimeout);
                }
                catch (Exception ex)
                {
                    if (Fx.IsFatal(ex))
                    {
                        throw;
                    }

                    DiagnosticUtility.TraceHandledException(ex, TraceEventType.Information);
                }
            }

            // Close the request context.
            try
            {
                this.Close(); // this also closes the HttpOutput
            }
            catch (Exception ex)
            {
                if (Fx.IsFatal(ex))
                {
                    throw;
                }

                DiagnosticUtility.TraceHandledException(ex, TraceEventType.Information);
            }
        }
            void CompleteChannelModelIntegrationHandlerTask(Message replyMessage)
            {
                if (this.channelModelIntegrationHandlerTask != null)
                {
                    // If Service Model (or service instance) sent us null then we create a 202 HTTP response
                    HttpResponseMessage httpResponseMessage = null;
                    this.httpOutput = this.GetHttpOutput(replyMessage);

                    if (replyMessage != null)
                    {
                        httpResponseMessage = this.CreateHttpResponseMessage(replyMessage);
                    }
                    else
                    {
                        httpResponseMessage = new HttpResponseMessage(HttpStatusCode.Accepted);
                    }

                    Fx.Assert(httpResponseMessage != null, "httpResponse should not be null.");
                    if (httpResponseMessage.RequestMessage == null)
                    {
                        httpResponseMessage.RequestMessage = this.httpRequestMessage;
                        Fx.Assert(httpResponseMessage.RequestMessage != null, "httpResponseMessage.RequestMessage should never be null.");

                        if (replyMessage != null)
                        {
                            httpResponseMessage.CopyPropertiesFromMessage(replyMessage);
                        }
                    }

                    HttpChannelUtilities.EnsureHttpResponseMessageContentNotNull(httpResponseMessage);

                    this.cancellationTokenSource.CancelAfter(TimeoutHelper.ToMilliseconds(this.defaultSendTimeout));
                    this.channelModelIntegrationHandlerTask.TrySetResult(httpResponseMessage);
                }

                this.TraceProcessResponseStop();
            }
Exemplo n.º 19
0
        protected override async Task OnReplyAsync(Message message, CancellationToken token)
        {
            Message responseMessage = message;

            try
            {
                bool closeOutputAfterReply = PrepareReply(ref responseMessage);
                httpOutput = this.GetHttpOutput(message);
                await httpOutput.SendAsync(token);

                if (closeOutputAfterReply)
                {
                    await httpOutput.CloseAsync();
                }
            }
            finally
            {
                if (message != null &&
                    !object.ReferenceEquals(message, responseMessage))
                {
                    responseMessage.Close();
                }
            }
        }
Exemplo n.º 20
0
        private bool SimulateLoginEx_ablort()
        {
            //HttpInput hi = new HttpInput();
            //HttpManager.Instance.InitWebClient(hi, true, 30, 30);
            //Random rand = new Random(Environment.TickCount);

            // 首先调用登录API
            //1:登录打码平台 ,这是我的API接口地址,^_^
            hi.Url = "http://120.27.110.11:9600/login_biz/login.oko?uid=01161add5a3c4c55bd9c133baa9effd0";
            // 请求访问
            //hi.EnableProxy = true;
            //hi.ProxyIP = "127.0.0.1";
            //hi.ProxyPort = 8888;
            HttpOutput ho = HttpManager.Instance.ProcessRequest(hi);

            if (ho.IsOK)
            {
                // 获得了过码接口地址
                string vcode_url = ho.TxtData;

_rt1:
                // 请求验证码
                //hi.Url = "http://www.qixin.com/service/gtregister?t=14664817340727&_=1466481710608";
                hi.Url = string.Format("http://www.qixin.com/service/gtregister?t=={0}&_={1}", GetTimeLikeJS(), GetTimeLikeJS());
                //hi.Cookies = Settings.SimulateCookies;
                ho = HttpManager.Instance.ProcessRequest(hi);
                if (ho.IsOK)
                {
                    //{"success":1,"gt":"68bb53762881989c3ca8e86c4621dcdb","challenge":"94490fd25aedbc2b83a843a89e2c15ad"}

                    hi.Url      = vcode_url;
                    hi.PostData = "data=" + Toolslib.Str.Sub(ho.TxtData, "gt\":\"", "\"") + "|" + Toolslib.Str.Sub(ho.TxtData, "challenge\":\"", "\"");

                    Console.WriteLine("给过码接口的POST数据为:" + hi.PostData);
                    ho = HttpManager.Instance.ProcessRequest(hi);
                    string kkk = ho.TxtData;
                    if (kkk.StartsWith("success:"))
                    {
                        string[] lastvcode = kkk.Replace("success:", string.Empty).Split(new char[] { '|' });
                        //{"success":1,","momo_pic_verify_token":"44fb42329028fd1c40b66ec0a8e08375","ec":200,"em":"ok"}
                        // 登录
                        // hi.Cookies = Settings.SimulateCookies;
                        // hi.Url = "http://www.qixin.com/service/gt-validate-for-chart";
                        hi.Url = "http://www.qixin.com/service/gtvalidate";

                        // hi.Refer = "http://www.qixin.com/company/network/db4bef40-08b3-4b00-8501-fdd6e854fb84?name=%E5%8E%A6%E9%97%A8%E5%B8%82%E8%87%B3%E5%B0%9A%E4%BC%98%E5%93%81%E4%BC%A0%E5%AA%92%E6%9C%89%E9%99%90%E5%85%AC%E5%8F%B8";
                        hi.Refer    = "http://www.qixin.com/search?key=%E5%8E%A6%E9%97%A8%E5%AF%8C%E5%85%B0%E5%85%8B%E6%9E%97&type=enterprise&source=&isGlobal=Y";
                        hi.PostData = "geetest_challenge=" + lastvcode[1] + "&geetest_validate=" + lastvcode[0]
                                      + "&geetest_seccode=" + lastvcode[0] + "%7Cjordan&requestType=search_enterprise";

                        ho = HttpManager.Instance.ProcessRequest(hi);
                        if (ho.IsOK && ho.TxtData.Contains("succ"))
                        {
                            return(true);
                        }
                    }
                    else
                    {
                        Console.WriteLine("重试");
                        goto _rt1;
                    }
                }
                else
                {
                    Console.WriteLine("重试");
                    goto _rt1;
                }
            }
            return(false);
        }