public CacheRequestResult(Guid id, ChangeSet changeSet, Exception error, HttpState step, object state) { this.ChangeSet = changeSet; this.Error = error; this.State = state; this.Id = id; this.HttpStep = step; }
internal void ReleaseHttpState(HttpState state) { lock(this) { if(_states.Count < MAX_SIZE) { state.clear(); _states.Push(state); } } }
/// <summary> /// Creates a new instance of the http response class with the specified parameters. /// </summary> /// <param name="version">The http version.</param> /// <param name="state">The http state.</param> public HttpResponse(HttpVersion version, HttpState state) { if (!Enum.IsDefined(typeof(HttpVersion), version)) throw new ArgumentException("The argument is not valid.", nameof(version)); if (state == InvalidCode) throw new ArgumentException("The argument is not valid.", nameof(state)); HttpVersion = version; State = state; }
public void BeginConnectDest(EndPoint destEndPoint, AsyncCallback callback, object state) { DestEndPoint = destEndPoint; string request = string.Format(HTTP_CONNECT_TEMPLATE, destEndPoint); var b = Encoding.UTF8.GetBytes(request); var st = new HttpState(); st.Callback = callback; st.AsyncState = state; _remote.BeginSend(b, 0, b.Length, 0, HttpRequestSendCallback, st); }
public CacheRequestResult(Guid id, ChangeSetResponse response, int uploadCount, Exception error, HttpState step, object state) { this.ChangeSetResponse = response; this.Error = error; this.State = state; this.HttpStep = step; this.Id = id; this.BatchUploadCount = (uint)uploadCount; // Check that error is carried over to the response if (this.Error == null) return; if (this.ChangeSetResponse == null) this.ChangeSetResponse = new ChangeSetResponse(); this.ChangeSetResponse.Error = this.Error; }
public async Task ExecuteAsync_WithEditorDoesNotExist_VerifyResponse() { // Arrange string editorPath = "FileThatDoesNotExist.exe"; string commandText = "POST https://localhost/"; MockedShellState shellState = new MockedShellState(); IFileSystem fileSystem = new MockedFileSystem(); IUserProfileDirectoryProvider userProfileDirectoryProvider = new UserProfileDirectoryProvider(); IPreferences preferences = new UserFolderPreferences(fileSystem, userProfileDirectoryProvider, null); ICoreParseResult parseResult = CoreParseResultHelper.Create(commandText); HttpClient httpClient = new HttpClient(); HttpState httpState = new HttpState(preferences, httpClient); PostCommand postCommand = new PostCommand(fileSystem, preferences, new NullTelemetry()); preferences.SetValue(WellKnownPreference.DefaultEditorCommand, editorPath); // Act await postCommand.ExecuteAsync(shellState, httpState, parseResult, CancellationToken.None); // Execute Assert.Empty(shellState.Output); Assert.Contains(string.Format(Strings.BaseHttpCommand_Error_DefaultEditorDoesNotExist, editorPath), shellState.ErrorMessage); }
public void GetValueCompletions_MultipleMatches_ReturnsCorrectMatches() { DirectoryStructure directoryStructure = new DirectoryStructure(null); RequestInfo requestInfo = new RequestInfo(); requestInfo.SetRequestBody("GET", "application/json", ""); requestInfo.SetRequestBody("GET", "text/plain", ""); requestInfo.SetRequestBody("PUT", "application/xml", ""); directoryStructure.RequestInfo = requestInfo; HttpState httpState = SetupHttpState(); httpState.BaseAddress = new Uri("https://localhost/"); ApiDefinition apiDefinition = new ApiDefinition(); apiDefinition.DirectoryStructure = directoryStructure; httpState.ApiDefinition = apiDefinition; IEnumerable <string> result = HeaderCompletion.GetValueCompletions(method: "GET", path: "", header: "Content-Type", "", httpState); Assert.Equal(2, result.Count()); Assert.Contains("application/json", result, StringComparer.OrdinalIgnoreCase); Assert.Contains("text/plain", result, StringComparer.OrdinalIgnoreCase); }
public static IEnumerable <string> GetValueCompletions(string method, string path, string header, string prefix, HttpState programState) { header = header ?? throw new ArgumentNullException(nameof(header)); programState = programState ?? throw new ArgumentNullException(nameof(programState)); switch (header.ToUpperInvariant()) { case "CONTENT-TYPE": IEnumerable <string> results = programState.GetApplicableContentTypes(method, path); return(results?.Where(x => !string.IsNullOrEmpty(x) && x.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))); default: return(null); } }
public bool ContainsState(HttpState state) { return(_states.ContainsKey(state)); }
/// <summary> /// Get Async get request. /// </summary> /// <param name="getUrl"> The url.</param> /// <param name="values"> The get values.</param> /// <param name="cookies"> The cookies.</param> /// <param name="state"> The http state.</param> private void StartGetRequest(GetForm httpCommand, string getUrl, ArrayList values, CookieCollection cookies, HttpProperties settings, HttpState state) { try { httpCommand.StartAsyncHttpGet( getUrl, settings, values, cookies, state, false); } catch (Exception ex) { // register and show Utils.ExceptionHandler.RegisterException(ex); AbortSessionRun(ex.Message); } }
/// <summary> /// Redirects to url. /// </summary> /// <param name="state"> The HTTP State.</param> /// <param name="cookies"> The cookie collection.</param> /// <param name="settings"> The HTTP Settings.</param> /// <param name="url"> The url to redirect to.</param> private void ApplyUrlRedirection(HttpState state, CookieCollection cookies,HttpProperties settings, string url) { this.DisplaySessionProcessEvent(this, new SessionCommandProcessEventArgs("Requesting " + url)); // Request, we only use url, http settings and cookies, because // IE doesn't returns and arraylist of values for GET requests. this.StartGetRequest(safeSessionGetRequest,url,null, cookies, settings, state); }
/// <summary> /// Executes the next safe request in order. Uses session cookies instead of updating them. /// </summary> /// <param name="state"> The HTTP state.</param> /// <param name="responseBufferData"> The ResponseBuffer.</param> private void ExecuteNextSafeRequest(HttpState state, ResponseBuffer responseBufferData) { CookieCollection cookies = null; // Get safe session and execute Session safeSession = this.SafeSession; int k = state.SessionRequestId; // http settings HttpProperties httpSettings = null; if ( safeSession.SessionRequests[k].RequestHttpSettings == null ) { httpSettings = safeSessionPostRequest.ClientSettings; } else { httpSettings = safeSession.SessionRequests[k].RequestHttpSettings; } if ( safeSession.SessionRequests[k].RequestType == HttpRequestType.GET ) { GetSessionRequest sessionRequest = (GetSessionRequest)safeSession.SessionRequests[k]; // // Location is found in Hashtable // if ( responseBufferData.ResponseHeaderCollection.ContainsKey("Location") ) // { // #region Redirect // // Location is not empty // if ( ((string)responseBufferData.ResponseHeaderCollection["Location"])!=String.Empty ) // { // string location = (string)responseBufferData.ResponseHeaderCollection["Location"]; // Uri url = (Uri)responseBufferData.ResponseHeaderCollection["Response Uri"]; // // // Get redirect uri // string redirectUri = UriResolver.ResolveUrl(url,location); // // if ( this.SafeSession.IsCookieUpdatable ) // { // // get cookies from cookie manager // cookies = cookieManager.GetCookies(new Uri(redirectUri)); // } // else // { // // else use saved cookies // cookies = sessionRequest.RequestCookies; // } // // this.ApplyUrlRedirection(state, cookies,httpSettings, redirectUri); // } // #endregion // } // else // { #region Get Request // get cookies. if ( this.SafeSession.IsCookieUpdatable ) { // get cookies from cookie manager cookies = cookieManager.GetCookies(sessionRequest.Url); } else { // else use saved cookies cookies = sessionRequest.RequestCookies; } this.DisplaySessionProcessEvent(this, new SessionCommandProcessEventArgs("Requesting " + sessionRequest.Url.ToString())); // Request, we only use url, http settings and cookies, because // IE doesn't returns and arraylist of values for GET requests. this.StartGetRequest(safeSessionGetRequest, sessionRequest.Url.ToString(), null, cookies, httpSettings, state); #endregion //} } else { #region Post Request PostSessionRequest sessionRequest = (PostSessionRequest)safeSession.SessionRequests[k]; // Post url string postUrl = String.Empty; #region Update post url //if ( this.TestSession.SessionRequests[k].UpdateSessionUrl ) //{ Uri postUri = null; // if response headers null, use from response buffer if ( sessionRequest.ResponseHeaders == null ) { postUri = (Uri)responseBufferData.ResponseHeaderCollection["Response Uri"]; } else { // if it has uri if ( sessionRequest.ResponseHeaders.ContainsKey("Response Uri") ) { if ( sessionRequest.ResponseHeaders["Response Uri"] != null ) { postUri = (Uri)sessionRequest.ResponseHeaders["Response Uri"]; } } } string s = string.Empty; if ( postUri.Query.Length > 0 ) { s = postUri.AbsoluteUri.Replace(postUri.Query,""); } else { s = postUri.AbsoluteUri; } string action = parser.GetFormActionByAbsoluteUrl(s, responseBufferData.HttpBody); if ( action == "" ) { postUrl = s; } else { // Resolve url postUrl = UriResolver.ResolveUrl(postUri,action); } //} #endregion // get cookies. if ( this.SafeSession.IsCookieUpdatable ) { // get cookies from cookie manager cookies = cookieManager.GetCookies(new Uri(postUrl)); } else { // else use saved cookies cookies = sessionRequest.RequestCookies; } SessionCommandProcessEventArgs args = new SessionCommandProcessEventArgs("Requesting " + postUrl); // Check form for updates session values // Convert form ArrayList listValues = parser.ConvertToArrayList(sessionRequest.Form, responseBufferData.HttpBody); // Display posted values string posted = ConvertToPostDataString(listValues); args.Detail = "Posted data: " + posted; args.ProcessType = SessionProcessType.SafeRequest; this.DisplaySessionProcessEvent(this, args); // Request post this.StartPostRequest(safeSessionPostRequest, postUrl, listValues, cookies, httpSettings, state); #endregion } }
public void ProcessHTTP() { var memoryStream = this.RequestStream as MemoryStream; //Uses the underlying buffer instead of creating a new array with ToArray byte[] requestBytes = memoryStream.GetBuffer(); if(this.State == HttpState.RequestLine) { for (int i = 0; i < this.RequestStream.Length; i++) { if (requestBytes[i] == '\n') { string requestLine = Encoding.UTF8.GetString(requestBytes, 0, i - 1); log.Debug(string.Format("Request line, {0}", requestLine)); string[] request = requestLine.Split(' '); if (request.Length != 3) throw new HttpProcessException("Request line must be seperated by 3 spaces"); this.Request.Method = request[0]; this.Request.RequestURI = request[1]; this.Request.Version = request[2]; this.State = HttpState.Headers; this.requestBytesOffset = i; break; } } } if(State == HttpState.Headers) { for(int i = (int)requestBytesOffset; i < this.RequestStream.Length; i++) { if (requestBytes[i] == '\n' && requestBytes[i - 1] == '\r') { if ((i + 1) < this.RequestStream.Length && requestBytes[i + 1] == '\r' && requestBytes[i + 2] == '\n') { log.Debug("End of headers"); if (this.Request.Length != 0 || this.Request.TransferEncoding) { this.Request.Body = new byte[Request.Length]; this.State = HttpState.Body; } else State = HttpState.Finished; this.requestBytesOffset = i + 3; break; } else { string headerString = Encoding.UTF8.GetString(requestBytes, (int)this.requestBytesOffset + 1, i - (int)this.requestBytesOffset); if (!String.IsNullOrEmpty(headerString) && !String.IsNullOrWhiteSpace(headerString)) { string[] header = headerString.Split(HEADER_SPLIT, 2, StringSplitOptions.RemoveEmptyEntries); if (header.Length != 2) throw new HttpProcessException(string.Format("Malformed header [{0}]", headerString)); string fieldName = header[0].Trim(); string value = header[1].Trim(); //Field names are case insensitive if (fieldName.ToLower() == "content-length") { int length = 0; if (!int.TryParse(value, out length)) throw new HttpProcessException("Content-Length not an integer value"); this.Request.Length = length; } //Even if there was a content-length, transfer-encoding takes precedence if (fieldName.ToLower() == "transfer-encoding" && value == "chunked") { log.Debug("Transfer-Encoded message"); this.Request.TransferEncoding = true; this.Request.TransferEncodedBody = new MemoryStream(); } this.Request.Headers.Add(fieldName, value); log.Debug(string.Format("Header: {0} => {1}", fieldName, value)); this.requestBytesOffset = i; } } } } } if (this.State == HttpState.Body) { if (this.Request.TransferEncoding) { for (int i = (int)this.requestBytesOffset; i < this.RequestStream.Length; i++) { if(this.transferEncodedChunkRemaining == 0 && requestBytes[i] == '\n' && requestBytes[i - 1] == '\r') { //Might need to consider endianess here this.transferEncodedChunkSize = BitConverter.ToInt32(requestBytes, (int)requestBytesOffset); if(this.transferEncodedChunkSize == 0) { //Followed by a trailer of entity headers this.Request.Body = this.Request.TransferEncodedBody.ToArray(); this.Request.TransferEncodedBody.Dispose(); this.State = HttpState.Trailer; } this.transferEncodedChunkRemaining = this.transferEncodedChunkSize; log.Debug(string.Format("Transfer Encoded Chunk Size: {0}", this.transferEncodedChunkSize)); } else if(transferEncodedChunkRemaining != 0 && requestBytes[i] == '\n' && requestBytes[i - 1] == '\r') { this.Request.TransferEncodedBody.Write(requestBytes, (int)this.requestBytesOffset, this.transferEncodedChunkSize); this.transferEncodedChunkRemaining = 0; } } } else { //A non-transfer encoded request long remaining = this.RequestStream.Length - this.requestBytesOffset; if (remaining >= Request.Length) { Buffer.BlockCopy(requestBytes, (int)this.requestBytesOffset, this.Request.Body, 0, this.Request.Length); this.State = HttpState.Finished; } } } if(this.State == HttpState.Trailer) { //Will need to find a way to test transfer-encoding, but for now we'll finisht the request this.State = HttpState.Finished; } }
/// <summary> /// Executes the session. /// </summary> public void Run() { this._isRunning = true; reports = new ArrayList(); unitTestPostRequest = new PostForm(); unitTestGetRequest = new GetForm(); // Add proxy settings unitTestPostRequest.ProxySettings = this.Context.Proxy; unitTestGetRequest.ProxySettings = this.Context.Proxy; // http settings unitTestPostRequest.ClientSettings = this.Context.ProtocolProperties; unitTestGetRequest.ClientSettings = this.Context.ProtocolProperties; // set events for unit test requests unitTestPostRequest.EndHttp += new ResponseCallbackDelegate(UnitTestResult_EndHttp); unitTestGetRequest.EndHttp += new ResponseCallbackDelegate(UnitTestResult_EndHttp); HttpState state = new HttpState(); // the test sessin request of the safe request. state.TestSessionRequest = this.TestSession.SessionRequests[0]; state.SessionRequestId = 0; state.IsLastItem = true; ExecuteNextSafeRequest(state); }
public TransitionRoute(string route, HttpState state) { Route = route; State = state; }
public void Reset() { this.Socket = null; //No preformance benefits to setting the position to 0, as opposed to creating a new memory stream this.RequestStream = new MemoryStream(); this.Request = new HttpRequest(); //Not useful to call Dispose, but perhaps in the future if a change in streams this.Response.OutputStream.Dispose(); this.Response = new HttpResponse(); this.State = HttpState.RequestLine; }
public static TransitionList WithSimpleRouteOf(this TransitionList transitions, HttpState source, string defaultRoute, HttpState destination) { var transitionRoute = new TransitionRoute(defaultRoute, destination); var routes = new[] { transitionRoute }; transitions.Register(source, routes); return(transitions); }
public static Mock <IPipelineActionCreator> ForceExecuteToReturn(this Mock <IPipelineActionCreator> instance, HttpState desired, string newRoute) { var pipelineAction = new Mock <HttpPipelineAction>(); pipelineAction.Setup(p => p.Execute(It.IsAny <PipelineContext>(), It.IsAny <HttpContextBase>())).Returns(newRoute); instance.Setup(p => p.Create(It.Is <HttpState>(x => x == desired))).Returns(pipelineAction.Object); return(instance); }
public RequestConfig(HttpState state) : base(state) { }
public FakeAsyncResult(IAsyncResult orig, HttpState state) { r = orig; innerState = state; }
private bool OpenConnection() { lock (this) { if (_isConnectionOpened) { return(false); } _isConnectionOpened = true; } InitClient(); InitMethod(); _state = _stateCache.GetHttpState(); //todo insert needed Authontication, Cookies info to state! _method.setDoAuthentication(this.PreAuthenticate); InitHostConfig(); InitCredentials(); InitProxyCredentials(); if (this.ProtocolVersion == HttpVersion.Version11) { _method.getParams().setVersion(mainsoft.apache.commons.httpclient.HttpVersion.HTTP_1_1); } else if (ProtocolVersion == HttpVersion.Version10) { _method.getParams().setVersion(mainsoft.apache.commons.httpclient.HttpVersion.HTTP_1_0); } else { throw new ProtocolViolationException("Unsupported protocol version: " + ProtocolVersion); } if (!(_method is mainsoft.apache.commons.httpclient.methods.EntityEnclosingMethod)) { _method.setFollowRedirects(this.AllowAutoRedirect); } else { if (!AllowWriteStreamBuffering && _contentLength < 0 && !SendChunked) { throw new ProtocolViolationException(); } if (SendChunked) { ((EntityEnclosingMethod)_method).setContentChunked(SendChunked); } } if (MaxAutoRedirections != _defaultMaxRedirectsNum) { _method.getParams().setParameter(HttpClientParams.MAX_REDIRECTS, new java.lang.Integer(MaxAutoRedirections)); } foreach (string k in Headers) { if (String.Compare(k, "connection", StringComparison.InvariantCultureIgnoreCase) == 0) { continue; } string val = Headers[k]; val = (val == null) ? "" : val; _method.setRequestHeader(k, val); } if (this.CookieContainer != null) { string cookieHeader = this.CookieContainer.GetCookieHeader(this.GetOriginalAddress()); if (cookieHeader != "") { _method.setRequestHeader("Cookie", cookieHeader); } } SetConnectionHeader(Headers["Connection"]); _method.getParams().setSoTimeout(ReadWriteTimeout); return(true); }
public JsonConfig(HttpState state) { _state = state; }
private static void Arrange(string commandText, out HttpState httpState, out MockedShellState shellState, out ICoreParseResult parseResult, out UserFolderPreferences preferences) { Arrange(commandText, out httpState, out shellState, out parseResult, out _, out preferences); }
/// <summary> /// Apply the test requests for a session request. /// </summary> /// <param name="sessionRequest"> The session request.</param> /// <param name="result"> The response buffer result from the safe session.</param> private void ApplyRequestTests(SessionRequest sessionRequest, ResponseBuffer result) { UnitTestItem unitTestItem = sessionRequest.WebUnitTest; unitTestItem.Form = sessionRequest.Form; CookieCollection cookies = null; //int availableTests = this.AvailableTests(); //bool lastItem = false; string requestUrl = sessionRequest.Url.ToString(); #region Run each test in SessionRequest WebUnitTestItem // run each test in Form foreach (DictionaryEntry de in unitTestItem.Tests) { Test test = (Test)de.Value; ArrayList values = new ArrayList(); // get cookies cookies = cookieManager.GetCookies(sessionRequest.Url); // set current test index unitTestItem.SelectedTestIndex = unitTestItem.Tests.IndexOfValue(test); // create SessionCommandProcessEventArgs SessionCommandProcessEventArgs args = new SessionCommandProcessEventArgs("Applying test '" + test.Name + "' to " + sessionRequest.Url.ToString()); args.ProcessType = SessionProcessType.TestRequest; #region Apply Test // -------------------------------------------------------------------------------- // Process data // Html Form Tag if ( test.UnitTestDataType == UnitTestDataContainer.HtmlFormTag ) { // is a form tag // apply test to form HtmlFormTag filledForm = ApplyTestToForm(test, sessionRequest.Form.CloneTag()); values = parser.ConvertToArrayList(filledForm, result.HttpBody, updateElementNames); } // Post Data Hashtable if ( test.UnitTestDataType == UnitTestDataContainer.PostDataHashtable ) { string postdata = ((PostSessionRequest)sessionRequest).PostData; // convert post data to hashtable FormConverter converter = new FormConverter(); Hashtable postDataHash = converter.ConvertPostDataString(postdata); // Applies test to post data hashtable Hashtable filledPostData = ApplyTestToPostData(test, (Hashtable)postDataHash.Clone()); values = converter.ConvertPostDataArrayList(filledPostData); } // Cookies if ( test.UnitTestDataType == UnitTestDataContainer.Cookies ) { cookies = ApplyTestToCookies(test, cookies); } // Url if( test.UnitTestDataType == UnitTestDataContainer.NoPostData ) { // a url test requestUrl = ApplyTestToUrl(test, WebServerUriType.Normal,sessionRequest.Url).ToString(); } // ----------------------------------------------------------------------------------- #endregion if ( (test.UnitTestDataType == UnitTestDataContainer.HtmlFormTag ) || ( test.UnitTestDataType == UnitTestDataContainer.PostDataHashtable ) ) { // Set post data for report test.Arguments.PostData = ConvertToPostDataString(values); args.Detail = "Posted Data:" + test.Arguments.PostData; } if ( test.UnitTestDataType == UnitTestDataContainer.NoPostData ) { args.Detail = "Url query:" + requestUrl; } if ( test.UnitTestDataType == UnitTestDataContainer.Cookies ) { StringBuilder cookieQuery = new StringBuilder(); foreach ( Cookie cky in cookies ) { cookieQuery.Append("Name:" + cky.Name); cookieQuery.Append(", "); cookieQuery.Append("Value:" + cky.Value); cookieQuery.Append(";"); } args.Detail = "Cookie:" + cookieQuery.ToString(); } // // set last item flag // if ( availableTests == 1) // { // lastItem = true; // } // display the current processing this.DisplaySessionProcessEvent(this,args); // clone test item and set last item value HttpState httpRequestState = new HttpState(); httpRequestState.TestItem = unitTestItem.Clone(); //httpRequestState.IsLastItem = lastItem; // http settings HttpProperties httpSettings = null; if ( sessionRequest.RequestHttpSettings == null ) { httpSettings = unitTestGetRequest.ClientSettings; } else { httpSettings = sessionRequest.RequestHttpSettings; } if ( sessionRequest.RequestType == HttpRequestType.GET ) { // get request this.StartGetRequest(unitTestGetRequest, requestUrl, null, cookies, httpSettings, httpRequestState); } else { // post request this.StartPostRequest(unitTestPostRequest, requestUrl, values, cookies, httpSettings, httpRequestState); } //availableTests--; } #endregion }
public void HeaderSetup_WithDefaultUserAgent_UsesHttpRepl() { HttpState httpState = SetupHttpState(preferencesFileContent: ""); Assert.Equal("HTTP-REPL", httpState.Headers["User-Agent"].Single(), StringComparer.Ordinal); }
/// <summary> /// Executes the next safe request in order. /// </summary> /// <param name="state"> The HTTP state.</param> private void ExecuteNextSafeRequest(HttpState state) { // Get safe session and execute Session safeSession = this.SafeSession; int k = state.SessionRequestId; // http settings HttpProperties httpSettings = null; if ( safeSession.SessionRequests[k].RequestHttpSettings == null ) { httpSettings = safeSessionPostRequest.ClientSettings; } else { httpSettings = safeSession.SessionRequests[k].RequestHttpSettings; } if ( safeSession.SessionRequests[k].RequestType == HttpRequestType.GET ) { GetSessionRequest sessionRequest = (GetSessionRequest)safeSession.SessionRequests[k]; SessionCommandProcessEventArgs args = new SessionCommandProcessEventArgs("Requesting " + sessionRequest.Url.ToString()); args.ProcessType = SessionProcessType.SafeRequest; this.DisplaySessionProcessEvent(this, args); // Request, we only use url, http settings and cookies, because // IE doesn't returns and arraylist of values for GET requests. StartGetRequest(safeSessionGetRequest, sessionRequest.Url.ToString(), null, sessionRequest.RequestCookies, httpSettings, state); } }
public void GetEffectivePath_NoBaseAddressOrAbsoluteUri_ThrowsArgumentNullException() { Assert.Throws <ArgumentNullException>(() => HttpState.GetEffectivePath(null, "", "/NotAnAbsoluteUri")); }
/// <summary> /// Returns the result from the safe requests. /// </summary> /// <param name="sender"> The sender object.</param> /// <param name="e"> The ResponseEventArgs.</param> private void SafeSessionResult_EndHttp(object sender, ResponseEventArgs e) { // if is not running, then exit ... if ( this.IsRunning ) { // on return, run each test SessionRequest testRequest = e.State.TestSessionRequest; // add cookies to cookie manager cookieManager.AddCookies(e.Response.CookieCollection); Uri responseUri = (Uri)e.Response.ResponseHeaderCollection["Response Uri"]; // // Update Session Headers // if ( ( testRequest.Url.ToString() != responseUri.ToString() ) && ( responseUri != null ) ) // { // // Updates the Test Url with the response uri from the safe session // testRequest.Url = responseUri; // } try { #region Apply Tests and execute safe requests if ( testRequest.WebUnitTest != null ) { if ( testRequest.WebUnitTest.Tests != null ) { #region Apply tests if ( ( testRequest.WebUnitTest.Tests.Count > 0 ) ) { // matchId > currentRestart // apply tests ApplyRequestTests(testRequest, e.Response); } #endregion // add safe test report // HtmlUnitTestReport report = rptBuilder.BuildReport(e); // reports.Add(report); HttpState state = new HttpState(); state.SessionRequestId = e.State.SessionRequestId + 1; // if equal, then we stop to request and enabled the report. if ( state.SessionRequestId == this.SafeSession.SessionRequests.Count ) { // end // show report UnitTestSessionReportEventArgs args = new UnitTestSessionReportEventArgs(); args.Report = reports; this.CreateReportEvent(this, args); } else { // continue state.TestSessionRequest = this.TestSession.SessionRequests[state.SessionRequestId]; ResponseBuffer inputResponse = e.Response; // call safe request backtracking else call next safe request directly if ( this.SafeSession.AllowSafeRequestBacktracking ) { this.ExecuteNextSafeRequestById(state, inputResponse, state.SessionRequestId); } else { this.ExecuteNextSafeRequest(state, inputResponse); } } } } #endregion } catch ( WebException web) { Utils.ExceptionHandler.RegisterException(web); AbortSessionRun(web.Message); } catch (Exception ex) { Utils.ExceptionHandler.RegisterException(ex); AbortSessionRun(ex.Message); } } else { // abort requests this.safeSessionGetRequest.SafeAbortRequest(); this.safeSessionPostRequest.SafeAbortRequest(); } }
public static IEnumerable <string> GetValueCompletions(string method, string path, string header, string prefix, HttpState programState) { switch (header.ToUpperInvariant()) { case "CONTENT-TYPE": IEnumerable <string> results = programState.GetApplicableContentTypes(method, path) ?? DefaultContentTypesList; if (results is null) { return(null); } return(results.Where(x => !string.IsNullOrEmpty(x) && x.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))); default: return(null); } }
private bool OpenConnection() { lock(this) { if(_isConnectionOpened) return false; _isConnectionOpened = true; } InitClient(); InitMethod(); _state = _stateCache.GetHttpState(); //todo insert needed Authontication, Cookies info to state! _method.setDoAuthentication(this.PreAuthenticate); InitHostConfig(); InitCredentials(); InitProxyCredentials(); if(this.ProtocolVersion == HttpVersion.Version11) _method.getParams().setVersion(mainsoft.apache.commons.httpclient.HttpVersion.HTTP_1_1); else if(ProtocolVersion == HttpVersion.Version10) _method.getParams().setVersion(mainsoft.apache.commons.httpclient.HttpVersion.HTTP_1_0); else throw new ProtocolViolationException("Unsupported protocol version: " + ProtocolVersion); if(!(_method is mainsoft.apache.commons.httpclient.methods.EntityEnclosingMethod)) { _method.setFollowRedirects(this.AllowAutoRedirect); } else { if(!AllowWriteStreamBuffering && _contentLength < 0 && !SendChunked) throw new ProtocolViolationException(); if(SendChunked) ((EntityEnclosingMethod)_method).setContentChunked(SendChunked); } if(MaxAutoRedirections != _defaultMaxRedirectsNum) { _method.getParams().setParameter(HttpClientParams.MAX_REDIRECTS, new java.lang.Integer(MaxAutoRedirections)); } foreach(string k in Headers) { if(String.Compare (k, "connection", StringComparison.InvariantCultureIgnoreCase) == 0) continue; string val = Headers[k]; val = (val == null) ? "" : val; _method.setRequestHeader(k, val); } if (this.CookieContainer != null) { string cookieHeader = this.CookieContainer.GetCookieHeader (this.GetOriginalAddress()); if (cookieHeader != "") _method.setRequestHeader("Cookie", cookieHeader); } SetConnectionHeader(Headers["Connection"]); _method.getParams().setSoTimeout(ReadWriteTimeout); return true; }
public ResponseConfig(HttpState state) : base(state) { }
private void HandleWebException(WebException we, HttpState httpState) { HttpStatusCode statusCode = GetErrorCode(we.Response as HttpWebResponse); // It hasn't an active INTERNET connection (resolve error), // or the connection was LOST after http request was sent (connect failure) // It disconnects automatically and stops. So you don't need to call Disconnect(). if (we.Status == WebExceptionStatus.NameResolutionFailure || we.Status == WebExceptionStatus.ProxyNameResolutionFailure || we.Status == WebExceptionStatus.ConnectFailure || we.Status == WebExceptionStatus.ProtocolError) { isWebRequestInProcess = false; Disconnect(); OnConnectingException(we); return; } // If the session corrupted (BadRequest), // or the first http request (Open) is timed out then reconnect: We passed resolve/connect failures. // IMPORTANT: Don't send httpState.OutgoingData again... if (statusCode == HttpStatusCode.BadRequest || (we.Status == WebExceptionStatus.Timeout && httpState.PollAction == HttpPollAction.Open)) { isWebRequestInProcess = false; Disconnect(); Connect(); return; } switch (we.Status) { // If a soft error occurs, re-send the last packet. case WebExceptionStatus.ConnectionClosed: case WebExceptionStatus.PipelineFailure: case WebExceptionStatus.KeepAliveFailure: case WebExceptionStatus.Timeout: case WebExceptionStatus.SendFailure: case WebExceptionStatus.ReceiveFailure: { isWebRequestInProcess = false; // IN MIDDLE SOFT ERROR // Outgoing data wasn't sent, we can re-send... if (httpState.OutgoingData != null && httpState.OutgoingData.Length > 0) { Send(httpState.OutgoingData, httpState.UserState); } else { // AT END SOFT ERROR // Outgoing data was sent, but an error occured while closing (KeepAliveFailure) // Anyway this is not fatal, next time we will send PNG... return; } } break; case WebExceptionStatus.SecureChannelFailure: { OnConnectionException(we); goto default; } case WebExceptionStatus.RequestCanceled: case WebExceptionStatus.UnknownError: default: { OnDisconnected(); Trace.WriteLineIf(Settings.TraceSwitch.TraceError, "HTTP Error: " + we.ToString(), GetType().Name); break; } } }
protected RequestOrResponseConfig(HttpState state) { State = state; }
public TransitionState(HttpState state, IReadOnlyDictionary <string, HttpState> routes) { State = state; Routes = routes; }
private void Setup(string commandText, out MockedShellState mockedShellState, out HttpState httpState, out ICoreParseResult parseResult) { mockedShellState = new MockedShellState(); IFileSystem fileSystem = new RealFileSystem(); IUserProfileDirectoryProvider userProfileDirectoryProvider = new UserProfileDirectoryProvider(); IPreferences preferences = new UserFolderPreferences(fileSystem, userProfileDirectoryProvider, null); parseResult = CoreParseResultHelper.Create(commandText); HttpClient httpClient = new HttpClient(); httpState = new HttpState(preferences, httpClient); }
private void EndGetRequestStreamCallback(IAsyncResult ar) { HttpState httpState = (HttpState)ar.AsyncState; try { using (Stream stream = httpState.Request.EndGetRequestStream(ar)) { stream.Write(httpState.OutgoingData, 0, httpState.OutgoingData.Length); // We must re-send the data when connection error is not fatal. // So, don't set here: httpState.OutgoingData = null; } WebResponse response = httpState.Request.GetResponse(); httpState.Request = null; #region Read Headers lock (SyncObject) { foreach (string header in response.Headers.AllKeys) { switch (header) { case "X-MSN-Host": host = response.Headers.Get(header); break; case "X-MSN-Messenger": string text = response.Headers.Get(header); string[] parts = text.Split(';'); foreach (string part in parts) { string[] elements = part.Split('='); switch (elements[0].Trim()) { case "SessionID": SessionID = elements[1]; break; case "GW-IP": GatewayIP = elements[1]; break; case "Session": if ("close" == elements[1]) { // Session has just closed (OUT/SignoutFromHere) // We will receive 400 error if we send a new data. connected = false; // We will fire Disconnected event after all content was read. // See the finally block of this function. } break; case "Action": break; } } break; } } isWebResponseHeadersProcessed = true; } #endregion MemoryStream responseReadStream = new MemoryStream(); int read = 0; try { using (Stream responseStream = response.GetResponseStream()) { byte[] readBuffer = new byte[8192]; do { read = responseStream.Read(readBuffer, 0, readBuffer.Length); if (read > 0) { responseReadStream.Write(readBuffer, 0, read); } }while (read > 0); // We read all incoming data and no error occured. // Now, it is time to set null to NOT resend the data. httpState.OutgoingData = null; // This can close "keep-alive" connection, but it isn't important. // We handle soft errors and we send the last packet again if it is necessary. try { response.Close(); response = null; } catch (Exception) { } } } catch (IOException ioe) { if (ioe.InnerException is WebException) { throw ioe.InnerException; } throw ioe; } finally { isWebRequestInProcess = false; } // Yay! No http errors (soft or hard) OnAfterRawDataSent(httpState.UserState); // Don't catch exceptions here. responseReadStream.Flush(); byte[] rawData = responseReadStream.ToArray(); DispatchRawData(rawData); responseReadStream.Close(); responseReadStream = null; } catch (WebException we) { HandleWebException(we, httpState); } finally { lock (SyncObject) { if (connected && (!isWebRequestInProcess) && (!pollTimer.Enabled)) { pollTimer.Start(); } else if (!connected) { // All content was read. It is time to fire event if not connected. // "connected" is set as "false" when Session=close received. Disconnect(); // This won't fire OnDisconnected event, because connected=false, OnDisconnected(); // so we fire event here to ensure event fired. } } } }
private void ArrangeInputs(string commandText, out MockedShellState shellState, out HttpState httpState, out ICoreParseResult parseResult, out IPreferences preferences, string fileContents = null) { ArrangeInputs(commandText, baseAddress: null, path: null, urlsWithResponse: null, out shellState, out httpState, out parseResult, out _, out preferences, readBodyFromFile: fileContents is object, fileContents: fileContents); }
public override void Send(byte[] outgoingData, object userState) { if (opened || (null != (outgoingData = GetOpenOrClosePacket(outgoingData)))) { if (isWebRequestInProcess) { lock (SyncObject) { sendingQueue.Enqueue(new QueueState(outgoingData, userState)); action = HttpPollAction.None; } } else { isWebRequestInProcess = true; HttpPollAction oldAction = action; lock (SyncObject) { action = HttpPollAction.None; if (pollTimer.Enabled) { pollTimer.Stop(); } } HttpWebRequest request = (HttpWebRequest)WebRequest.Create(GenerateURI(oldAction)); ConnectivitySettings.SetupWebRequest(request); request.Accept = "*/*"; request.Method = "POST"; request.KeepAlive = true; request.AllowAutoRedirect = false; request.AllowWriteStreamBuffering = false; request.ContentLength = outgoingData.Length; request.Headers.Add("Pragma", "no-cache"); // Set timeouts (10+40=50) = PNG average interval request.Timeout = 10000; // 10 seconds for GetRequestStream(). Timeout error occurs when the server is busy. request.ReadWriteTimeout = 40000; // 40 seconds for Read()/Write(). PNG interval is 45-60, so timeout must be <= 40. // Bypass msnp blockers request.ContentType = "text/html; charset=UTF-8"; request.UserAgent = @"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.65 Safari/535.11"; request.Headers.Add("X-Requested-Session-Content-Type", "text/html"); // Enable GZIP request.AutomaticDecompression = Settings.EnableGzipCompressionForWebServices ? DecompressionMethods.GZip : DecompressionMethods.None; // Don't block current thread. HttpState httpState = new HttpState(request, outgoingData, userState, oldAction); request.BeginGetRequestStream(EndGetRequestStreamCallback, httpState); } } }
public void GetBearer_NoTokenSet_ReturnsNull() { HttpState httpState = SetupHttpState(); Assert.Null(httpState.BearerToken); }