internal virtual void ExecuteInternal()
        {
            try
            {
                _currentEasyWeb = this.BuildWebRequest(null);
                _currentEasyWeb.RequestCompressionMethod = RequestCompressionMethod;

                _currentEasyWeb.Fetch(_connection.RequestUrl, this);
            }
            catch (XmlException xmlException)
            {
                throw new HealthServiceException(
                    ResourceRetriever.GetResourceString("InvalidResponseFromXMLRequest"),
                    xmlException);
            }
            finally
            {
                if (_currentEasyWeb != null)
                {
                    _currentEasyWeb.Dispose();
                    _currentEasyWeb = null;
                }

                List<HealthServiceRequest> pendingRequests = _connection.PendingRequests;
                lock (pendingRequests)
                {
                    _connection.PendingRequests.Remove(this);
                }
            }
        }
        /// <summary> 
        /// constructor for string POST 
        /// </summary>
        /// 
        /// <param name="stringRequest">
        /// text to send 
        /// </param>
        /// 
        internal static EasyWebRequest Create(string stringRequest)
        {
            EasyWebRequest instance;

            if (_requestOverride != null)
            {
                instance = _requestOverride;
            }
            else
            {
                instance = new EasyWebRequest();
            }

            instance._stringRequest = stringRequest;

            return instance;
        }
        internal virtual string ExecuteForTransformInternal(string transform)
        {
            String result = null;
            try
            {
                _currentEasyWeb = this.BuildWebRequest(transform);
                _currentEasyWeb.RequestCompressionMethod = RequestCompressionMethod;
                _currentEasyWeb.Fetch(_connection.RequestUrl);

                result = _currentEasyWeb.ResponseText;
            }
            finally
            {
                if (_currentEasyWeb != null)
                {
                    _currentEasyWeb.Dispose();
                    _currentEasyWeb = null;
                }

                List<HealthServiceRequest> pendingRequests = _connection.PendingRequests;
                lock (pendingRequests)
                {
                    _connection.PendingRequests.Remove(this);
                }
            }

            // Now look at the errors in the response before returning. If we see HV XML returned
            // containing a failure status code, throw an exception

            if (HealthVaultPlatformTrace.LoggingEnabled)
            {
                HealthVaultPlatformTrace.LogResponse(result);
            }

            XmlReaderSettings settings = SDKHelper.XmlReaderSettings;
            settings.CloseInput = false;
            settings.IgnoreWhitespace = false;

            try
            {
                using (XmlReader reader = XmlReader.Create(new StringReader(result), settings))
                {
                    reader.NameTable.Add("wc");

                    if (SDKHelper.ReadUntil(reader, "response"))
                    {
                        if (SDKHelper.ReadUntil(reader, "status"))
                        {
                            if (SDKHelper.ReadUntil(reader, "code"))
                            {
                                int responseCode = reader.ReadElementContentAsInt();

                                HealthServiceStatusCode errorCode =
                                    HealthServiceStatusCodeManager.GetStatusCode(responseCode);

                                if (errorCode != HealthServiceStatusCode.Ok)
                                {
                                    HealthServiceResponseError error = HandleErrorResponse(reader);

                                    HealthServiceException e =
                                        HealthServiceExceptionHelper.GetHealthServiceException(
                                            responseCode,
                                            error);

                                    throw e;
                                }
                            }
                        }
                    }
                }
            }
            catch (FormatException)
            {
            }
            catch (MissingFieldException)
            {
            }
            catch (XmlException)
            {
            }
            catch (InvalidOperationException)
            {
            }
            return result;
        }
        /// <summary>
        /// Invokes the open query with the specified timeout and returns the results.
        /// </summary>
        /// 
        /// <param name="defaultTimeout">
        /// The time in milliseconds before the invocation of the query will 
        /// timeout.
        /// </param>
        /// 
        /// <returns>
        /// A string representing the invocation results.
        /// </returns>
        /// 
        /// <remarks>
        /// The invocation results are returned as a string because
        /// any method can be called.
        /// An open query can be constructed as a call to any of the 
        /// HealthVault methods. You can also apply any transforms to the 
        /// method results as part of the open query. The returned string 
        /// contains the HTTP response. This could be the XML produced by the 
        /// HealthVault service method, or it can be a transformed version 
        /// of that XML data.
        /// </remarks>
        /// 
        /// <exception cref="InvalidOperationException">
        /// <cref name="PinRequired"/> is <b>true</b>, in which case you should  
        /// use the <cref name="Invoke(int,string)"/> method instead.
        /// </exception>
        /// 
        public string Invoke(int defaultTimeout)
        {
            Validator.ThrowInvalidIf(this.PinRequired, "PinCodeRequired");

            using (EasyWebRequest easyWeb = new EasyWebRequest())
            {
                easyWeb.TimeoutMilliseconds = defaultTimeout;
                easyWeb.Fetch(Url);
                return easyWeb.ResponseText;
            }
        }
 /// <summary>
 /// Invokes the open query given the specified timeout and URL and 
 /// returns the results.
 /// </summary>
 /// 
 /// <param name="defaultTimeout">
 /// The time in seconds before the invocation of the query will 
 /// timeout.
 /// </param>
 /// 
 /// <param name="requestUrl">
 /// A URI representing the complete URL of an existing <see cref="OpenQuery"/>.
 /// The URL must include the query ID and personal identification number
 /// (PIN) if required.
 /// </param>
 /// 
 /// <returns>
 /// A string representing the invocation results.
 /// </returns>
 /// 
 /// <remarks>
 /// The invocation results are returned as a string because
 /// any method can be called.
 /// An open query can be constructed as a call to any of the 
 /// HealthVault methods. You can also apply any transforms to the 
 /// method results as part of the open query. The returned string 
 /// contains the HTTP response. This could be the XML produced by the 
 /// HealthVault service method, or it can be a transformed version 
 /// of that XML data.
 /// </remarks>
 /// 
 public static string Invoke(int defaultTimeout, Uri requestUrl)
 {
     using (EasyWebRequest easyWeb = new EasyWebRequest())
     {
         easyWeb.TimeoutMilliseconds = defaultTimeout;
         easyWeb.Fetch(requestUrl);
         return easyWeb.ResponseText;
     }
 }
        /// <summary>
        /// Invokes the open query with the specified timeout and personal 
        /// identification number (PIN) and returns the results.
        /// </summary>
        /// 
        /// <param name="defaultTimeout">
        /// The time in seconds before the invocation of the query will 
        /// timeout.
        /// </param>
        /// 
        /// <param name="pinCode">
        /// The  code required to access the query.
        /// </param>
        /// 
        /// <returns>
        /// A string representing the invocation results.
        /// </returns>
        /// 
        /// <remarks>
        /// The invocation results are returned as a string because
        /// any method can be called.
        /// An open query can be constructed as a call to any of the 
        /// HealthVault methods. You can also apply any transforms to the 
        /// method results as part of the open query. The returned string 
        /// contains the HTTP response. This could be the XML produced by the 
        /// HealthVault service method, or it can be a transformed version 
        /// of that XML data.
        /// </remarks>
        /// 
        /// <exception cref="ArgumentException">
        /// The <paramref name="pinCode"/> parameter is <b>null</b> or empty.
        /// </exception>
        /// 
        public string Invoke(int defaultTimeout, string pinCode)
        {
            Validator.ThrowIfStringNullOrEmpty(pinCode, "pinCode");

            Uri requestUrl = CreateOpenQueryUrl(Id, pinCode);

            using (EasyWebRequest easyWeb = new EasyWebRequest())
            {
                easyWeb.TimeoutMilliseconds = defaultTimeout;
                easyWeb.Fetch(requestUrl);
                return easyWeb.ResponseText;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// 
        /// <param name="appId"></param>
        /// <param name="ticket"></param>
        /// <param name="sharedSecret"></param>
        /// 
        /// <param name="isMra">
        /// True if the application is a multi-record application, or false otherwise. Multi-record
        /// applications can work with many user records at one time and does not rely on the
        /// selected record when performing operations.
        /// </param>
        /// 
        /// <param name="isPersistent">
        /// True if creating a persistent token, or false otherwise.  Persistent connections
        /// remain valid for the duration specified in the application's configuration within
        /// HealthVault.  Typically, persistent tokens are valid for up to one year.
        /// </param>
        /// 
        /// <param name="cancelTrigger"></param>
        /// <param name="shellUrl"></param>
        /// 
        /// <returns></returns>
        /// 
        /// <exception cref ="HealthServiceException">
        /// If the request results in an error being returned from the Shell.  The 
        /// <see cref="HealthServiceException.ErrorCode"/> can give more details about the error
        /// that occurred.
        /// </exception>
        /// 
        /// <exception cref="HealthRecordAuthorizationRequiredException">
        /// If the user could not be logged in because they have not authorized the application to
        /// a health record. The application should direct the user to the APPAUTH target of the
        /// Shell.
        /// </exception>
        /// 
        /// <exception cref="HealthRecordAuthorizationNotPossible">
        /// If the user does not have access to a health record that meets the minimum authorization
        /// requirements of the application. The user will need to request more access from the 
        /// custodian to use this application.
        /// </exception>
        /// 
        /// <exception cref="HealthRecordReauthorizationRequired">
        /// If the user had authorized a health record for this application but the application
        /// changed its required base authorizations such that the user must reauthorize the
        /// application. The application should direct the user to the APPAUTH target of the Shell.
        /// </exception>
        /// 
        private static string VerifyTicketWithShell(
            Guid appId,
            string ticket,
            CryptoHash sharedSecret,
            bool isMra,
            bool isPersistent,
            ManualResetEvent cancelTrigger,
            Uri shellUrl)
        {
            ShellResponseHandler handler = new ShellResponseHandler();
            EasyWebRequest request = new EasyWebRequest();
            request.ForceAsyncRequest = true;
            request.RequestCompressionMethod = String.Empty;

            if (cancelTrigger != null)
            {
                request.RequestCancelTrigger = cancelTrigger;
            }

            // Add the Authorization header for passport verification
            string ticketHeader =
                Convert.ToBase64String(
                    new UTF8Encoding().GetBytes("WLID1.0 t=" + ticket));
            request.Headers.Add(
                "LiveIdTicket",
                ticketHeader);

            // Add the shared secret header for creating the session token
            string sharedSecretHeader =
                Convert.ToBase64String(
                    new UTF8Encoding().GetBytes(sharedSecret.GetInfoXml()));
            request.Headers.Add(
                "SharedSecret",
                sharedSecretHeader);

            string authToken = null;
            try
            {
                Uri liveIdTicketVerifierUrl =
                    new Uri(
                        shellUrl,
                        "redirect.aspx?target=verifyliveid&targetqs=" +
                            HttpUtility.UrlEncode(
                                "?appid=" + appId + "&ismra=" + SDKHelper.XmlFromBool(isMra) +
                                "&persistwctoken=" + SDKHelper.XmlFromBool(isPersistent)));

                request.Fetch(liveIdTicketVerifierUrl,handler);

                ApplicationRecordAuthorizationAction action =
                    ApplicationRecordAuthorizationAction.Unknown;

                XmlReader infoReader = handler.Response.InfoReader;
                if (SDKHelper.ReadUntil(infoReader, "token"))
                {
                    if (infoReader.MoveToAttribute("app-record-auth-action"))
                    {
                        try
                        {
                            action =
                                (ApplicationRecordAuthorizationAction)Enum.Parse(
                                    typeof(ApplicationRecordAuthorizationAction),
                                    infoReader.Value);
                        }
                        catch (ArgumentException)
                        {
                        }
                    }
                }

                switch (action)
                {
                    case ApplicationRecordAuthorizationAction.NoActionRequired :
                        break;

                    case ApplicationRecordAuthorizationAction.AuthorizationRequired :
                        throw new HealthRecordAuthorizationRequiredException();

                    case ApplicationRecordAuthorizationAction.ReauthorizationNotPossible :
                        throw new HealthRecordAuthorizationNotPossible();

                    case ApplicationRecordAuthorizationAction.ReauthorizationRequired :
                        throw new HealthRecordReauthorizationRequired();

                    default :
                        throw new HealthServiceException(
                            HealthServiceStatusCode.RecordAuthorizationFailure);
                }

                infoReader.MoveToElement();
                authToken = infoReader.ReadElementContentAsString();
            }
            catch (WebException webException)
            {
                if (((HttpWebResponse)webException.Response).StatusCode ==
                    HttpStatusCode.Forbidden)
                {
                    throw new HealthServiceAccessDeniedException(
                        webException.Message,
                        webException);
                }
                throw;
            }
            finally
            {
                if (request != null)
                {
                    request.Dispose();
                    request = null;
                }
            }
            return authToken;
        }