예제 #1
0
        public override Task Install(RestClient rc)
        {
            var extensibleRequest = rc.extensibleRequest;

            rc.extensibleRequest = async(httpRequestMessage, restRequestConfig) =>
            {
                if (!enabled)
                {
                    return(await extensibleRequest(httpRequestMessage, restRequestConfig));
                }

                BeforeRequest?.Invoke(this, httpRequestMessage);
                try
                {
                    var httpResponseMessage = await extensibleRequest(httpRequestMessage, restRequestConfig);

                    RequestSuccess?.Invoke(this, new HttpMessages
                    {
                        httpResponseMessage = httpResponseMessage,
                        httpRequestMessage  = httpRequestMessage
                    });
                    return(httpResponseMessage);
                }
                catch (RestException re)
                {
                    RequestError?.Invoke(this, re);
                    throw;
                }
            };
            return(Task.CompletedTask);
        }
예제 #2
0
        async Task <string> IRCallbacks.ReadConsole(IReadOnlyList <IRContext> contexts, string prompt, int len, bool addToHistory, CancellationToken ct)
        {
            await TaskUtilities.SwitchToBackgroundThread();

            if (!_initializedTcs.Task.IsCompleted)
            {
                await AfterHostStarted(_startupInfo);
            }

            var callback = _callback;

            if (!addToHistory && callback != null)
            {
                return(await callback.ReadUserInput(prompt, len, ct));
            }

            var currentRequest = Interlocked.Exchange(ref _currentRequestSource, null);

            _contexts = contexts;
            Prompt    = GetDefaultPrompt(prompt);
            MaxLength = len;

            var requestEventArgs = new RBeforeRequestEventArgs(contexts, Prompt, len, addToHistory);

            BeforeRequest?.Invoke(this, requestEventArgs);

            OnMutated();

            currentRequest?.CompleteResponse();

            string consoleInput = null;

            do
            {
                ct.ThrowIfCancellationRequested();
                try {
                    consoleInput = await ReadNextRequest(Prompt, len, ct);
                } catch (OperationCanceledException ex) when(!(ex is CancelAllException))
                {
                    // If request was canceled through means other than our token, it indicates the refusal of
                    // that requestor to respond to that particular prompt, so move on to the next requestor.
                    // If it was canceled through the token, then host itself is shutting down, and cancellation
                    // will be propagated on the entry to next iteration of this loop.
                    //
                    // If request was canceled due to CancelAllAsync, then we should not continue to process this
                    // ReadConsole call at all. Under normal conditions, ct will also be marked as canceled; but
                    // there is a potential for a race condition where we get a cancellation exception here, but
                    // ct is not marked as canceled yet. Explicitly checking for CancelAllException handles this.
                }
            } while (consoleInput == null);


            // We only want to fire 'directory changed' events when it is initiated by the user
            _processingChangeDirectoryCommand = consoleInput.StartsWithOrdinal("setwd");

            consoleInput = consoleInput.EnsureLineBreak();
            AfterRequest?.Invoke(this, new RAfterRequestEventArgs(contexts, Prompt, consoleInput, addToHistory, currentRequest?.IsVisible ?? false));

            return(consoleInput);
        }
예제 #3
0
 private void OnBeforeRequest(RawContext context, SessionEventArgs e)
 {
     if (context == null)
     {
         return;
     }
     BeforeRequest?.Invoke(context, e);
 }
예제 #4
0
 private ITraktModule RegisterModule(ITraktModule module)
 {
     module.BeforeRequest += (sender, e) => {
         BeforeRequest?.Invoke(sender, e);
     };
     module.AfterRequest += (sender, e) => {
         AfterRequest?.Invoke(sender, e);
     };
     return(module);
 }
예제 #5
0
 public Task <IRSessionEvaluation> BeginEvaluationAsync(CancellationToken cancellationToken = default(CancellationToken))
 {
     _eval = new RSessionEvaluationMock();
     BeforeRequest?.Invoke(this, new RRequestEventArgs(_eval.Contexts, Prompt, 4096, true));
     if (_eval.IsMutating)
     {
         Mutated?.Invoke(this, EventArgs.Empty);
     }
     return(Task.FromResult(_eval));
 }
