/// <summary>
        /// Process the list of authorized people and continue the flow.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The event arguments.</param>
        private static void GetAuthorizedPeopleCompleted(object sender, CHBaseResponseEventArgs e)
        {
            AuthenticationCheckState state = (AuthenticationCheckState)e.Request.UserState;

            if (e.ErrorText != null)
            {
                state.AuthenticationCompletedHandler(state.Service, e);
                return;
            }

            XElement response = XElement.Parse(e.ResponseXml);

            XElement responseResults = response.Descendants("response-results").Single();

            state.Service.Records.Clear();

            foreach (XElement personInfo in responseResults.Elements("person-info"))
            {
                Guid   personId   = new Guid(personInfo.Element("person-id").Value);
                string personName = personInfo.Element("name").Value;

                // If we loaded our settings, the current record is incomplete. We will try
                // to match it to one that we got back...
                CHBaseRecord currentRecord = state.Service.CurrentRecord;
                state.Service.CurrentRecord = null;

                foreach (XElement recordNode in personInfo.Elements("record"))
                {
                    CHBaseRecord record = CHBaseRecord.Create(personId, personName, CHBaseService.GetOuterXml(recordNode));
                    if (record != null)
                    {
                        state.Service.Records.Add(record);

                        if ((currentRecord != null) &&
                            (currentRecord.PersonId == record.PersonId) &&
                            (currentRecord.RecordId == record.RecordId))
                        {
                            state.Service.CurrentRecord = record;
                        }
                    }
                }
            }

            if (state.Service.Records.Count != 0)
            {
                // all done
                state.AuthenticationCompletedHandler(state.Service, null);
            }
            else
            {
                // unsuccessful, restart from scratch...
                state.Service.ClearProvisioningInformation();
                BeginAuthenticationCheck(state);
            }
        }
        /// <summary>
        /// Invoke the calling application's callback.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="resultText">The raw response.</param>
        /// <param name="response">The response object.</param>
        /// <param name="errorText">The error text, or null if successful. </param>
        private void InvokeApplicationResponseCallback(
            CHBaseRequest request,
            string resultText,
            CHBaseResponse response,
            string errorText)
        {
            CHBaseResponseEventArgs eventArgs = new CHBaseResponseEventArgs(request, resultText, response);

            eventArgs.ErrorText = errorText;

            if (request.ResponseCallback != null)
            {
                request.ResponseCallback(this, eventArgs);
            }
        }
        /// <summary>
        /// Processes the CAST information and re-issues the original request.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The event args.</param>
        private void RefreshSessionTokenCompleted(object sender, CHBaseResponseEventArgs e)
        {
            SendPostEventArgs args = (SendPostEventArgs)e.Request.UserState;

            // any error just gets returned to the application.
            if (e.ErrorText != null)
            {
                InvokeApplicationResponseCallback(args.HealthVaultRequest, args.ResponseData, e.Response, e.Response.ErrorMessage);
                return;
            }

            // if the CAST was successful the results were saved and
            // the original request is restarted.
            SaveCastCallResults(e.ResponseXml);

            BeginSendRequest(args.HealthVaultRequest);
        }
        /// <summary>
        /// Handle the response from the CAST call and continue the flow.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The event arguments.</param>
        private static void CastCallCompleted(object sender, CHBaseResponseEventArgs e)
        {
            AuthenticationCheckState state = (AuthenticationCheckState)e.Request.UserState;

            if (e.ErrorCode == ErrorInvalidApp)
            {
                state.Service.SharedSecret  = null;     // force creation of app from scratch...
                state.Service.AppIdInstance = Guid.Empty;
            }
            else if (e.ErrorText != null)
            {
                state.ShellAuthRequiredHandler(state.Service, e);
                return;
            }
            else
            {
                state.Service.SaveCastCallResults(e.ResponseXml);
            }

            BeginAuthenticationCheck(state);
        }
        /// <summary>
        /// Save the new application info and continue the process.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The event arguments.</param>
        private static void NewApplicationCreationInfoCompleted(object sender, CHBaseResponseEventArgs e)
        {
            AuthenticationCheckState state = (AuthenticationCheckState)e.Request.UserState;

            if (e.ErrorText != null)
            {
                state.AuthenticationCompletedHandler(state.Service, e);
                return;
            }

            XElement response = XElement.Parse(e.ResponseXml);

            XNamespace responseNamespace = "urn:com.microsoft.wc.methods.response.NewApplicationCreationInfo";
            XElement   info = response.Element(responseNamespace + "info");

            state.Service.AppIdInstance            = new Guid(info.Element("app-id").Value);
            state.Service.SharedSecret             = info.Element("shared-secret").Value;
            state.Service.ApplicationCreationToken = info.Element("app-token").Value;

            state.ShellAuthRequiredHandler(state.Service, e);
        }
        /// <summary>
        /// Process the list of authorized people and continue the flow.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The event arguments.</param>
        private static void GetAuthorizedPeopleCompleted(object sender, CHBaseResponseEventArgs e)
        {
            AuthenticationCheckState state = (AuthenticationCheckState)e.Request.UserState;

            if (e.ErrorText != null)
            {
                state.AuthenticationCompletedHandler(state.Service, e);
                return;
            }

            XElement response = XElement.Parse(e.ResponseXml);

            XElement responseResults = response.Descendants("response-results").Single();

            state.Service.Records.Clear();

            foreach (XElement personInfo in responseResults.Elements("person-info"))
            {
                Guid personId = new Guid(personInfo.Element("person-id").Value);
                string personName = personInfo.Element("name").Value;

                // If we loaded our settings, the current record is incomplete. We will try
                // to match it to one that we got back...
                CHBaseRecord currentRecord = state.Service.CurrentRecord;
                state.Service.CurrentRecord = null;

                foreach (XElement recordNode in personInfo.Elements("record"))
                {
                    CHBaseRecord record = CHBaseRecord.Create(personId, personName, CHBaseService.GetOuterXml(recordNode));
                    if (record != null)
                    {
                        state.Service.Records.Add(record);

                        if ((currentRecord != null) &&
                            (currentRecord.PersonId == record.PersonId) &&
                            (currentRecord.RecordId == record.RecordId))
                        {
                            state.Service.CurrentRecord = record;
                        }
                    }
                }
            }

            if (state.Service.Records.Count != 0)
            {
                // all done
                state.AuthenticationCompletedHandler(state.Service, null);
            }
            else
            {
                // unsuccessful, restart from scratch...
                state.Service.ClearProvisioningInformation();
                BeginAuthenticationCheck(state);
            }
        }
        /// <summary>
        /// Processes the CAST information and re-issues the original request.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The event args.</param>
        private void RefreshSessionTokenCompleted(object sender, CHBaseResponseEventArgs e)
        {
            SendPostEventArgs args = (SendPostEventArgs)e.Request.UserState;

            // any error just gets returned to the application.
            if (e.ErrorText != null)
            {
                InvokeApplicationResponseCallback(args.HealthVaultRequest, args.ResponseData, e.Response, e.Response.ErrorMessage);
                return;
            }

            // if the CAST was successful the results were saved and
            // the original request is restarted.
            SaveCastCallResults(e.ResponseXml);

            BeginSendRequest(args.HealthVaultRequest);
        }
        /// <summary>
        /// Invoke the calling application's callback.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="resultText">The raw response.</param>
        /// <param name="response">The response object.</param>
        /// <param name="errorText">The error text, or null if successful. </param>
        private void InvokeApplicationResponseCallback(
            CHBaseRequest request,
            string resultText,
            CHBaseResponse response,
            string errorText)
        {
            CHBaseResponseEventArgs eventArgs = new CHBaseResponseEventArgs(request, resultText, response);
            eventArgs.ErrorText = errorText;

            if (request.ResponseCallback != null)
            {
                request.ResponseCallback(this, eventArgs);
            }
        }
        void GetPersonalImageCompleted(object sender, CHBaseResponseEventArgs e)
        {
            SetProgressBarVisibility(false);

            if (e.ErrorText == null)
            {
                _currentThingIds.Clear();

                List<XElement> thingNodes = GetThingsFromResponse(e);
                try
                {
                    if (thingNodes.Count != 0)
                    {
                        string url = thingNodes[0].Descendants("blob-ref-url").Single().Value;

                        HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
                        request.BeginGetResponse((ar) =>
                        {
                            var response = request.EndGetResponse(ar);
                            Dispatcher.BeginInvoke(() =>
                            {
                                using (var stream = response.GetResponseStream())
                                {
                                    var image = new BitmapImage();
                                    image.SetSource(stream);
                                    c_RecordImage.Source = image;
                                }
                            });
                        }, null);
                    }
                }
                catch (Exception) { }
            }

            AnimateObjectOpacity(c_RecordPanel);

            GetThingsStart();
        }
        void RemoveThingsCompleted(object sender, CHBaseResponseEventArgs e)
        {
            SetProgressBarVisibility(false);

            GetThingsStart();
        }
        void GetThingsCompleted(object sender, CHBaseResponseEventArgs e)
        {
            SetProgressBarVisibility(false);

            if (e.ErrorText == null)
            {
                _currentThingIds.Clear();

                List<XElement> thingNodes = GetThingsFromResponse(e);

                List<string> values = new List<string>();
                int count = 0;
                foreach (XElement thingNode in thingNodes)
                {
                    XElement thingIdNode = thingNode.Element("thing-id");
                    _currentThingIds.Add(thingIdNode.ToString());

                    XElement dateNode = thingNode.Element("eff-date");
                    DateTime dateTime = DateTime.Parse(dateNode.Value);
                    string value, units = "kg";
                    try
                    {
                        XElement displayValueNode = thingNode.Descendants("display").Single();
                        value = displayValueNode.Value;
                        units = displayValueNode.Attribute("units").Value;
                    }
                    catch
                    {
                        XElement displayValueNode = thingNode.Descendants("value").Single();
                        value = displayValueNode.Descendants("kg").Single().Value;
                    }

                    string displayValue = dateTime.ToString() + "      " + value + " " + units;

                    values.Add(displayValue);

                    count++;
                    if (count == 10)
                    {
                        break;
                    }
                }

                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    string text = "Results\r\n";

                    foreach (string value in values)
                    {
                        text += value + "\r\n";
                    }

                    c_Response.Text = text;
                });
            }
        }
        List<XElement> GetThingsFromResponse(CHBaseResponseEventArgs eventArgs)
        {
            XElement responseNode = XElement.Parse(eventArgs.ResponseXml);

            XElement infoNode = responseNode.Element(XName.Get("info", "urn:com.microsoft.wc.methods.response.GetThings3"));

            List<XElement> thingNodes = new List<XElement>(infoNode.Element("group").Elements("thing"));

            return thingNodes;
        }
        void PutThingsCompleted(object sender, CHBaseResponseEventArgs e)
        {
            if (e.ErrorText != null)
            {
                // handle error...
            }

            SetProgressBarVisibility(false);

            XElement response = XElement.Parse(e.ResponseXml);

            XElement thingIdNode = response.Descendants("thing-id").Single();

            Guid thingId = new Guid(thingIdNode.Value);

            Guid versionStamp = new Guid(thingIdNode.Attribute("version-stamp").Value);

            GetThingsStart();
        }
        void AuthenticationCompleted(object sender, CHBaseResponseEventArgs e)
        {
            SetProgressBarVisibility(false);

            if (e != null && e.ErrorText != null)
            {
                SetRecordName(e.ErrorText);
                return;
            }

            if (App.HealthVaultService.CurrentRecord == null)
            {
                App.HealthVaultService.CurrentRecord = App.HealthVaultService.Records[0];
            }

            App.HealthVaultService.SaveSettings(SettingsFilename);
            if (App.HealthVaultService.CurrentRecord != null)
            {
                SetRecordName(App.HealthVaultService.CurrentRecord.RecordName);

                //GetThingsStart();
                GetPersonalImageStart();
            }
        }
        /// <summary>
        /// Save the new application info and continue the process.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The event arguments.</param>
        private static void NewApplicationCreationInfoCompleted(object sender, CHBaseResponseEventArgs e)
        {
            AuthenticationCheckState state = (AuthenticationCheckState)e.Request.UserState;

            if (e.ErrorText != null)
            {
                state.AuthenticationCompletedHandler(state.Service, e);
                return;
            }

            XElement response = XElement.Parse(e.ResponseXml);

            XNamespace responseNamespace = "urn:com.microsoft.wc.methods.response.NewApplicationCreationInfo";
            XElement info = response.Element(responseNamespace + "info");
            state.Service.AppIdInstance = new Guid(info.Element("app-id").Value);
            state.Service.SharedSecret = info.Element("shared-secret").Value;
            state.Service.ApplicationCreationToken = info.Element("app-token").Value;

            state.ShellAuthRequiredHandler(state.Service, e);
        }
        /// <summary>
        /// Handle the response from the CAST call and continue the flow.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The event arguments.</param>
        private static void CastCallCompleted(object sender, CHBaseResponseEventArgs e)
        {
            AuthenticationCheckState state = (AuthenticationCheckState)e.Request.UserState;

            if (e.ErrorCode == ErrorInvalidApp)
            {
                state.Service.SharedSecret = null;      // force creation of app from scratch...
                state.Service.AppIdInstance = Guid.Empty;
            }
            else if (e.ErrorText != null)
            {
                state.ShellAuthRequiredHandler(state.Service, e);
                return;
            }
            else
            {
                state.Service.SaveCastCallResults(e.ResponseXml);
            }

            BeginAuthenticationCheck(state);
        }
        void DoShellAuthentication(object sender, CHBaseResponseEventArgs e)
        {
            SetProgressBarVisibility(false);

            App.HealthVaultService.SaveSettings(SettingsFilename);

            string url;

            if (_addingRecord)
            {
                url = App.HealthVaultService.GetUserAuthorizationUrl();
            }
            else
            {
                url = App.HealthVaultService.GetApplicationCreationUrl();
            }

            App.HealthVaultShellUrl = url;

#if !UseHostedBrowser
            Uri pageUri = new Uri("/HealthVaultIntroPage.xaml", UriKind.RelativeOrAbsolute);

            Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    NavigationService.Navigate(pageUri);
                });
#else
            WebBrowserTask task = new WebBrowserTask();
            task.URL = HttpUtility.UrlEncode(url);
            task.Show();
#endif
        }