private void DataReceived(object sender, SerialDataReceivedEventArgs e) { int size = _reader.ReadInt16(); byte[] payLoad = _reader.ReadBytes(size); ResponseBuffer.TryAdd(Response.GetId(payLoad), payLoad); }
protected virtual bool ProcessPortResponse() { bool complete = false; TimeoutTimer.Disarm(); if (Test.Steps[CurrentStep].Response != null) { if (!string.IsNullOrEmpty(Test.Steps[CurrentStep].Response.Header)) { int index = ResponseBuffer.LastIndexOf(Test.Steps[CurrentStep].Response.Header); if (index >= 0) { ResponseBuffer = ResponseBuffer.Substring(index); } } } if (!string.IsNullOrEmpty(ResponseBuffer)) { qf4net.QF.Instance.Publish(new RecorderEvent(QFSignal.RecorderRecord, Name, CurrentStep + 1, ResponseBuffer)); } ResponseProcessor.Process(Test.Name, Test.Steps[CurrentStep], ResponseBuffer); ResponseBuffer = string.Empty; complete = true; return(complete); }
public void Reset() { ResponseBuffer.Clear(); ArgumentBytes = 0; Argument = 0; CommandNumber = 0; State = SpiState.WaitingForCommand; }
public void Clean() { if (ResponseBuffer != null) { ResponseBuffer.FinishedWriting(); ResponseBuffer = null; } }
public void Clean() { if (ResponseBuffer != null) { ResponseBuffer.Close(); ResponseBuffer = null; } }
private void StartMessageBuffer() { byte[] buffer = new byte[2]; Task.Factory.StartNew(async() => { while (!CancellationToken.IsCancellationRequested) { await _stream.ReadAsync(buffer, 0, buffer.Length, CancellationToken); short size = (short)(buffer[1] | buffer[2] << 8); if (size > 0) { byte[] payLoad = new byte[size]; await _stream.ReadAsync(payLoad, 0, payLoad.Length); ResponseBuffer.TryAdd(Response.GetId(payLoad), payLoad); } } }, CancellationToken, TaskCreationOptions.LongRunning, TaskScheduler.Current); Task.Factory.StartNew(async() => { while (!CancellationToken.IsCancellationRequested) { try { Command command; if (NoReplyCommandBuffer.TryDequeue(out command)) { await _stream.WriteAsync(command.PayLoad, 0, command.PayLoad.Length); _stream.Flush(); ResponseBuffer.TryAdd(command.Id, null); } if (CommandBuffer.TryDequeue(out command)) { await _stream.WriteAsync(command.PayLoad, 0, command.PayLoad.Length); _stream.Flush(); int retry = 0; while (!ResponseBuffer.ContainsKey(command.Id) && retry < 20) { await Task.Delay(50, CancellationToken); retry++; } } if (EventBuffer.TryDequeue(out command)) { await _stream.WriteAsync(command.PayLoad, 0, command.PayLoad.Length); _stream.Flush(); } } catch (TaskCanceledException) { } } }, CancellationToken, TaskCreationOptions.LongRunning, TaskScheduler.Current); }
/// <summary> /// Form that manages unit tests for a form. /// </summary> /// <param name="form"></param> /// <param name="sessionData"></param> public UnitTestManagerForm(HtmlFormTag form, ResponseBuffer sessionData, InspectorConfiguration config) { // // Required for Windows Form Designer support // InitializeComponent(); this.inspectorConfig = config; this.CurrentForm = form; this.lblFormName.Text = form.Name; this.lblUrl.Text = ((Uri)sessionData.RequestHeaderCollection["Request Uri"]).AbsoluteUri; }
private void StartMessageBuffer() { Task.Factory.StartNew(async() => { while (!CancellationToken.IsCancellationRequested) { byte[] payLoad = await Read(); if (payLoad != null) { ResponseBuffer.TryAdd(Response.GetId(payLoad), payLoad); } } }, CancellationToken, TaskCreationOptions.LongRunning, TaskScheduler.Current); Task.Factory.StartNew(async() => { while (!CancellationToken.IsCancellationRequested) { try { Command command; if (NoReplyCommandBuffer.TryDequeue(out command)) { await Write(command); ResponseBuffer.TryAdd(command.Id, null); } if (CommandBuffer.TryDequeue(out command)) { await Write(command); int retry = 0; while (!ResponseBuffer.ContainsKey(command.Id) && retry < 20) { await Task.Delay(50, CancellationToken); retry++; } } if (EventBuffer.TryDequeue(out command)) { await Write(command); } } catch (TaskCanceledException) { } } }, CancellationToken, TaskCreationOptions.LongRunning, TaskScheduler.Current); }
protected void Clear() { ResponseBuffer.Clear(); while (NoReplyCommandBuffer.Count > 0) { NoReplyCommandBuffer.TryDequeue(out _); } while (CommandBuffer.Count > 0) { CommandBuffer.TryDequeue(out _); } while (EventBuffer.Count > 0) { EventBuffer.TryDequeue(out _); } }
private void StartMessageBuffer() { Task.Factory.StartNew(async() => { while (!CancellationToken.IsCancellationRequested) { try { Command command; if (NoReplyCommandBuffer.TryDequeue(out command)) { lock (_serialPort) _serialPort.Write(command.PayLoad, 0, command.PayLoad.Length); ResponseBuffer.TryAdd(command.Id, null); } if (CommandBuffer.TryDequeue(out command)) { lock (_serialPort) _serialPort.Write(command.PayLoad, 0, command.PayLoad.Length); int retry = 0; while (!ResponseBuffer.ContainsKey(command.Id) && retry < 20) { await Task.Delay(50, CancellationToken); retry++; } } if (EventBuffer.TryDequeue(out command)) { lock (_serialPort) _serialPort.Write(command.PayLoad, 0, command.PayLoad.Length); } } catch (TaskCanceledException) { } } }, CancellationToken, TaskCreationOptions.LongRunning, TaskScheduler.Current); }
/// <summary> /// Gets the meta tag url from http content. /// </summary> /// <param name="httpResponse"> The response buffer.</param> /// <param name="url"> The response uri.</param> /// <returns> An url found in the META tag.</returns> private Uri GetMetaTagUrl(ResponseBuffer httpResponse, Uri url) { // check if html content has any META tag. string metaUrl = parser.GetMetaRedirectUrlString(httpResponse.HttpBody); Uri newUrl = null; if ( metaUrl.Length > 0 ) { if ( metaUrl.ToLower().StartsWith("http") ) { try { newUrl = new Uri(metaUrl); } catch { newUrl = url; } } else { // make relative newUrl = new Uri(UriResolver.ResolveUrl(url, metaUrl)); } } return newUrl; }
/// <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 } }
/// <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 }
/// <summary> /// Fills the headers in the response buffer. /// </summary> /// <param name="sender"> The sender object.</param> /// <param name="e"> The event arguments.</param> private void InspectorPipeline_FillHeaders(object sender, EventArgs e) { ResponseBuffer respBuffer = null; HttpWebRequest webRequest = HttpStateData.HttpRequest; HttpWebResponse webResponse = HttpStateData.HttpResponse; if ( CompareString.Compare(webRequest.Method,"get") ) { respBuffer = new ResponseBuffer(HttpRequestType.GET); } else if ( CompareString.Compare(webRequest.Method,"post") ) { respBuffer = new ResponseBuffer(HttpRequestType.POST); } else if ( CompareString.Compare(webRequest.Method,"put") ) { respBuffer = new ResponseBuffer(HttpRequestType.PUT); } else if ( CompareString.Compare(webRequest.Method,"head") ) { respBuffer = new ResponseBuffer(HttpRequestType.HEAD); } else if ( CompareString.Compare(webRequest.Method,"delete") ) { respBuffer = new ResponseBuffer(HttpRequestType.DELETE); } else if ( CompareString.Compare(webRequest.Method,"trace") ) { respBuffer = new ResponseBuffer(HttpRequestType.TRACE); } else if ( CompareString.Compare(webRequest.Method,"options") ) { respBuffer = new ResponseBuffer(HttpRequestType.OPTIONS); } respBuffer.StatusCode = (int)webResponse.StatusCode; respBuffer.StatusDescription = webResponse.StatusDescription; if ( webResponse.ProtocolVersion == HttpVersion.Version11 ) { respBuffer.Version="1.1"; } else { respBuffer.Version="1.0"; } // Request Header Collection BufferBuilder.FillRequestHeader(respBuffer,webRequest.Headers,webRequest); // Header Collection BufferBuilder.FillResponseHeader(respBuffer,webRequest,webResponse.Headers,webResponse); this.HttpResponseData = respBuffer; }