예제 #6
0
 public Task <IRSessionEvaluation> BeginEvaluationAsync(CancellationToken cancellationToken = default(CancellationToken))
 {
     Evaluation = new RSessionEvaluationMock();
     BeforeRequest?.Invoke(this, new RBeforeRequestEventArgs(Evaluation.Contexts, Prompt, 4096, addToHistoty: true));
     if (Evaluation.IsMutating)
     {
         Mutated?.Invoke(this, EventArgs.Empty);
     }
     return(Task.FromResult((IRSessionEvaluation)Evaluation));
 }
예제 #7
0
        async Task <string> IRCallbacks.ReadConsole(IReadOnlyList <IRContext> contexts, string prompt, int len, bool addToHistory, bool isEvaluationAllowed, CancellationToken ct)
        {
            await TaskUtilities.SwitchToBackgroundThread();

            var currentRequest = Interlocked.Exchange(ref _currentRequestSource, null);

            _contexts = contexts;
            Prompt    = prompt;
            MaxLength = len;

            var requestEventArgs = new RRequestEventArgs(contexts, prompt, len, addToHistory);

            BeforeRequest?.Invoke(this, requestEventArgs);

            CancellationTokenSource evaluationCts;
            Task evaluationTask;

            if (isEvaluationAllowed)
            {
                evaluationCts  = new CancellationTokenSource();
                evaluationTask = EvaluateUntilCancelled(contexts, evaluationCts.Token, ct); // will raise Mutate
            }
            else
            {
                evaluationCts  = null;
                evaluationTask = Task.CompletedTask;
                OnMutated();
            }

            currentRequest?.CompleteResponse();

            string consoleInput = null;

            do
            {
                ct.ThrowIfCancellationRequested();
                try {
                    consoleInput = await ReadNextRequest(prompt, len, ct);
                } catch (OperationCanceledException) {
                    // If request was canceled through means other than our token, it indicates the refusal of
                    // that requestor to respond to that particular prompt, so move on to the next requestor.
                    // If it was canceled through the token, then host itself is shutting down, and cancellation
                    // will be propagated on the entry to next iteration of this loop.
                }
            } while (consoleInput == null);

            // If evaluation was allowed, cancel evaluation processing but await evaluation that is in progress
            evaluationCts?.Cancel();
            await evaluationTask;

            AfterRequest?.Invoke(this, requestEventArgs);

            return(consoleInput);
        }
예제 #8
0
        public ProxyNextAction OnBeforeRequest(Session session)
        {
            ProxyNextAction?nextAction = BeforeRequest?.Invoke(session);

            if (nextAction.HasValue)
            {
                return(nextAction.Value);
            }
            else
            {
                return(ProxyNextAction.AllowAndIgnoreContent);
            }
        }
예제 #9
0
        public int OnBeforeRequest(Session session)
        {
            Int32?blocked = BeforeRequest?.Invoke(session);

            if (blocked.HasValue)
            {
                return(blocked.Value);
            }
            else
            {
                return(0);
            }
        }
예제 #10
0
        /// <summary>
        /// Executes specified X-Road operations with given arguments.
        /// </summary>
        public T Execute <T>(object arg, IXRoadHeader xRoadHeader, IServiceMap serviceMap = null)
        {
            IServiceMap operationServiceMap = null;

            using (var requestMessage = new XRoadMessage(Protocol, xRoadHeader))
            {
                using (var writer = XmlWriter.Create(requestMessage.ContentStream))
                {
                    writer.WriteStartDocument();

                    Protocol.Style.WriteSoapEnvelope(writer, Protocol.ProducerNamespace);
                    if (!string.IsNullOrEmpty(RequestNamespace))
                    {
                        writer.WriteAttributeString(PrefixConstants.XMLNS, "req", NamespaceConstants.XMLNS, RequestNamespace);
                    }

                    Protocol.WriteSoapHeader(writer, xRoadHeader);

                    writer.WriteStartElement("Body", NamespaceConstants.SOAP_ENV);

                    operationServiceMap = serviceMap ?? requestMessage.GetSerializerCache().GetServiceMap(XName.Get(xRoadHeader.Service.ServiceCode, Protocol.ProducerNamespace));
                    operationServiceMap.SerializeRequest(writer, arg, requestMessage, RequestNamespace);

                    writer.WriteEndElement();
                    writer.WriteEndElement();
                    writer.WriteEndDocument();
                    writer.Flush();
                }

                var request = WebRequest.Create(Uri);

                request.ContentType           = $"text/xml; charset={XRoadEncoding.UTF8.WebName}";
                request.Headers["SOAPAction"] = string.Empty;
                request.Method = "POST";

                BeforeRequest?.Invoke(this, new XRoadRequestEventArgs(request, requestMessage));

                requestMessage.SaveTo(request);

                using (var response = request.GetResponseAsync().Result)
                    using (var responseStream = response.GetResponseStream())
                        using (var seekableStream = new MemoryStream())
                            using (var responseMessage = new XRoadMessage())
                            {
                                responseStream?.CopyTo(seekableStream);
                                BeforeDeserialize?.Invoke(this, new XRoadResponseEventArgs(response, seekableStream));
                                responseMessage.LoadResponse(seekableStream, response.Headers.GetContentTypeHeader(), Path.GetTempPath(), Protocol);
                                return((T)responseMessage.DeserializeMessageContent(operationServiceMap));
                            }
            }
        }
