/// <summary>
        /// Fills the HTTP Body.
        /// </summary>
        /// <param name="resp"> The ResponseBuffer type.</param>
        /// <param name="stm"> The Stream containing the HTTP Body.</param>
        /// <returns> An updated ResponseBuffer type containing the change.</returns>
        public static ResponseBuffer FillHttpBody(ResponseBuffer resp, Stream stm)
        {
            // used to build entire input
            StringBuilder buffer = new StringBuilder();

            // used on each read operation
            byte[] buf = new byte[8192];

            string tempString = null;
            int count = 0;

            do
            {
                if ( !stm.CanRead)
                {
                    break;
                }

                // fill the buffer with data
                count = stm.Read(buf, 0, buf.Length);

                // make sure we read some data
                if (count != 0)
                {
                    // translate from bytes to ASCII text
                    tempString = Encoding.ASCII.GetString(buf, 0, count);

                    // continue building the string
                    buffer.Append(tempString);
                }
            }
            while (count > 0); // any more data to read?
            resp.HttpBody = buffer.ToString(); // writer.ToString();
            return resp;
        }
        /// <summary>
        /// Fills the error message and returns the ResponseBuffer.
        /// </summary>
        /// <param name="errorMessage"> An error message explaining the cause of error.</param>
        /// <param name="httpState"> The HTTP State</param>
        /// <returns> A ResponseBuffer type.</returns>
        internal static ResponseBuffer FillErrorBuffer(string errorMessage, HttpState httpState)
        {
            //StringBuilder textStream = new StringBuilder();
            ResponseBuffer respBuffer = new ResponseBuffer();

            respBuffer.ErrorMessage = errorMessage;
            return respBuffer;
        }
        /// <summary>
        /// Creates a new FormsEditor.
        /// </summary>
        /// <param name="forms"> Form collection to load.</param>
        /// <param name="sessionData"> ResponseBuffer data.</param>
        /// <param name="parserSettings"> Parser Settings.</param>
        /// <param name="inspectorConfiguration"> The inspector configuration.</param>
        public FormsEditor(HtmlFormTagCollection forms, ResponseBuffer sessionData, HtmlParserProperties parserSettings, InspectorConfiguration inspectorConfiguration)
            : this()
        {
            this.SessionData = sessionData;
            this.InspectorConfig = inspectorConfiguration;

            // set parser settings
            _parserSettings = parserSettings;

            // Load tree
            LoadFormTree(forms);
        }
        /// <summary>
        /// Fills the ResponseBuffer.
        /// </summary>
        /// <param name="response"> The HttpWebResponse type.</param>
        /// <param name="hwr"> The HttpWebRequest type.</param>
        /// <param name="clientSettings"> The http settings.</param>
        /// <param name="httpState"> The Http state.</param>
        /// <returns> A ResponseBuffer type.</returns>
        internal static ResponseBuffer FillResponseBuffer(HttpWebResponse response, HttpWebRequest hwr, HttpProperties clientSettings, HttpState httpState)
        {
            ResponseBuffer respBuffer = null;

            if ( CompareString.Compare(hwr.Method,"get") )
            {
                respBuffer = new ResponseBuffer(HttpRequestType.GET);
            }
            else
            {
                respBuffer = new ResponseBuffer(HttpRequestType.POST);
            }

            respBuffer.StatusCode = (int)response.StatusCode;
            respBuffer.StatusDescription=response.StatusDescription;

            if ( response.ProtocolVersion == HttpVersion.Version11  )
            {
                respBuffer.Version="1.1";
            }
            else
            {
                respBuffer.Version="1.0";
            }

            // Request Header Collection
            BufferBuilder.FillRequestHeader(respBuffer,hwr.Headers,hwr);

            // Header Collection
            BufferBuilder.FillResponseHeader(respBuffer,hwr,response.Headers,response);

            // Cookie collection
            response.Cookies = hwr.CookieContainer.GetCookies(hwr.RequestUri);
            BufferBuilder.FillCookieData(respBuffer,response.Cookies);

            Stream stm = response.GetResponseStream();
            BufferBuilder.FillHttpBody(respBuffer,stm);
            stm.Close();

            if ( response!=null )
            {
                response.Close();
            }

            return respBuffer;
        }
        /// <summary>
        /// Fills the cookie data collection.
        /// </summary>
        /// <param name="resp"> The ResponseBuffer type.</param>
        /// <param name="cookies"> Cookie collection. </param>
        /// <returns> An updated ResponseBuffer type containing the change.</returns>
        public static ResponseBuffer FillCookieData(ResponseBuffer resp, CookieCollection cookies)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append("---------------------");
            sb.Append("=COOKIES=");
            sb.Append("---------------------\r\n");
            foreach (Cookie cky in cookies)
            {
                    // text
                    sb.Append(cky.Name);
                    sb.Append(": ");
                    sb.Append(cky.Value);
                    sb.Append("\r\n");
            }

            resp.CookieCollection = cookies;
            resp.CookieData = sb.ToString();

            return resp;
        }
        /// <summary>
        /// Displays the executed session run.
        /// </summary>
        /// <param name="resp"> The ResponseBuffer type.</param>
        /// <param name="lastItem"> The last item flag.</param>
        private void TestRun(ResponseBuffer resp, bool lastItem)
        {
            this.textViewerForm.EditorText  += resp.HttpBody + "\r\n\r\n";
            this.textViewerForm.EditorText  += resp.ResponseHeader + "\r\n\r\n";
            this.textViewerForm.EditorText  += resp.CookieData + "\r\n\r\n";

            //			if ( lastItem )
            //			{
            //				_scriptingDataDesigner.UpdateRunTestMenu(true);
            //			}
        }
        /// <summary>
        /// Sends POST Requests.
        /// </summary>
        /// <param name="postUri"> Post uri.</param>
        /// <param name="values"> Values to post.</param>
        /// <param name="stateData"> ResponseBuffer from site.</param>
        /// <param name="cookies"> Cookies from site.</param>
        /// <param name="formTag"> The HtmlFormTag value.</param>
        private void GetPostRequest(string postUri,ArrayList values,ResponseBuffer stateData, CookieCollection cookies, HtmlFormTag formTag)
        {
            // disable
            DisableFormView();

            // add Messaging
            ShowPostRequestMessage(postUri);

            if ( values != null )
                ShowPostedData(values);

            try
            {
                InitializeHttpCommands();
                postForm.ProxySettings = this.ProxySettings;

                if ( formTag.Enctype.ToLower(System.Globalization.CultureInfo.InvariantCulture) == "multipart/form-data" )
                {
                    HttpRequestResponseContext context = new HttpRequestResponseContext();
                    PostWebRequest postReq = new PostWebRequest();
                    postReq.Form.ReadHtmlFormTag(formTag);
                    Ecyware.GreenBlue.Engine.Scripting.Cookies c = new Cookies(cookies);
                    postReq.Cookies =  c.GetCookies();
                    postReq.RequestType = HttpRequestType.POST;
                    postReq.Url = postUri;
                    postReq.RequestHttpSettings = this.GetHttpPropertiesFromPanel();
                    context.Request = postReq;

                    postForm.StartAsyncHttpPostFileUpload(context);
                }
                else
                {
                    postForm.StartAsyncHttpPost(postUri,this.GetHttpPropertiesFromPanel(),values,cookies);
                }
            }
            catch ( Exception ex )
            {
                this.txtMessaging.SelectionColor = Color.Red;
                this.txtMessaging.SelectedText = "Html Browser Error: " + ex.Message + "\r\n";

                textViewerForm.EditorText = ex.Message;
                // enable
                EnableFormView();
                this.navForm.StopNavigation();
                this.StopProgressBarEvent(this,new ProgressBarControlEventArgs("Ready"));
            }
        }
        /// <summary>
        /// Sends GET requests.
        /// </summary>
        /// <param name="url"> Post uri.</param>
        /// <param name="stateData"> ResponseBuffer from site.</param>
        /// <param name="cookies"> Cookies from site.</param>
        private void GetHttpRequest(string url,ResponseBuffer stateData, CookieCollection cookies)
        {
            DisableFormView();

            // add Messaging
            ShowGetRequestMessage(url);

            try
            {
                if (stateData==null)
                {
                    stateData=new ResponseBuffer();
                }

                InitializeHttpCommands();
                getForm.ProxySettings = this.ProxySettings;
                getForm.StartAsyncHttpGet(url, this.GetHttpPropertiesFromPanel(), null, cookies, false);
            }
            catch (Exception ex)
            {
                this.txtMessaging.SelectionColor = Color.Red;
                this.txtMessaging.SelectedText = "Html Browser Error: " + ex.Message  + "\r\n";

                textViewerForm.EditorText  = ex.Message;
                // enable
                EnableFormView();
                this.navForm.StopNavigation();
                this.StopProgressBarEvent(this,new ProgressBarControlEventArgs("Ready"));
            }
        }
        /// <summary>
        /// Fills the Request and Response ListViews
        /// </summary>
        /// <param name="response"> The current response buffer.</param>
        private void FillListViews(ResponseBuffer response)
        {
            // Clear lists
            lvResponseHeader.Items.Clear();
            // lvRequestHeader.Items.Clear();

            // add Messaging
            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            txtMessaging.SelectionColor = Color.Teal;
            txtMessaging.SelectedText = "Server Response [" + DateTime.Now.ToShortTimeString() + "]: ";

            sb.Append("HTTP/");
            sb.Append(response.Version);
            sb.Append(" ");
            sb.Append(response.StatusCode);
            sb.Append(" ");
            sb.Append(response.StatusDescription);
            sb.Append("\r\n");

            txtMessaging.SelectionColor = Color.Black;
            txtMessaging.SelectedText = sb.ToString();

            txtMessaging.Focus();
            txtMessaging.SelectionStart = txtMessaging.Text.Length;
            txtMessaging.SelectionLength = 0;
            txtMessaging.ScrollToCaret();

            foreach (DictionaryEntry de in response.ResponseHeaderCollection)
            {
                ListViewItem lvi = new ListViewItem();
                lvResponseHeader.Items.Add(lvi);

                lvi.Text = (string)de.Key;
                lvi.SubItems.Add(Convert.ToString(de.Value));
            }
        }
        /// <summary>
        /// Adds the request headers to the report.
        /// </summary>
        /// <param name="parentRow"> The ResponseDocumentRow.</param>
        /// <param name="report"> The HtmlUnitTestReport type.</param>
        /// <param name="responseBuffer"> The response buffer.</param>
        /// <param name="httpProperties"> The Http Properties type.</param>
        private void AddRequestHeaders(HtmlUnitTestReport.ResponseDocumentRow parentRow,HtmlUnitTestReport report, ResponseBuffer responseBuffer, HttpProperties httpProperties)
        {
            Ecyware.GreenBlue.ReportEngine.HtmlUnitTestReport.RequestHeaderRow reqHeaderRow = report.RequestHeader.NewRequestHeaderRow();

            reqHeaderRow.SetParentRow(parentRow);
            report.RequestHeader.AddRequestHeaderRow(reqHeaderRow);

            Ecyware.GreenBlue.ReportEngine.HtmlUnitTestReport.RequestItemsRow row = null;

            if ( httpProperties.Accept != null )
            {
                row = report.RequestItems.NewRequestItemsRow();
                row.Name = "Accept";
                row.Value = httpProperties.Accept;
                row.SetParentRow(reqHeaderRow);
                report.RequestItems.AddRequestItemsRow(row);
            }

            row = report.RequestItems.NewRequestItemsRow();
            row.Name = "Content length";
            row.Value = httpProperties.ContentLength.ToString();
            row.SetParentRow(reqHeaderRow);
            report.RequestItems.AddRequestItemsRow(row);

            if ( httpProperties.ContentType != null )
            {
                row = report.RequestItems.NewRequestItemsRow();
                row.Name = "Content type";
                row.Value = httpProperties.ContentType;
                row.SetParentRow(reqHeaderRow);
                report.RequestItems.AddRequestItemsRow(row);
            }

            row = report.RequestItems.NewRequestItemsRow();
            row.Name = "If modified since";
            row.Value = httpProperties.IfModifiedSince.ToString();
            row.SetParentRow(reqHeaderRow);
            report.RequestItems.AddRequestItemsRow(row);

            row = report.RequestItems.NewRequestItemsRow();
            row.Name = "Keep alive";
            row.Value = httpProperties.KeepAlive.ToString();
            row.SetParentRow(reqHeaderRow);
            report.RequestItems.AddRequestItemsRow(row);

            if ( httpProperties.MediaType != null )
            {
                row = report.RequestItems.NewRequestItemsRow();
                row.Name = "Media type";
                row.Value = httpProperties.MediaType;
                row.SetParentRow(reqHeaderRow);
                report.RequestItems.AddRequestItemsRow(row);
            }

            row = report.RequestItems.NewRequestItemsRow();
            row.Name = "Pipeline";
            row.Value = httpProperties.Pipeline.ToString();
            row.SetParentRow(reqHeaderRow);
            report.RequestItems.AddRequestItemsRow(row);

            if ( httpProperties.Referer != null )
            {
                row = report.RequestItems.NewRequestItemsRow();
                row.Name = "Referer";
                row.Value = httpProperties.Referer;
                row.SetParentRow(reqHeaderRow);
                report.RequestItems.AddRequestItemsRow(row);
            }

            row = report.RequestItems.NewRequestItemsRow();
            row.Name = "Send chunked";
            row.Value = httpProperties.SendChunked.ToString();
            row.SetParentRow(reqHeaderRow);
            report.RequestItems.AddRequestItemsRow(row);

            if ( httpProperties.TransferEncoding != null )
            {
                row = report.RequestItems.NewRequestItemsRow();
                row.Name = "Transfer encoding";
                row.Value = httpProperties.TransferEncoding;
                row.SetParentRow(reqHeaderRow);
                report.RequestItems.AddRequestItemsRow(row);
            }

            if ( httpProperties.UserAgent != null )
            {
                row = report.RequestItems.NewRequestItemsRow();
                row.Name = "User agent";
                row.Value = httpProperties.UserAgent;

                row.SetParentRow(reqHeaderRow);
                report.RequestItems.AddRequestItemsRow(row);
            }
        }
        private void InspectorPipeline_FillHeaders(object sender, EventArgs e)
        {
            ResponseBuffer respBuffer;
            HttpWebRequest webRequest = HttpStateData.HttpRequest;
            HttpWebResponse webResponse = HttpStateData.HttpResponse;

            if ( CompareString.Compare(webRequest.Method,"get") )
            {
                respBuffer = new ResponseBuffer(HttpRequestType.GET);
            }
            else
            {
                respBuffer = new ResponseBuffer(HttpRequestType.POST);
            }

            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);

            inspectorPipeline.ResponseData = respBuffer;
        }
 /// <summary>
 /// Adds a current web site to history.
 /// </summary>
 /// <param name="response"> The response buffer.</param>
 private void AddToHistory(ResponseBuffer response)
 {
     try
     {
         Uri requestUri = (Uri)response.RequestHeaderCollection["Request Uri"];
         sitesTree.AddHistoryNodeDisk(requestUri,response);
     }
     catch (Exception ex)
     {
         string message = ExceptionHandler.RegisterException(ex);
         MessageBox.Show(message,AppLocation.ApplicationName,MessageBoxButtons.OK,MessageBoxIcon.Error);
     }
 }
        /// <summary>
        /// Adds the cookies to the report.
        /// </summary>
        /// <param name="parentRow"> The ResponseDocumentRow.</param>
        /// <param name="report"> The HtmlUnitTestReport type.</param>
        /// <param name="responseBuffer"> The response buffer.</param>
        private void AddCookies(HtmlUnitTestReport.ResponseDocumentRow parentRow,HtmlUnitTestReport report, ResponseBuffer responseBuffer)
        {
            foreach (Cookie cookie in responseBuffer.CookieCollection)
            {
            //				HttpCookie cookie = (HttpCookie)de.Value;
                Ecyware.GreenBlue.ReportEngine.HtmlUnitTestReport.CookiesRow row = report.Cookies.NewCookiesRow();

                row.Domain = cookie.Domain;
                row.Name = cookie.Name;
                row.Path = cookie.Path;
                row.Value = cookie.Value;

                row.SetParentRow(parentRow);
                report.Cookies.AddCookiesRow(row);
            }
        }
        /// <summary>
        /// Parses the scripts tags found in buffer.
        /// </summary>
        /// <param name="buffer"> The ResponseBuffer.</param>
        /// <returns> An updated ResponseBuffer.</returns>
        internal static ResponseBuffer ParseScriptTags(ResponseBuffer buffer)
        {
            Regex getScripts = null;
            Regex getAttributes = null;

            if ( RegExpList == null )
            {
                // Remove Scripts regex
                RegexOptions options = RegexOptions.None;
                getScripts = new Regex(@"(?<header><(?i:script)[^>]*?)(/>|>(?<source>[\w|\t|\r|\W]*?)</(?i:script)>)",options);
                getAttributes = new Regex(@"(?<name>(\w+))=(""|')(?<value>.*?)(""|')",options);

                // add to list
                RegExpList = new Hashtable();
                RegExpList.Add("ScriptQuery",getScripts);
                RegExpList.Add("AttributesQuery",getAttributes);
            }
            else
            {
                getScripts = (Regex)RegExpList["ScriptQuery"];
                getAttributes = (Regex)RegExpList["AttributesQuery"];
            }

            // Get matches
            MatchCollection matches = getScripts.Matches(buffer.HttpBody);

            for(int i=0;i<matches.Count;i++)
            {
                HtmlScript scriptTag = new HtmlScript();
                string scriptHeader = matches[i].Groups["header"].Value;
                string scriptSource = matches[i].Groups["source"].Value;

                scriptTag.Text = scriptSource;

                // get attributes
                MatchCollection attributes = getAttributes.Matches(scriptHeader);
                foreach (Match m in attributes)
                {
                    string name = m.Groups["name"].Value;
                    string result = m.Groups["value"].Value;

                    if ( name.ToLower() == "language" )
                    {
                        scriptTag.Language=result.Trim();
                    }
                    if ( name.ToLower() == "src" )
                    {
                        scriptTag.Source = result.Trim();
                    }
                }
                buffer.Scripts.Add(scriptTag);
            }

            return buffer;
        }
        /// <summary>
        /// Updates the current session request.
        /// </summary>
        /// <param name="response"> The ResponseBuffer type.</param>
        private void UpdateSessionRequest(ResponseBuffer response)
        {
            if ( IsRecording )
            {
                SessionRequest sr = this.CurrentSessionRecording.SessionRequests[this.CurrentSessionRecording.SessionRequests.Count-1];

                sr.RequestHeaders = this.CurrentResponseBuffer.RequestHeaderCollection;
                sr.ResponseHeaders = this.CurrentResponseBuffer.ResponseHeaderCollection;
                sr.StatusCode = this.CurrentResponseBuffer.StatusCode;
                sr.StatusDescription = this.CurrentResponseBuffer.StatusDescription;
            }
        }
        /// <summary>
        /// Loads scripts with SRC attribute and adds it to the Script Collection in ResponseBuffer.
        /// </summary>
        /// <param name="requestUrl"> The top url.</param>
        /// <param name="response"> The ResponseBuffer.</param>
        /// <param name="clientSettings"> The http settings.</param>
        /// <returns> An updated ResponseBuffer.</returns>
        internal static ResponseBuffer LoadScriptsFromSrc(Uri requestUrl,ResponseBuffer response,HttpProperties clientSettings)
        {
            GetForm http = new GetForm();
            HtmlScriptCollection scripts = response.Scripts;

            for (int i=0;i<scripts.Count;i++)
            {
                if ( scripts[i].Source.Length!=0 )
                {
                    string src = scripts[i].Source;
                    string requestData = string.Empty;

                    requestData = UriResolver.ResolveUrl(requestUrl,src);

                    // add User Agent
                    clientSettings.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0)";

                    try
                    {
                        // load
                        ResponseBuffer result = http.StartSyncHttpGet(requestData,clientSettings,null,response.CookieCollection);

                        scripts[i].Text = result.HttpBody;
                    }
                    catch (Exception ex)
                    {
                        // TODO: Log this errors as SCRIPT loading failed error
                        System.Diagnostics.Debug.Write(ex.Message);
                    }
                }
            }

            return response;
        }
 /// <summary>
 /// Creates a new HistoryTreeNode and sets the text, url and data properties.
 /// </summary>
 /// <param name="text"> The node text.</param>
 /// <param name="url"> The uri.</param>
 /// <param name="data"> The ResponseBuffer data.</param>
 public HistoryTreeNode(string text, Uri url, ResponseBuffer data)
 {
     this.Text=text;
     this.Url=url;
     this.HttpSiteData=data;
 }
        /// <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.GetArrayList(filledForm, result.HttpBody, updateElementNames);
                }
                // Post Data Hashtable
                if ( test.UnitTestDataType == UnitTestDataContainer.PostDataHashtable )
                {
                    string postdata = ((PostSessionRequest)sessionRequest).PostData;

                    // TODO: Change to PostDataCollection method.
                    // convert post data to hashtable
                    FormConverter converter = new FormConverter();
                    //Hashtable postDataCollection = converter.ConvertPostDataStringHashtable(postdata);
                    PostDataCollection postDataCollection = converter.GetPostDataCollection(postdata);

                    // Applies test to post data hashtable
                    PostDataCollection filledPostData = ApplyTestToPostData(test, postDataCollection.Clone());
                    values = converter.GetArrayList(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  if ( sessionRequest.RequestType == HttpRequestType.POST )
                {
                    // post request
                    this.StartPostRequest(unitTestPostRequest,
                        requestUrl,
                        values,
                        cookies,
                        httpSettings,
                        httpRequestState);
                }

                //availableTests--;
            }
            #endregion
        }
        /// <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 the session cookies, instead of updating them.
        /// </summary>
        /// <param name="state"> The HTTP state.</param>
        /// <param name="responseBufferData"> The ResponseBuffer.</param>
        /// <param name="loopToId"> The request id to start the loop.</param>
        private void ExecuteNextSafeRequestById(HttpState state, ResponseBuffer responseBufferData, int loopToId)
        {
            CookieCollection cookies = null;
            //ResponseBuffer result = null;

            // Get safe session and execute
            Session safeSession = this.SafeSession;
            int k = -1;

            if ( state.SafeSessionRequestCurrentId == -1 )
            {
                state.SafeSessionRequestCurrentId = 0;
                k = 0;
            }
            else
            {
                k = state.SafeSessionRequestCurrentId;
            }

            // settings
            HttpProperties httpSettings = null;
            if ( safeSession.SessionRequests[k].RequestHttpSettings == null )
            {
                httpSettings = loopPostRequest.ClientSettings;
            }
            else
            {
                httpSettings = safeSession.SessionRequests[k].RequestHttpSettings;
            }

            if ( safeSession.SessionRequests[k].RequestType == HttpRequestType.GET  )
            {
            //				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"];
            //
            //						string redirectUri = UriResolver.ResolveUrl(url,location);
            //
            //						// get cookies ny url.
            //						 if ( this.SafeSession.IsCookieUpdatable )
            //						 {
            //							cookies = cookieManager.GetCookies(new Uri(redirectUri));
            //						 } else {
            //							cookies = safeSession.SessionRequests[k].RequestCookies;
            //						 }
            //
            //						// Request, we only use url, http settings and cookies, because
            //						// IE doesn't returns and arraylist of values for GET requests.
            //						this.StartGetRequest(this.loopGetRequest,
            //							redirectUri,
            //							null,
            //							cookies,
            //							httpSettings,
            //							state);
            //
            //
            //					}
            //					#endregion
            //				}
            //				else
            //				{
                    #region Get Request
                    // get cookies ny url.
                    if ( this.SafeSession.IsCookieUpdatable )
                    {
                        cookies = cookieManager.GetCookies(safeSession.SessionRequests[k].Url);
                    }
                    else
                    {
                        cookies = safeSession.SessionRequests[k].RequestCookies;
                    }

                    GetSessionRequest sessionRequest = (GetSessionRequest)safeSession.SessionRequests[k];

                    //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(this.loopGetRequest,
                        sessionRequest.Url.ToString(),
                        null,
                        cookies,
                        httpSettings,
                        state);
                    #endregion
                //}

            }
            else if ( safeSession.SessionRequests[k].RequestType == HttpRequestType.POST  )
            {
                #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 )
                {
                    cookies = cookieManager.GetCookies(new Uri(postUrl));
                }
                else
                {
                    cookies = sessionRequest.RequestCookies;
                }

                //SessionCommandProcessEventArgs args = new SessionCommandProcessEventArgs("Requesting " + sessionRequest.Url.ToString());

                //				// Posted Data Event Console Info
                ArrayList listValues = parser.GetArrayList(sessionRequest.Form, responseBufferData.HttpBody);
                //string posted = ConvertToPostDataString(listValues);
                //args.Detail = "Posted data: " + posted;
                //this.DisplaySessionProcessEvent(this, args);

                // Request post
                this.StartPostRequest(loopPostRequest,
                    postUrl,
                    listValues,
                    cookies,
                    httpSettings,
                    state);

                #endregion
            }

            // return result;
        }
        /// <summary>
        /// Fills the workspace with data retrieve from site.
        /// </summary>
        /// <param name="response">ResponseBuffer</param>
        public void FillWorkspace(ResponseBuffer response)
        {
            if (response.ErrorMessage != String.Empty)
            {
                // reset statusbar
                ChangeStatusBarPanelEvent(this, CleanStatusArgs);

                this.txtMessaging.SelectionColor = Color.Red;
                this.txtMessaging.SelectedText = "Html Browser Error: " + response.ErrorMessage  + "\r\n";

                // Show Error
                textViewerForm.EditorText  = response.ErrorMessage;

                // Stop progress
                this.StopProgressBarEvent(this, new ProgressBarControlEventArgs("Ready"));

                this.InspectorState = GBInspectorState.Error;
            }
            else
            {
                // Set Editor Text
                try
                {
                    textViewerForm.EditorText = response.HttpBody;

                    // save buffer, do not save before error message check
                    this.CurrentResponseBuffer = response;

                    // load forms editor if any
                    if ( formCollection != null )
                    {
                        DisplayForms(formCollection, false);
                    }

                    Uri responseUri = (Uri)response.ResponseHeaderCollection["Response Uri"];

                    // Get Settings from Panel
                    ClientProperties = this.GetHttpPropertiesFromPanel();

                    // Update referer
                    ClientProperties.Referer = responseUri.ToString();

                    // Load properties
                    LoadHttpProperties(this.ClientProperties);

                    // Add to history
                    AddToHistory(response);

                    //					// Add to cookies
                    //					cookieManager.AddCookies(response.CookieCollection);

                    // Fill Lists
                    FillListViews(response);
                    FillCookieListView(response.CookieCollection);

                    // Update address bar
                    RequestGetEventArgs requestArgs = new RequestGetEventArgs();
                    requestArgs.Url = responseUri.ToString();
                    this.UpdateAddressEvent(this, requestArgs);

                    // Update Session Request
                    UpdateSessionRequest(response);

                    EnableFormView();
                    this.InspectorState = GBInspectorState.Complete;

                    // Stop progress only if navigator CanLinkNavigate is true.
                    if ( navForm.CanLinkNavigate )
                    {
                        // reset statusbar
                        ChangeStatusBarPanelEvent(this, CleanStatusArgs);
                        // stop progress bar
                        this.StopProgressBarEvent(this,new ProgressBarControlEventArgs("Ready"));
                    }

                    // Location is found in Hashtable
                    if ( response.ResponseHeaderCollection.ContainsKey("Location") )
                    {
                        // Location is not empty
                        if ( ((string)response.ResponseHeaderCollection["Location"])!=String.Empty )
                        {
                            // Apply direct and log in recording sesion if any.
                            this.ApplyUrlRedirection();

                            // navForm.PendingRedirection = true;
                            //ChangeStatusBarPanelEvent(this,RedirectMessageArgs);
                        }
                    }
                }
                catch (Exception ex)
                {
                    string message = ExceptionHandler.RegisterException(ex);
                    MessageBox.Show(message,AppLocation.ApplicationName, MessageBoxButtons.OK,MessageBoxIcon.Error);
                }
            }
        }
        /// <summary>
        /// Checks for the unit test result.
        /// </summary>
        /// <param name="httpResponse"> The response buffer.</param>
        /// <param name="test"> The test.</param>
        /// <returns> A UnitTestResult.</returns>
        public UnitTestResult CheckTestResult(ResponseBuffer httpResponse, Test test)
        {
            this.HttpResponseBuffer = httpResponse;
            this.TestToEvaluate = test;

            return CheckTestResult();
        }
        /// <summary>
        /// Adds a HistoryDiskInfo.
        /// </summary>
        /// <param name="siteUri"> The site uri.</param>
        /// <param name="siteData"> The ResponseBuffer data.</param>
        public void AddHistoryNodeDisk(Uri siteUri, ResponseBuffer siteData)
        {
            this.SuspendLayout();

            //string folderName = string.Empty;
            string uriAndPort = string.Empty;

            if ( siteUri.Port == 80 )
            {
                //folderName = siteUri.Authority + siteUri.Port;
                uriAndPort = siteUri.Authority + ":" + siteUri.Port;
            }
            else
            {
                //folderName = siteUri.Authority.Replace(":","");
                uriAndPort = siteUri.Authority;
            }
            //			string dir = recentSitesDir + @"\" + folderName;
            //
            //			if ( !Directory.Exists(dir) )
            //			{
            //				Directory.CreateDirectory(dir);
            //			}

            // search index data for site root existence
            HistoryDiskInfo diskInfo = (HistoryDiskInfo)sitesIndex[uriAndPort];
            int index = sitesIndex.IndexOfKey(uriAndPort);

            // add new to disk
            if ( diskInfo != null )
            {
                HistoryTreeNode node = (HistoryTreeNode)this.Nodes[index];

                // add node to tree
                HistoryTreeNode tn = new HistoryTreeNode(siteUri.AbsolutePath,siteUri,null);
                tn.ImageIndex = this.IconNodeIndex;
                tn.SelectedImageIndex = this.IconNodeIndex;

                //int i = node.Nodes.IndexOf(tn);
                HistoryDiskInfo hdi = new HistoryDiskInfo();
                hdi.Url = uriAndPort + siteUri.AbsolutePath;

                if ( !diskInfo.ContainsNodeKey(hdi.Url) )
                {
                    node.Nodes.Add(tn);
                    diskInfo.AddHistoryDiskInfo(hdi.Url, hdi);
                }
            }
            else
            {
                // add as root node
                HistoryTreeNode tn = new HistoryTreeNode(uriAndPort,siteUri,null);
                tn.ImageIndex = this.IconSiteIndex;
                tn.SelectedImageIndex = this.IconSiteIndex;

                // add file to disk
                //string filePath = UpdateRecentSite(dir,siteUri.AbsolutePath,siteData);

                // add node to tree
                HistoryTreeNode newNode = new HistoryTreeNode(siteUri.AbsolutePath,siteUri,null);
                newNode.ImageIndex = this.IconNodeIndex;
                newNode.SelectedImageIndex = this.IconNodeIndex;

                tn.Nodes.Add(newNode);

                int i = tn.Nodes.IndexOf(newNode);
                HistoryDiskInfo child = new HistoryDiskInfo();
                child.Url = uriAndPort + siteUri.AbsolutePath;

                // add reference to Index data
                //sitesIndex.Add(uriAndPort + siteUri.AbsolutePath,hdi);

                this.Nodes.Add(tn);

                // add root reference to Index data
                HistoryDiskInfo parent = new HistoryDiskInfo();
                parent.Url = uriAndPort;
                parent.Type = HistoryDiskInfo.NodeType.Parent;
                parent.AddHistoryDiskInfo(child.Url, child);
                sitesIndex.Add(uriAndPort, parent);
            }

            UpdateIndexData();
            this.ResumeLayout();
        }
 /// <summary>
 /// Creates a new ASDE Command.
 /// </summary>
 /// <param name="httpResponse"> The response buffer type.</param>
 /// <param name="test"> The test type.</param>
 public AsdeCommand(ResponseBuffer httpResponse, Test test)
 {
     this.HttpResponseBuffer = httpResponse;
     this.TestToEvaluate = test;
 }
        /// <summary>
        /// Adds the report document row to a report.
        /// </summary>
        /// <param name="report"> The HtmlUnitTestReport type.</param>
        /// <param name="responseBuffer"> The response buffer.</param>
        /// <returns> A HtmlUnitTestReport type.</returns>
        private HtmlUnitTestReport.ResponseDocumentRow AddReportDocumentRow(HtmlUnitTestReport report, ResponseBuffer responseBuffer)
        {
            Ecyware.GreenBlue.ReportEngine.HtmlUnitTestReport.ResponseDocumentRow row = report.ResponseDocument.NewResponseDocumentRow();

            row.Date = DateTime.Now;
            row.ErrorMessage = responseBuffer.ErrorMessage;

            if ( this.CanSaveHtml )
            {
                // save html
                row.HtmlResponse = SaveHtml(responseBuffer.HttpBody);
                row.IsHtmlResponseFile = true;
            }
            else
            {
                row.HtmlResponse = responseBuffer.HttpBody;
                row.IsHtmlResponseFile = false;
            }

            row.RequestType = responseBuffer.RequestType.ToString();
            row.StatusCode = responseBuffer.StatusCode.ToString();
            row.StatusDescription = responseBuffer.StatusDescription;
            row.Version = responseBuffer.Version;

            report.ResponseDocument.AddResponseDocumentRow(row);

            return row;
        }
        /// <summary>
        /// Starts a new HTTP Post request.
        /// </summary>
        /// <param name="postUri"> The Url string.</param>
        /// <param name="properties"> The HttpProperties to set for the request.</param>
        /// <param name="values"> The data to post.</param>
        /// <param name="cookies"> The cookie data to set for the request.</param>
        /// <returns> A ResponseBuffer type.</returns>
        public ResponseBuffer StartSyncHttpPost(string postUri,HttpProperties properties,ArrayList values, CookieCollection cookies)
        {
            HttpWebResponse response=null;
            ResponseBuffer respBuffer=new ResponseBuffer();
            httpRequestState = new HttpState();

            postUri = EncodeDecode.UrlDecode(postUri);
            postUri = EncodeDecode.HtmlDecode(postUri);

            // create webrequest
            try
            {
                //this.ValidateIPAddress(new Uri(postUri));

                httpRequestState.HttpRequest = (HttpWebRequest)WebRequest.Create(postUri);

                // Set HttpWebRequestProperties
                SetHttpWebRequestProperties(httpRequestState.HttpRequest, properties);

                // Apply proxy settings
                if ( this.ProxySettings != null )
                {
                    SetProxy(httpRequestState.HttpRequest,this.ProxySettings);
                }

                byte[] data=null;
                if (values!=null)
                {
                    // transform to postdata and encode in bytes
                    string postData = GetPostData(values);
                    data=Encoding.UTF8.GetBytes(postData);
                }

                //httpRequestState.httpRequest.Referer = postUri;

                // set properties
                httpRequestState.HttpRequest.Method="POST";
                httpRequestState.HttpRequest.ContentType="application/x-www-form-urlencoded";
                httpRequestState.HttpRequest.ContentLength=data.Length;

                // get request stream
                Stream stm = httpRequestState.HttpRequest.GetRequestStream();
                stm.Write(data,0,data.Length);
                stm.Close();

                //hwr.ContinueDelegate=getRedirectHeaders;

                // save cookies
                httpRequestState.HttpRequest.CookieContainer=new CookieContainer();
                if ( cookies!=null )
                {
                    httpRequestState.HttpRequest.CookieContainer.Add(cookies);
                }

                HttpWebResponse httpResponse = (HttpWebResponse)httpRequestState.HttpRequest.GetResponse();
                httpRequestState.HttpResponse = httpResponse;

                // get ResponseBuffer
                respBuffer = HttpPipeline.FillResponseBuffer(httpResponse,
                    httpRequestState.HttpRequest,
                    properties,
                    httpRequestState);
            }
            catch (ProtocolViolationException p)
            {
                if ( response!=null )
                {
                    response.Close();
                }
                respBuffer.ErrorMessage = "Protocol Exception:" + p.Message;
                return respBuffer;
            }
            catch (WebException w)
            {
                StringBuilder s = new StringBuilder();
                s.Append("Error message:");
                s.Append(w.Message);
                s.Append("\r\nStatus Code:");
                s.Append(((HttpWebResponse)w.Response).StatusCode);
                s.Append("\r\nStatus Description:");
                s.Append(((HttpWebResponse)w.Response).StatusDescription);

                if ( response!=null )
                {
                    response.Close();
                }
                respBuffer.ErrorMessage = s.ToString();
                return  respBuffer;
            }

            // response here
            return respBuffer;
        }
        /// <summary>
        /// Adds the response headers to the report.
        /// </summary>
        /// <param name="parentRow"> The ResponseDocumentRow.</param>
        /// <param name="report"> The HtmlUnitTestReport type.</param>
        /// <param name="responseBuffer"> The response buffer.</param>
        private void AddResponseHeaders(HtmlUnitTestReport.ResponseDocumentRow parentRow,HtmlUnitTestReport report, ResponseBuffer responseBuffer)
        {
            Ecyware.GreenBlue.ReportEngine.HtmlUnitTestReport.ResponseHeaderRow respHeaderRow = report.ResponseHeader.NewResponseHeaderRow();
            respHeaderRow.SetParentRow(parentRow);
            report.ResponseHeader.AddResponseHeaderRow(respHeaderRow);

            foreach (DictionaryEntry de in responseBuffer.ResponseHeaderCollection)
            {
                Ecyware.GreenBlue.ReportEngine.HtmlUnitTestReport.ResponseItemsRow row = report.ResponseItems.NewResponseItemsRow();

                string name = (string)de.Key;
                if ( !hiddenHeaders.Contains(name.ToLower()) )
                {
                    if ( de.Value is Uri )
                    {
                        row.Name = name;
                        row.Value = ((Uri)de.Value).ToString();
                    }
                    else
                    {
                        row.Name = name;
                        if ( de.Value == null )
                        {
                            row.Value = String.Empty;
                        }
                        else
                        {
                            row.Value = de.Value.ToString();
                        }

                    }

                    row.SetParentRow(respHeaderRow);
                    report.ResponseItems.AddResponseItemsRow(row);
                }
            }
        }
 /// <summary>
 /// Displays the executed session run.
 /// </summary>
 /// <param name="resp"> The ResponseBuffer type.</param>
 /// <param name="lastItem"> The last item flag.</param>
 private void EasyTestRunDisplay(ResponseBuffer resp, bool lastItem)
 {
     this.textViewerForm.EditorText  += resp.HttpBody + "\r\n\r\n";
     this.textViewerForm.EditorText  += resp.ResponseHeader + "\r\n\r\n";
     this.textViewerForm.EditorText  += resp.CookieData + "\r\n\r\n";
 }
 private void PipelineCommandCompleted(object sender, EventArgs e)
 {
     _responseBuffer = inspectorPipeline.ResponseData;
 }
        /// <summary>
        /// Fills the Response Header Collection.
        /// </summary>
        /// <param name="resp"> The ResponseBuffer type.</param>
        /// <param name="request"> The HttpWebRequest type.</param>
        /// <param name="responseHeaders"> The Response WebHeaderCollection.</param>
        /// <param name="hwr"> The HttpWebResponse type.</param>
        /// <returns> An updated ResponseBuffer type containing the change.</returns>
        public static ResponseBuffer FillResponseHeader(ResponseBuffer resp,HttpWebRequest request, WebHeaderCollection responseHeaders, HttpWebResponse hwr)
        {
            Hashtable coll = new Hashtable();

            coll.Add("Character Set",hwr.CharacterSet);
            coll.Add("Content Encoding",hwr.ContentEncoding);
            coll.Add("Last Modified",hwr.LastModified);
            coll.Add("Method",hwr.Method);
            coll.Add("Protocol Version",hwr.ProtocolVersion);
            coll.Add("Response Uri",hwr.ResponseUri);
            coll.Add("Server",hwr.Server);
            coll.Add("Status Code",hwr.StatusCode);
            coll.Add("Status Description",hwr.StatusDescription);
            coll.Add("Referer", request.Referer);

            for (int i = 0;i<responseHeaders.Count;i++)
            {
                if (!coll.ContainsKey(responseHeaders.GetKey(i)) )
                {
                    coll.Add(responseHeaders.GetKey(i), responseHeaders[i]);
                }
            }

            StringBuilder sb = new StringBuilder();

            sb.Append("---------------------");
            sb.Append("=RESPONSE HEADERS=");
            sb.Append("---------------------\r\n");
            foreach (DictionaryEntry de in coll)
            {
                sb.Append(de.Key);
                sb.Append(":");
                sb.Append(de.Value);
                sb.Append("\r\n");
            }

            resp.ResponseHeader = sb.ToString();
            resp.ResponseHeaderCollection = coll;
            return resp;
        }