public HttpClient(IConnectionManager connectionManager, IWebRequest webRequest, IReynaLogger logger, ITime time) { this.ConnectionManager = connectionManager; _webRequest = webRequest; _logger = logger; _time = time; }
public void WriteJsonObject(IWebRequest req, object obj) { var data = JsonSerializer.SerializeObject(obj); var encoded = Encoding.UTF8.GetBytes(data); req.ContentLength = encoded.Length; var output = req.GetRequestStream(); output.Write(encoded, 0, encoded.Length); // ReSharper disable RedundantAssignment // Clean up data = null; encoded = null; _garbage.Collect(); // ReSharper restore RedundantAssignment }
public WebApi(IWebRequest webRequest, IHelper helper) { this.webRequest = webRequest; this.helper = helper; endpoints = new Dictionary<string, WebApiEndpoint>() { { "video", new WebApiEndpoint { Name = "video", Url = "http://www.ccboise.org/api/messages/video/" } }, { "audio", new WebApiEndpoint { Name = "audio", Url = "http://www.ccboise.org/api/messages/audio" } }, { "devotional", new WebApiEndpoint { Name = "devotional", Url = "http://www.ccboise.org/api/daily/devotionals", ItemUrl = "http://www.ccboise.org/api/daily/devotional/{ItemId}" } }, { "prayer", new WebApiEndpoint { Name = "prayer", Url = "http://www.ccboise.org/api/daily/prayer" } }, { "events", new WebApiEndpoint { Name = "events", Url = "http://www.ccboise.org/api/connect/events" } }, { "calendar", new WebApiEndpoint { Name = "calendar", Url = "http://www.ccboise.org/api/connect/calendar", ItemUrl = "http://www.ccboise.org/api/connect/calendar-event/{ItemId}" } }, }; }
public string ReadText(IWebRequest req, int bufferSize) { int read; var result = new byte[bufferSize]; using (var res = req.GetResponse()) { using (var stream = res.GetResponseStream()) { read = stream.Read(result, 0, result.Length); } } _garbage.Collect(); var chars = Encoding.UTF8.GetChars(result, 0, read); // ReSharper disable RedundantAssignment result = null; // ReSharper restore RedundantAssignment _garbage.Collect(); return new string(chars); }
protected BaseClient(IWebRequest webRequest, IConfigurationStore configurationStore, ILoggerFactory logger, IDataCache dataCache, IServiceResolution serviceResolution) : base(webRequest, configurationStore, logger, dataCache, serviceResolution) { }
/// <summary> /// Execute the provided request. /// </summary> /// <param name="newRequest"></param> /// <param name="maxRetries">The maximum number of times to retry the request. Use -1 to retry indefinitely.</param> public async Task ExecuteRequest(IWebRequest newRequest, int maxRetries) { if (newRequest == null) { throw new ArgumentNullException(nameof(newRequest)); } if ((newRequest.RequiresAuthentication) && (m_AuthenticationProvider == null)) { throw new ArgumentException("The request requires authentication and no authentication provider is available.", nameof(newRequest)); } EnsureConnectionInitialized(); bool requestComplete = false; bool lastCallWasAuthentication = false; //indicates if we just tried an auth, so another 401 means no go. int errorCount = 0; CancellationToken cancellationToken = GetCommonCancellationToken(); try { while ((cancellationToken.IsCancellationRequested == false) && (requestComplete == false) && ((maxRetries < 0) || (errorCount <= maxRetries))) { bool reAuthenticate = false; bool delayBeforeRetry = false; try { if (m_ConnectionState == ChannelConnectionState.Disconnected) { SetConnectionState(ChannelConnectionState.Connecting); } else if (m_ConnectionState == ChannelConnectionState.Connected) { SetConnectionState(ChannelConnectionState.TransferingData); } if ((newRequest.RequiresAuthentication) && (m_AuthenticationProvider.IsAuthenticated == false)) { //no point in waiting for the failure, go ahead and authenticate now. await Authenticate().ConfigureAwait(false); } //Now, because we know we're not MT-safe we can do this "pass around" m_RequestSupportsAuthentication = newRequest.SupportsAuthentication; await newRequest.ProcessRequest(this).ConfigureAwait(false); SetConnectionState(ChannelConnectionState.Connected); requestComplete = true; } catch (WebChannelMethodNotAllowedException ex) { if (m_UseCompatibilityMethods == false) { //most likely we did a delete or put and the caller doesn't support that, enable compatibility methods. m_UseCompatibilityMethods = true; SetUseCompatiblilityMethodsOverride(m_HostName, m_UseCompatibilityMethods); //so we don't have to repeatedly run into this for this server if (EnableLogging) { m_Logger.Write(LogMessageSeverity.Information, ex, true, LogCategory, "Switching to HTTP method compatibility mode", "Because we got an HTTP 405 error from the server we're going to turn on Http method compatibility translation and try again. Status Description:\r\n{0}", ex.Message); } } else { throw; } } catch (WebChannelExpectationFailedException ex) { if (m_UseHttpVersion10 == false) { //most likely we are talking to an oddball proxy that doesn't support keepalive (like on a train or plane, seriously..) m_UseHttpVersion10 = true; SetUseHttpVersion10Override(m_HostName, m_UseHttpVersion10); //so we don't have to repeatedly run into this for this server if (EnableLogging) { m_Logger.Write(LogMessageSeverity.Information, ex, true, LogCategory, "Switching to HTTP 1.0 compatibility mode", "Because we got an HTTP 417 error from the server we're going to turn on Http 1.0 compatibility translation and try again. Status Description:\r\n{0}", ex.Message); } } else { throw; } } catch (WebChannelAuthorizationException ex) { if ((m_AuthenticationProvider != null) && newRequest.SupportsAuthentication && //we can do an auth (lastCallWasAuthentication == false)) //and we didn't just try to do an auth.. { if (EnableLogging) { m_Logger.Write(LogMessageSeverity.Information, ex, true, LogCategory, "Attempting to authenticate to server", "Because we got an HTTP 401 error from the server we're going to attempt to authenticate with our server credentials and try again. Status Description:\r\n{0}", ex.Message); } lastCallWasAuthentication = true; reAuthenticate = true; } else { //rethrow to tell our caller it's an authorization problem. SetConnectionState(ChannelConnectionState.Disconnected); throw; } } catch (WebChannelFileNotFoundException) { //this is a real result, we don't want to retry. But, if we got this then something didn't *expect* the null so keep the exception flying. throw; } catch (HttpRequestException) { //if we didn't carve them out above then we consider these fatal. throw; } catch (Exception ex) { //assume a retryable connection error if (EnableLogging) { m_Logger.Write(LogMessageSeverity.Warning, ex, true, LogCategory, "Connection error while making web channel request", "We received a communication exception while executing the current request on our channel. Since it isn't an authentication exception we're going to retry the request.\r\nRequest: {0}\r\nError Count: {1:N0}\r\nException: {2}", newRequest, errorCount, ex.Message); } SetConnectionState(ChannelConnectionState.Disconnected); errorCount++; lastCallWasAuthentication = false; //so if we get another request to authenticate we'll give it a shot. if (CanRetry(maxRetries, errorCount)) { if (errorCount > 1) { //back down our rate. delayBeforeRetry = true; } } else { throw new WebChannelException(ex.Message, ex, null); } break; } if (reAuthenticate) { await Authenticate().ConfigureAwait(false); } if (delayBeforeRetry) { await SleepForConnection().ConfigureAwait(false); } } } catch (Exception ex) { //this is just here so we can log exceptions that we're letting get thrown. if (EnableLogging) { m_Logger.Write(LogMessageSeverity.Verbose, ex, true, LogCategory, ex.Message, "While executing a web channel request an exception was thrown, which will be thrown to our caller.\r\nRequest: {0}\r\n", newRequest); } throw; } }
void UpdateRequest(AuthenticationType authenticationType, string userName, string password, bool isDebug, IWebRequest req) { if (authenticationType == AuthenticationType.Windows) { req.UseDefaultCredentials = true; } else { req.UseDefaultCredentials = false; // we to default to the hidden public user name of \, silly know but that is how to get around ntlm auth ;) if (authenticationType == AuthenticationType.Public) { userName = GlobalConstants.PublicUsername; password = string.Empty; } req.Credentials = new NetworkCredential(userName, password); } var remoteInvokerId = DataObject.RemoteInvokerID; if (remoteInvokerId == Guid.Empty.ToString()) { throw new Exception(ErrorResource.RemoteServerIDNull); } req.Headers.Add(HttpRequestHeader.From, remoteInvokerId); // Set to remote invoke ID ;) req.Headers.Add(HttpRequestHeader.Cookie, isDebug ? GlobalConstants.RemoteServerInvoke : GlobalConstants.RemoteDebugServerInvoke); ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true; }
private static void SetAuthorizationHeaderOnRequest(IWebRequest request, string accessToken) { request.Headers["Authorization"] = string.Format("Basic {0}", accessToken); }
public CwsProfileSettingsClient(IWebRequest gracefulClient, IConfigurationStore configuration, ILoggerFactory logger, IDataCache dataCache, IServiceResolution serviceResolution) : base(gracefulClient, configuration, logger, dataCache, serviceResolution) { }
private Hashtable GetValue(IWebRequest req) { return _netio.ReadJsonObject(req, BufferSize); }
protected virtual void SetRequestHeaders(IWebRequest webRequest) { webRequest.Headers.Add("Cache-Control", "no-cache"); }
public DynamicDns(IWebRequest webRequest) { _webRequest = webRequest; }
public FileWebOperation(IWebRequest webRequest) { WebRequest = webRequest; }
private void WriteBody(IWebRequest req, object body) { _netio.WriteJsonObject(req, body); }
public Hashtable ReadJsonObject(IWebRequest req, int bufferSize) { _garbage.Collect(); var response = ReadText(req, bufferSize); return JsonSerializer.DeserializeString(response) as Hashtable; }
public UsrRequestControl(IWebRequest webRequest, Guid Id) { InitializeComponent(); this.webRequest = webRequest; this.Id = Id; }
public TwitchService(IWebRequest webRequest) { this.webRequest = webRequest; }
protected abstract Task <IWebResponse> OnSendAsync(IWebRequest request);
public XmlApiProxy(XmlApiSettings apiSettings, IWebRequest webRequest) { _apiSettings = apiSettings; _webRequest = webRequest; }
public override string CacheLifeKey => "PRODUCTIVITY3D_NOTIFICATION_CACHE_LIFE"; // not used public Productivity3dV2ProxyNotification(IWebRequest webRequest, IConfigurationStore configurationStore, ILoggerFactory logger, IDataCache dataCache, IServiceResolution serviceResolution) : base(webRequest, configurationStore, logger, dataCache, serviceResolution) { }
public abstract IWebResponse GetResponse (IWebRequest request, object arg);
public static Task <HttpResponseMessage> UploadFileAsync(this IWebRequest webRequest, string filePath) { var fileStream = new FileStream(filePath, FileMode.Open); return(webRequest.UploadFileAsync(fileStream, fileStream.Name)); }
public override IWebResponse GetResponse (IWebRequest request, object arg) { return (IWebResponse)request; }
public BingSearch(IWebRequest _webRequest) { webRequest = _webRequest; }
public CruiseControlParser(IWebRequest request) { _request = request; }
public TPaasProxy(IWebRequest webRequest, IConfigurationStore configurationStore, ILoggerFactory logger) : base(webRequest, configurationStore, logger) { }
public XmlApiService(XmlApiSettings apiSettings, IWebRequest webRequest) { _apiSettings = apiSettings; _webRequest = webRequest; }
public AuthenticationController(IWebRequest webRequest, ITwitchService twitchService) { this.webRequest = webRequest; this.twitchService = twitchService; }
public abstract T Execute(IWebRequest webRequest);
public ProxyRequestBuilder(IWebRequestFactory webRequestFactory, IWebRequest request) { _webRequestFactory = webRequestFactory; _request = request; }
private static void SetNestHeadersOnRequest(IWebRequest request, string userId) { request.Headers["X-nl-protocol-version"] = "1"; request.Headers["X-nl-user-id"] = userId; }
public Task ExecuteHandlers(IWebRequest request) => _handlers.ExecuteHandlersAsync(request, CancellationToken.None);
protected BaseServiceDiscoveryProxy(IWebRequest webRequest, IConfigurationStore configurationStore, ILoggerFactory logger, IDataCache dataCache, IServiceResolution serviceResolution) : base(webRequest, configurationStore, logger, dataCache) { _serviceResolution = serviceResolution; }
public AzureDevOpsRequest(IWebRequest webRequest, DllArgs args) { this.webRequest = webRequest; this.args = args; }
/// <param name="user">Identity, authentication, and security information of the client making the request.</param> /// <param name="request">Client request</param> /// <param name="response">Response that will be sent back to the client</param> public ListenerRequestEventArgs(IPrincipal user, IWebRequest request, IMutableWebResponse response) { User = user; Request = request; Response = response; }
public abstract IWebResponse GetResponse(IWebRequest request, object arg);
protected virtual void ExecuteWebRequestAsync(IWebRequest buildGetWebRequest) { _ = buildGetWebRequest?.GetResponseAsync(); }
public abstract void ProcessRequest(IWebRequest request);
public void ProcessRequest(IWebRequest request, IMutableWebResponse response, IPrincipal user, IEnumerable <IWebRequestFilter> requestFilters, IEnumerable <IWebResponseFilter> responseFilters) { Trace.TraceInformation("Responding to request: {0}", request.RawUrl); try { // Filter request var requestFilterResult = FilterRequest(request, requestFilters); if (requestFilterResult.Action == (requestFilterResult.Action | FilterResultAction.Block)) { Trace.TraceInformation("Blocking request."); if (requestFilterResult.Action == (requestFilterResult.Action | FilterResultAction.Redirect)) { Redirect(response, requestFilterResult.RedirectUrl); return; } if (requestFilterResult.Action == (requestFilterResult.Action | FilterResultAction.CustomResult)) { CustomAction(response, requestFilterResult.CustomResultStatus, requestFilterResult.CustomResultStream); return; } var message = String.Format("Request for {0} was blocked by a filter", request.RawUrl); var data = Encoding.Default.GetBytes(message); var messageStream = new MemoryStream(data); CustomAction(response, HttpStatusCode.OK, messageStream); return; } Trace.TraceInformation("Proxying request"); // Build proxy request var requestBuilder = new ProxyRequestBuilder(_webRequestFactory, request); var proxyRequest = requestBuilder.Build(); // Get proxy response Trace.TraceInformation("Getting proxy response"); using (var proxyResponse = proxyRequest.GetResponse()) { var responseFilterResult = FilterResponse(proxyResponse, responseFilters); if (responseFilterResult.Action == (responseFilterResult.Action | FilterResultAction.Block)) { Trace.TraceInformation("Blocking request."); if (responseFilterResult.Action == (responseFilterResult.Action | FilterResultAction.Redirect)) { Redirect(response, responseFilterResult.RedirectUrl); return; } if (responseFilterResult.Action == (responseFilterResult.Action | FilterResultAction.CustomResult)) { CustomAction(response, responseFilterResult.CustomResultStatus, responseFilterResult.CustomResultStream); return; } var message = String.Format("Request for {0} was blocked by a filter", request.RawUrl); var data = Encoding.Default.GetBytes(message); var messageStream = new MemoryStream(data); CustomAction(response, HttpStatusCode.OK, messageStream); return; } Trace.TraceInformation("Forwarding proxy response"); BuildResponse(response, proxyResponse); } } catch (HttpListenerException hEx) { if (hEx.ErrorCode == 64) { Trace.TraceWarning("Stream aborted"); } else { Trace.TraceError("Error processing request: {0}", hEx); var data = Encoding.Default.GetBytes("SimpleProxy: Error Processing Request."); var messageStream = new MemoryStream(data); CustomAction(response, HttpStatusCode.InternalServerError, messageStream); } } catch (ProxyResponseException wEx) { if (wEx.Response != null) { BuildResponse(response, wEx.Response); } if (wEx.Status == WebExceptionStatus.NameResolutionFailure) { Trace.TraceWarning("Name Resolution Failure, redirecting to search: {0}", request.RawUrl); Redirect(response, String.Format("http://www.google.com/search?q={0}", HttpUtility.UrlEncode(request.RawUrl))); } else { Trace.TraceError("Error processing request: {0}", wEx); var data = Encoding.Default.GetBytes(String.Format("SimpleProxy: Error Processing Request: {0}", wEx.Message)); var messageStream = new MemoryStream(data); CustomAction(response, HttpStatusCode.InternalServerError, messageStream); } } catch (Exception ex) { Trace.TraceError("Error processing request: {0}", ex); var data = Encoding.Default.GetBytes("SimpleProxy: Error Processing Request."); var messageStream = new MemoryStream(data); CustomAction(response, HttpStatusCode.InternalServerError, messageStream); } }
protected XDocument GetXDocument(IWebRequest request) { using (var response = request.GetResponse()) { using (var responseStream = response.GetResponseStream()) { if (responseStream != null) { using (var rd = new StreamReader(responseStream)) { return XDocument.Parse(rd.ReadToEnd()); } } } } return new XDocument(); }
public FilterV1Proxy(IWebRequest webRequest, IConfigurationStore configurationStore, ILoggerFactory logger, IDataCache dataCache, IServiceResolution serviceResolution) : base(webRequest, configurationStore, logger, dataCache, serviceResolution) { }
protected override void ExecuteWebRequestAsync(IWebRequest buildGetWebRequest) { LogExecutionUrl = buildGetWebRequest.RequestUri.ToString(); LogExecutionWebRequest = buildGetWebRequest; }
public abstract void ProcessRequest (IWebRequest request);
/// <summary> /// Set Proxy Information on WebRequest. /// </summary> /// <param name="request">Makes a request to a Uniform Resource Identifier (URI).</param> private void SetProxy(IWebRequest request) { Debug.Assert(request != null); IWebProxy proxy = _prefs.GetWebProxy(); if (proxy != null) { request.Proxy = proxy; } // Don't set request.Proxy = null - Issue 49 }
public HttpPoster(IWebRequest webRequest) { _webRequest = webRequest; }
protected CwsProfileSettingsManagerClient(IWebRequest webRequest, IConfigurationStore configurationStore, ILoggerFactory logger, IDataCache dataCache, IServiceResolution serviceResolution) : base(webRequest, configurationStore, logger, dataCache, serviceResolution) { }
public override void ProcessRequest (IWebRequest request) { request.Process ((IWebResponse)request); }
public HttpWebOperation(IWebRequest webRequest) { WebRequest = webRequest; }
private Hashtable GetValue(IWebRequest req) { return(_netio.ReadJsonObject(req, BufferSize)); }