예제 #11
0
        /// <summary>
        /// Send an request an an asynchronous operation
        /// </summary>
        /// <param name="uri">The Uri the request is sent to</param>
        /// <returns>The task object representing the asynchronous operation</returns>
        public async Task SendGetRequestAsync(Uri uri)
        {
            var req = new HttpRequestMessage(HttpMethod.Get, uri);

            mergeHeaders(req, RequestHeaders);
            BeforeRequest?.Invoke(this, new FetchTEventArgs <HttpRequestMessage>(new Link(uri, uri), req));

            if (Logger != null)
            {
                Logger.Information($"[GET] {uri}");
            }

            var resp = await httpClient.SendAsync(req);

            await processSendResult(req, resp, new Link(uri, uri));
        }
예제 #12
0
        public async Task <EntryResponse> ExecuteAsync(EntryRequest interaction)
        {
            if (interaction == null)
            {
                throw Error.ArgumentNull(nameof(interaction));
            }

            bool compressRequestBody = false;

            var request = interaction.ToHttpWebRequest(BaseUrl, Settings);

#if !NETSTANDARD1_6
            request.Timeout = Settings.Timeout;
#endif

            if (Settings.PreferCompressedResponses)
            {
                request.Headers["Accept-Encoding"] = "gzip, deflate";
            }

            BeforeRequest?.Invoke(request, interaction.RequestBodyContent);

            // Write the body to the output
            if (interaction.RequestBodyContent != null)
            {
                request.WriteBody(compressRequestBody, interaction.RequestBodyContent);
            }

            // Make sure the HttpResponse gets disposed!
            using (HttpWebResponse webResponse = (HttpWebResponse)await request.GetResponseAsync(TimeSpan.FromMilliseconds(Settings.Timeout)).ConfigureAwait(false))
            {
                try
                {
                    //Read body before we call the hook, so the hook cannot read the body before we do
                    var inBody = readBody(webResponse);
                    AfterResponse?.Invoke(webResponse, inBody);

                    return(webResponse.ToEntryResponse(inBody));
                }
                catch (AggregateException ae)
                {
                    throw ae.GetBaseException();
                }
            }
        }
예제 #13
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="method"></param>
        /// <param name="url"></param>
        /// <param name="body"></param>
        /// <param name="headersAction"></param>
        /// <exception cref="T:System.Net.Http.HttpRequestException">
        ///   由于基础问题(如网络连接性、DNS 失败、服务器证书验证或超时),请求失败。
        /// </exception>
        /// <returns></returns>
        public async Task <RestResponse> Send(HttpMethod method, string url, HttpContent body,
                                              Action <HttpRequestHeaders> headersAction = null)
        {
            //请求行
            if (!string.IsNullOrEmpty(_config.BaseUrl))
            {
                //baseUrl 和 url参数必需用 / 连接
                url = !_config.BaseUrl.EndsWith("/") && !url.StartsWith("/")
                    ? _config.BaseUrl + "/" + url
                    : _config.BaseUrl + url;
            }

            HttpRequestMessage httpRequestMessage = new HttpRequestMessage(method, url);

            //请求体
            if (body != null)
            {
                httpRequestMessage.Content = body;
            }
            //请求头
            headersAction?.Invoke(httpRequestMessage.Headers);
            //触发事件
            BeforeRequest?.Invoke(httpRequestMessage);

            RestResponse restResponse;

            //发送请求
            try {
                HttpResponseMessage httpResponseMessage = await _httpClient.SendAsync(httpRequestMessage);

                restResponse = new RestResponse(httpResponseMessage);
            }
            catch (Exception e) {
                restResponse = new RestResponse(httpRequestMessage, e);
            }
            //触发事件
            AfterResponse?.Invoke(restResponse);
            if (restResponse.Exception != null)
            {
                throw restResponse.Exception;
            }
            return(restResponse);
        }
