private static async void Test2() { var watcher = new System.Diagnostics.Stopwatch(); watcher.Start(); var request = new HttpRequest(new Uri("https://www.baidu.com/")); request.KeepAlive = true; request.CookieContainer = new CookieContainer(); using (var response = await request.SendAsync()) { var sum = 0; using (var stream = response.GetResponseStream()) { var buffer = new byte[4096]; var count = 0; while ((count = await stream.ReadAsync(buffer, 0, buffer.Length)) > 0) { sum += count; // Console.WriteLine(count); } } Console.WriteLine("#2 total " + sum + " bytes"); } watcher.Stop(); Console.WriteLine("elapsed[1]:" + watcher.Elapsed.TotalMilliseconds + "'ms"); }
public static void AddPersonToFamily( Rock.Client.Person person, int childAdultRoleMemberId, int toFamilyId, bool removeFromOtherFamilies, HttpRequest.RequestResult result ) { // setup the oData. childAdultRoleMemberId describes whether this person should be an adult or child in the family. string oDataFilter = string.Format( "?personId={0}&familyId={1}&groupRoleId={2}&removeFromOtherFamilies={3}", person.Id, toFamilyId, childAdultRoleMemberId, removeFromOtherFamilies ); RockApi.Post_People_AddExistingPersonToFamily( oDataFilter, result ); }
public HttpRequestWrapper(string url, HttpRequestMethod method, Encoding encode) { reqSetting = new HttpRequestSetting(url, method, encode); httpRequest = new HttpRequest(); cookieParser = new CookieParser(); }
public async void TestRouter() { var routeTable = new RouteTable( Route.Get("/").With(() => new TextResponse("root")), Route.Get("/1").With(() => new TextResponse("one")), Route.Get("/2").With(() => new TextResponse("two")), Route.Get("/3").With(() => new TextResponse("three")), Route.Get("/{number}/capture").With(() => new TextResponse("some number")) ); var router = new Router(routeTable); var req1 = new HttpRequest(RemoteEndPoint, false, "localhost", Method.GET, new Uri("http://localhost/invalid"), "/invalid", string.Empty, new Dictionary<string, string>(), ContentTypes.Plain, 0, false, new MemoryStream()); var result1 = await router.HandleRequest(req1, DateTime.UtcNow); var resp1 = result1.HttpResponse; Assert.AreEqual(HttpStatusCode.NotFound, resp1.StatusCode); var req2 = new HttpRequest(RemoteEndPoint, false, "localhost", Method.GET, new Uri("http://localhost/1"), "/1", string.Empty, new Dictionary<string, string>(), ContentTypes.Plain, 0, false, new MemoryStream()); var result2 = await router.HandleRequest(req2, DateTime.UtcNow); var resp2 = result2.HttpResponse; Assert.IsInstanceOf<TextResponse>(resp2); Assert.AreEqual(ContentTypes.Plain, resp2.ContentType); Assert.AreEqual("one", System.Text.Encoding.UTF8.GetString(resp2.Body)); var req3 = new HttpRequest(RemoteEndPoint, false, "localhost", Method.GET, new Uri("http://localhost/8/capture"), "/8/capture", string.Empty, new Dictionary<string, string>(), ContentTypes.Plain, 0, false, new MemoryStream()); await router.HandleRequest(req3, DateTime.UtcNow); Assert.AreEqual("8", req3.PathVariables["number"]); }
private HttpResponse Process(HttpRequest request) { if (request.Method.ToLower() == "head") { return new HttpResponse(request.ProtocolVersion, HttpStatusCode.OK, string.Empty); } if (request.Method.ToLower() == "options") { var routes = Assembly.GetEntryAssembly() .GetTypes() .Where(x => x.Name.EndsWith("Controller") && typeof(Controller).IsAssignableFrom(x)) .Select( x => new { x.Name, Methods = x.GetMethods().Where(m => m.ReturnType == typeof(IActionResult)) }) .SelectMany( x => x.Methods.Select( m => string.Format( "/{0}/{1}/{{parameter}}", x.Name.Replace("Controller", string.Empty), m.Name))) .ToList(); return new HttpResponse(request.ProtocolVersion, HttpStatusCode.OK, string.Join(Environment.NewLine, routes)); } if (new StaticFileHandler().CanHandle(request)) { return new StaticFileHandler().Handle(request); } if (request.ProtocolVersion.Major <= 3) { HttpResponse response; try { var controller = this.CreateController(request); var actionInvoker = new ActionInvoker(); var actionResult = actionInvoker.InvokeAction(controller, request.Action); response = actionResult.GetResponse(); } catch (HttpNotFoundException exception) { response = new HttpResponse(request.ProtocolVersion, HttpStatusCode.NotFound, exception.Message); } catch (Exception exception) { response = new HttpResponse(request.ProtocolVersion, HttpStatusCode.InternalServerError, exception.Message); } return response; } return new HttpResponse(request.ProtocolVersion, HttpStatusCode.NotImplemented, "Request cannot be handled."); }
/// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public string GetContextTokenFromRequest(HttpRequest request) { try { string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" }; foreach (string paramName in paramNames) { if (!string.IsNullOrEmpty(request.Form[paramName])) { return request.Form[paramName]; } if (!string.IsNullOrEmpty(request.Query[paramName])) { return request.Query[paramName]; } } } catch { //RC1 produces exception on get request ((Microsoft.AspNet.Http.Internal.DefaultHttpRequest)request).Form //where the Form should be {} //https://github.com/aspnet/Mvc/issues/2749 //TODO: review later } return null; }
public HttpResponse GetResponse(HttpRequest request, CookieContainer cookies) { if (OsInfo.IsMonoRuntime && request.Url.Scheme == "https") { if (!_curlTLSFallbackCache.Find(request.Url.Host)) { try { return _managedDispatcher.GetResponse(request, cookies); } catch (Exception ex) { if (ex.ToString().Contains("The authentication or decryption has failed.")) { _logger.Debug("https request failed in tls error for {0}, trying curl fallback.", request.Url.Host); _curlTLSFallbackCache.Set(request.Url.Host, true); } else { throw; } } } if (CurlHttpDispatcher.CheckAvailability()) { return _curlDispatcher.GetResponse(request, cookies); } _logger.Trace("Curl not available, using default WebClient."); } return _managedDispatcher.GetResponse(request, cookies); }
internal void SetContext(Type type, HttpContext context, HttpRequest request, HttpResponse response) { PartialTrustHelpers.FailIfInPartialTrustOutsideAspNet(); this.type = type; this.context = context; this.request = request; this.response = response; Initialize(); }
public static HALResponse AddSelfLinkIfNotExists(this HALResponse response, HttpRequest request) { if(!response.HasSelfLink()) { response.AddSelfLink(request); } return response; }
public Http(HttpRequest httpRequest, HttpRequestParameters requestParameters = null) { _httpRequest = httpRequest; if (requestParameters != null) _requestParameters = requestParameters; else _requestParameters = new HttpRequestParameters(); _progress = new Progress(); }
private Http _Load(HttpRequest httpRequest, HttpRequestParameters requestParameters = null, string exportFile = null, bool setExportFileExtension = false) { Trace.WriteLine(1, "Load \"{0}\" ({1}){2}", httpRequest.Url, httpRequest.Method, exportFile != null ? "(\"" + exportFile + "\")" : null); Http http = CreateHttp(httpRequest, requestParameters, exportFile, setExportFileExtension); http.LoadAsText(); return http; }
public static void CreateNewFamily( Rock.Client.Group groupModel, HttpRequest.RequestResult resultHandler ) { // give the group model required values groupModel.Guid = Guid.NewGuid( ); groupModel.GroupTypeId = FamilyGroupTypeId; groupModel.IsActive = true; groupModel.IsPublic = true; RockApi.Post_Groups( groupModel, Config.Instance.CurrentPersonAliasId, resultHandler ); }
private static string BuildRequestString(HttpRequest r) { var sb = new StringBuilder(); sb.Append($"{r.Verb} /{r.Location} HTTP/1.1\r\n"); sb.Append($"Host: {r.Server}\r\n"); sb.Append("Connection: Close\r\n"); sb.Append("\r\n"); return sb.ToString(); }
public HttpResponse Handle(HttpRequest request) { var filePath = "../.." + "/" + request.Uri; if (!this.FileExists("C:\\", filePath, 3)) { return new HttpResponse(request.ProtocolVersion, HttpStatusCode.NotFound, "File not found!"); } var fileContents = File.ReadAllText(filePath); var response = new HttpResponse(request.ProtocolVersion, HttpStatusCode.OK, fileContents); return response; }
public static void GetConfigurationTemplates( int typeId, int configurationTemplateId, HttpRequest.RequestResult<List<Rock.Client.DefinedValue>> resultHandler ) { string oDataFilter = string.Format( "?LoadAttributes=simple&$filter=DefinedTypeId eq {0}", typeId ); // if a SPECIFIC templateId was requested, append it if ( configurationTemplateId > 0 ) { oDataFilter += string.Format( " and Id eq " + configurationTemplateId.ToString( ) ); } RockApi.Get_DefinedValues( oDataFilter, resultHandler ); }
public static HttpRequest CreateHttpRequest(string url, HttpRequestParameters_v1 requestParameters) { HttpRequest httpRequest = new HttpRequest(); httpRequest.Url = url; if (requestParameters != null) { httpRequest.Method = requestParameters.method; httpRequest.Content = requestParameters.content; httpRequest.Referer = requestParameters.referer; } return httpRequest; }
protected override ServerProtocol CreateIfRequestCompatible(HttpRequest request) { if (request.PathInfo.Length < 2) return null; if (request.HttpMethod != "POST") // MethodNotAllowed = 405, return new UnsupportedRequestProtocol(405); bool isLocal = request.Url.IsLoopback || request.IsLocal; if (!isLocal) return null; return new HttpPostServerProtocol(); }
public Http Load(HttpRequest httpRequest, HttpRequestParameters requestParameters = null, string exportFile = null, bool setExportFileExtension = false) { try { for (int i = 0; i < _loadRepeatIfError - 1; i++) { try { return _Load(httpRequest, requestParameters, exportFile, setExportFileExtension); } catch (Exception ex) { if (ex is WebException) { WebException wex = (WebException)ex; // WebExceptionStatus : ConnectFailure, PipelineFailure, ProtocolError, ReceiveFailure, SendFailure, ServerProtocolViolation, Timeout, UnknownError // $$pb modif le 27/01/2015 WebExceptionStatus.NameResolutionFailure ex : "The remote name could not be resolved: 'pixhost.me'" if (wex.Status == WebExceptionStatus.ProtocolError || wex.Status == WebExceptionStatus.NameResolutionFailure) throw; } if (ex is ProtocolViolationException) throw; Trace.WriteLine(1, "Error : \"{0}\" ({1})", ex.Message, ex.GetType().ToString()); } } return _Load(httpRequest, requestParameters, exportFile, setExportFileExtension); } catch (Exception ex) { //Load("http://www.frboard.com/magazines-et-journaux/441873-multi-les-journaux-mardi-13-aout-2013-pdf-lien-direct.html"); //15/08/2013 12:00:32 Error : A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 5.199.168.178:80 (System.Net.Sockets.SocketException) //Unable to connect to the remote server (System.Net.WebException) //---------------------- // at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) // at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception) //---------------------- // at System.Net.HttpWebRequest.GetResponse() // at pb.old.Http.OpenWebRequest() in c:\pib\dropbox\pbeuz\Dropbox\dev\project\Source\Source_01\Source\PB_Tools\\Http_Html.cs:line 911 // at pb.old.Http.Open() in c:\pib\dropbox\pbeuz\Dropbox\dev\project\Source\Source_01\Source\PB_Tools\\Http_Html.cs:line 780 // at pb.old.Http.Load() in c:\pib\dropbox\pbeuz\Dropbox\dev\project\Source\Source_01\Source\PB_Tools\\Http_Html.cs:line 503 // at pb.old.HtmlXmlReader.Load(String sUrl) in c:\pib\dropbox\pbeuz\Dropbox\dev\project\Source\Source_01\Source\PB_Tools\\HtmlXmlReader.cs:line 426 // at Print.download.w.Test_frboard_02() // at Print.download.w.Run() if (_traceException) Trace.CurrentTrace.WriteError(ex); else throw; return null; } }
public static void GetGeneralDataTime( HttpRequest.RequestResult<DateTime> resultHandler ) { string oDataFilter = string.Format( "?$filter=AttributeId eq {0}", GeneralDataTimeValueId ); RockApi.Get_AttributeValues<List<DateTimeModel>>( oDataFilter, delegate(HttpStatusCode statusCode, string statusDescription, List<DateTimeModel> dateTimeList) { DateTime dateTime = DateTime.MinValue; if( dateTimeList != null && dateTimeList.Count > 0 && dateTimeList[ 0 ].ValueAsDateTime != null ) { dateTime = DateTime.Parse( dateTimeList[ 0 ].ValueAsDateTime ); } resultHandler( statusCode, statusDescription, dateTime ); } ); }
public HttpSession(long id, TcpClient tcpClient, Stream stream, bool isSecured, int maxKeepAlives, int initialReadBufferSize, int readTimeoutMs, int writeTimeoutMs) : base(id, tcpClient, stream, initialReadBufferSize, readTimeoutMs, writeTimeoutMs) { this.isSecured = isSecured; this.maxKeepAlives = maxKeepAlives; requestState = null; }
public void Unsubscribe(HttpRequest req, HttpResponse res) { var data = req.ParseJSON<Subscription>(); if (data == null || string.IsNullOrEmpty(data.ClientId) || string.IsNullOrEmpty(data.SubscribedEvent)) { res.SendError(StatusCode.BadRequest, "Invalid data"); return; } _subscriptions.RemoveAll(s => s.ClientId == data.ClientId && s.SubscribedEvent == data.SubscribedEvent); req.Server.RaiseLogEvent("info", string.Format("subsriber removed: {0}", req.RawBody)); res.SendJson(new { success = true }); }
public HttpResponse GetResponse(string requestAsString) { HttpRequest request; try { var requestParser = new HttpRequest("GET", "/", "1.1"); request = requestParser.Parse(requestAsString); } catch (Exception ex) { return new HttpResponse(new Version(1, 1), HttpStatusCode.BadRequest, ex.Message); } var response = this.Process(request); return response; }
public HttpSession(long id, TcpClient tcpClient, Stream stream, bool isSecured, int maxKeepAlives, int initialReadBufferSize, TimeSpan readTimeout, TimeSpan writeTimeout) : base(id, tcpClient, stream, initialReadBufferSize, (int)writeTimeout.TotalMilliseconds) { this.isSecured = isSecured; this.maxKeepAlives = maxKeepAlives; this.readTimeout = readTimeout; requestState = null; }
/// <summary> /// In this method the Liskov Substitution Principle can be observed. The method is /// Proccessing request through polymorfism calling handler.Handle() where handler is /// a successor of an interface /// </summary> /// <param name="request"></param> /// <returns></returns> public HttpResponse ProccessRequest(HttpRequest request) { foreach (IRequestHandler handler in this.handlers) { handler.Handle(request); if (handler.IsSuccessful) { return handler.Response; } } // If no handler did resolve the request an 'invalid request' response is returned return new HttpResponse( request.ProtocolVersion, HttpStatusCode.NotImplemented, CantHandleErrorMessage); }
public static void GetAppAuthorization( int personId, HttpRequest.RequestResult resultHandler ) { // use PersonId 379595 for debugging. that one is allowed. string oDataFilter = string.Format( "?$filter=Guid eq guid'D832E933-1972-4482-B24D-6AF0AC6BDF20' and Members/any(p: p/PersonId eq {0})", personId ); RockApi.Get_Groups<List<Rock.Client.Group>>( oDataFilter, delegate(HttpStatusCode statusCode, string statusDescription, List<Rock.Client.Group> model ) { // if we get a successful status code, a valid model, and there's an object in it, they're authorized. if( Rock.Mobile.Network.Util.StatusInSuccessRange( statusCode ) && model != null && model.Count > 0) { resultHandler( HttpStatusCode.OK, "" ); } else { resultHandler( HttpStatusCode.Unauthorized, "" ); } } ); }
private Controller CreateController(HttpRequest request) { var controllerClassName = request.Action.ControllerName + "Controller"; var type = Assembly.GetEntryAssembly() .GetTypes() .FirstOrDefault( x => x.Name.ToLower() == controllerClassName.ToLower() && typeof(Controller).IsAssignableFrom(x)); if (type == null) { throw new HttpNotFoundException( string.Format("Controller with name {0} not found!", controllerClassName)); } var instance = (Controller)Activator.CreateInstance(type, request); return instance; }
public bool TryParseNextRequestFromBuffer(out int requestBytes, out HttpRequest request) { if (dataStart == readBufferOffset) { requestBytes = -1; request = null; return false; } if (requestState == null) { currentRequestBytes = 0; requestState = new HttpRequest((IPEndPoint)TcpClient.Client.RemoteEndPoint, isSecured); } var initialDataStart = dataStart; var isRequestComplete = RequestParser.TryParseHttpRequest(readBuffer, ref dataStart, readBufferOffset, requestState, out request); currentRequestBytes += dataStart - initialDataStart; if (isRequestComplete) { requestBytes = currentRequestBytes; CompactReadBuffer(ref dataStart); currentRequestBytes = 0; requestState = null; requests++; return true; } else { if (requestState.State == RequestParser.State.ReadBodyToEnd && readBuffer.Length >= 32768) { CompactReadBuffer(ref dataStart); // read in block of max. 32kb, do not allow further expansion of buffer (eg. big file post upload) } requestBytes = -1; request = null; return false; } }
public static void GetNews( HttpRequest.RequestResult< List<Rock.Client.ContentChannelItem> > resultHandler ) { string oDataFilter = ""; // if they're a developer, pull down pending and future start date items as well. if( RockGeneralData.Instance.Data.DeveloperModeEnabled == true ) { oDataFilter = string.Format( "?$filter=ContentChannel/Guid eq guid'EAE51F3E-C27B-4E7C-B9A0-16EB68129637' and " + "(Status eq '2' or Status eq '1') and " + "(ExpireDateTime ge DateTime'{0}' or ExpireDateTime eq null)&LoadAttributes=True", DateTime.Now.ToString( "s" ) ); } else { oDataFilter = string.Format( "?$filter=ContentChannel/Guid eq guid'EAE51F3E-C27B-4E7C-B9A0-16EB68129637' and " + "Status eq '2' and (StartDateTime le DateTime'{0}' or StartDateTime eq null) and " + "(ExpireDateTime ge DateTime'{0}' or ExpireDateTime eq null)&LoadAttributes=True", DateTime.Now.ToString( "s" ) ); } RockApi.Get_ContentChannelItems( oDataFilter, resultHandler ); }
public static void JoinGroup( Rock.Client.Person person, string firstName, string lastName, string spouseName, string email, string phone, int groupId, string groupName, HttpRequest.RequestResult resultHandler ) { if ( person.PrimaryAliasId.HasValue && person.PrimaryAliasId.Value != 0 ) { // resolve the alias ID ApplicationApi.ResolvePersonAliasId( person, delegate(int personId ) { string oDataFilter = string.Format( "/{0}?PersonAliasId={1}&FirstName={2}&LastName={3}&SpouseName={4}&Email={5}&MobilePhone={6}&GroupId={7}&GroupName={8}", GroupRegistrationValueId, personId, firstName, lastName, spouseName, email, phone, groupId, groupName ); RockApi.Post_Workflows_WorkflowEntry( oDataFilter, resultHandler ); } ); } else { // no ID, so just send the info string oDataFilter = string.Format( "/{0}?PersonAliasId={1}&FirstName={2}&LastName={3}&SpouseName={4}&Email={5}&MobilePhone={6}&GroupId={7}&GroupName={8}", GroupRegistrationValueId, 0, firstName, lastName, spouseName, email, phone, groupId, groupName ); RockApi.Post_Workflows_WorkflowEntry( oDataFilter, resultHandler ); } }
public void Publish(HttpRequest req, HttpResponse res) { var evt = req.ParseJSON<PublishedEvent>(); var eventType = EventFactory.GetPublishedEventType(evt.Name); var evtData = req.ParseJSON(eventType) as PublishedEvent; if (evtData == null || eventType == null || evtData == null) { res.SendError(StatusCode.BadRequest, "Invalid data"); return; } var subs = _subscriptions.Where(sub => sub.SubscribedEvent == evt.Name).ToList(); req.Server.RaiseLogEvent("info", string.Format("event published: {0}", req.RawBody)); // loop for all subscribers have registered for push notification foreach (var sub in subs) { var resource = EventFactory.CreatePublishedResource(evt.Name, sub.ClientId, evtData); if (!string.IsNullOrEmpty(sub.Endpoint)) { try { WebClient.PostJsonAsync(sub.Endpoint, resource, (responseText) => { req.Server.RaiseLogEvent("info", string.Format("forwarded to subscriber {0}", sub.ClientId)); }); } catch { } } else _resources.Add(resource); } res.SendJson(new { success = true }); }