예제 #14
0
        private void fetch(Link current)
        {
            var req = new HttpRequestMessage(HttpMethod.Get, current.Uri);

            RequestHelper.mergeHeaders(req, IncludeRequestHeaders);

            BeforeRequest?.Invoke(this, new FetchTEventArgs <HttpRequestMessage>(current, req));

            var resp       = httpClient.SendAsync(req).Result;
            var reqHeaders = RequestHelper.processHeaders(req.Headers);

            current.FetchEnd = DateTime.Now;
            if (resp.IsSuccessStatusCode)
            {
                var respHeaders = RequestHelper.processHeaders(resp.Headers);

                byte[] content = RequestHelper.loadResponseDataDecompress(resp.Content.ReadAsByteArrayAsync().Result);

                FetchCompleted(this, new FetchCompleteEventArgs(current,
                                                                content,
                                                                reqHeaders,
                                                                respHeaders));
            }
            else
            {
                if (resp.Headers.Location != null)
                {
                    // Redirect
                    var newUri = current.Uri.Combine(resp.Headers.Location.ToString());
                    current.ResourceMoved(newUri);
                    config.Logger.Information($"[MOV] {current.MovedUri} -> {current.Uri}");
                    fetch(current);
                    return;
                }

                FetchFailed(this, new FetchFailEventArgs(current,
                                                         (int)resp.StatusCode,
                                                         new HttpRequestException($"[{(int)resp.StatusCode}] {resp.ReasonPhrase}"),
                                                         new HeaderCollection(reqHeaders)));
            }
        }
예제 #15
0
        /// <summary>
        /// Override SendResponse to read request data
        /// </summary>
        protected override void SendRequest()
        {
            var req = new HttpRequest(this.RequestLine, this.RequestHeaders, null);

            if (BeforeRequest != null)
            {
                if (!BeforeRequest.Invoke(req))
                {
                    this.AbortRequest();
                    return;
                }
            }

            AfterReadRequestHeaders?.Invoke(req);

            this.currentSession = new Session();
            this.SocketPS.WriteBinary(Encoding.ASCII.GetBytes(
                                          $"{this.RequestLine.RequestLine}\r\n{this.RequestHeaders.HeadersInOrder}\r\n"));

            byte[] request = null;
            if (this.State.bRequestHasMessage)
            {
                if (this.State.bRequestMessageChunked)
                {
                    this.SocketBP.TunnelChunkedDataTo(this.SocketPS);
                }

                else
                {
                    request = new byte[this.State.RequestMessageLength];
                    this.SocketBP.TunnelDataTo(request, this.State.RequestMessageLength);
                    this.SocketPS.TunnelDataTo(this.TunnelPS, request);
                }
            }
            this.currentSession.Request = new HttpRequest(this.RequestLine, this.RequestHeaders, request);
            this.State.NextStep         = this.ReadResponse;
        }
예제 #16
0
 internal void InvokeBeforeRequest(Context ctx) => BeforeRequest?.Invoke(ctx);
예제 #17
0
 /// <summary>
 /// Invocator for BeforeRequest event.
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 protected virtual void OnBeforeRequest(object sender, SessionEventArgs e)
 {
     BeforeRequest?.Invoke(sender, e);
 }
예제 #18
0
 protected virtual void OnBeforeRequest(ClientRequestEventArgs e)
 {
     BeforeRequest?.Invoke(this, e);
 }
예제 #19
0
 public Task <IRSessionInteraction> BeginInteractionAsync(bool isVisible = true, CancellationToken cancellationToken = default(CancellationToken))
 {
     _inter = new RSessionInteractionMock();
     BeforeRequest?.Invoke(this, new RRequestEventArgs(_inter.Contexts, Prompt, 4096, true));
     return(Task.FromResult(_inter));
 }
예제 #20
0
 public virtual void OnBeforeRequest(WebEventArgs e)
 {
     BeforeRequest?.Invoke(e.Context, e);
 }
예제 #21
0
 private void onBeforeRequest(long handle)
 {
     BeforeRequest?.Invoke(new Session(handle, new Request(handle), new Response(handle)));
 }
예제 #22
0
 private int onBeforeRequest(long handle)
 {
     return((int)BeforeRequest?.Invoke(new Session(handle, new Request(handle), new Response(handle))));
 }