private void HandleControlMessage(string type)
        {
            try
            {
                log.Info(String.Format("{0} - HandleControlMessage started - {1}\n\n", ANI, type));
                SessionsUri = new Uri(BaseUri, "/ivr/api/sessions");
                Client = new HttpClient { BaseAddress = BaseUri };
                Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                var param =
                    Convert.ToBase64String(
                        System.Text.Encoding.ASCII.GetBytes(String.Format("{0}:{1}",
                                                                            "demo",
                                                                            "radisH1!")));
                Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("basic", param);
            }
            catch (UriFormatException ex)
            {
                log.Error(String.Format("{0} - Bad API server address - " + ex.Message, ANI));
            }

            log.Info(String.Format("{0} - SessionURI in HandleControlMessage is {1}", ANI, SessionURI));
            Client.GetAsync(SessionURI).ContinueWith(
            responseTask =>
            {
                log.Info(String.Format("{0} - continuing async get", ANI));
                if (responseTask.Result.IsSuccessStatusCode)
                {
                    responseTask.Result.Content.ReadAsAsync<Session>(
                        new List<MediaTypeFormatter> { jsonFormatter }).ContinueWith(
                        contentTask =>
                        {
                            cvSession = contentTask.Result;
                            if (cvSession != null)
                            {
                                ANI = cvSession.callerId;
                                CallSid = cvSession.callId;
                                log.Info(String.Format("{0} - ANI is {1}, CallSid is {2}", ANI, ANI, CallSid));
                                if (cvSession.status.Equals("connected"))
                                {
                                    log.Info(String.Format("{0} - session connected", ANI));
                                    if (SessionPropertiesUri == null ||
                                        !SessionPropertiesUri.AbsolutePath.StartsWith(
                                            SessionUri.AbsolutePath))
                                    {
                                        var link = cvSession.links.Find(l => l.rel.EndsWith(Link.PayloadRel));
                                        if (link != null)
                                        {
                                            SessionPropertiesUri = new Uri(link.href);
            //                                            log.Info(String.Format("{0} - Ready to log properties uri for {1}", ANI, link.href));
                                            GetProperties();
                                            log.Info(String.Format("{0} - After logging properties uri", ANI));
                                        }
                                        else
                                        {
                                            log.Info(String.Format("{0} - Cannot find the properties uri!", ANI));
                                        }
                                        log.Info(String.Format("{0} - looking for control message link", ANI));
                                        var cmlink = cvSession.links.Find(l => l.rel.EndsWith(Link.ControlMessageRel));
                                        if (cmlink != null)
                                        {
            //                                            log.Info(String.Format("{0} - control message link is not null", ANI));
                                            SessionControlMessageUri = new Uri(cmlink.href);
                                            log.Info(String.Format("{0} - control message URI is {1}", ANI, SessionControlMessageUri));
                                            GetControlMessage();
                                        }
                                        else
                                        {
                                            log.Info(String.Format("{0} - Cannot find the control message uri!", ANI));
                                        }
                                    }
                                    log.Info(String.Format("{0} - Last update: {1}", ANI, DateTime.Now));
                                }
                                else
                                {
                                    if (cvSession.status.Equals("interrupted"))
                                    {
                                        log.Info(String.Format("{0} - session interrupted", ANI));
                                    }
                                    else
                                        if (cvSession.status.Equals("suspended"))
                                        {
                                            log.Info(String.Format("{0} - session suspended", ANI));
                                        }
                                        else
                                        {
                                            log.Info(String.Format("{0} - session disconnected", ANI));
                                        }
                                    SendTwilioInterruptStatus(cvSession.status);
                                }
                            }
                            else
                            {
                                log.Info(String.Format("{0} - GET {1} did not return recognizable content!", ANI, SessionUri.AbsoluteUri));
                            }
                        });
                }
                else
                {
                    log.Info(String.Format("{0} - switching on StatusCode", ANI));
                    string statusMsg;
                    switch (responseTask.Result.StatusCode)
                    {
                        case HttpStatusCode.NotFound:
                            log.Info(String.Format("{0} - HttpStatusCode.NotFound detected", ANI));
                            statusMsg = "disconnected";
                            break;
                        case HttpStatusCode.NotModified:
                            log.Info(String.Format("{0} - HttpStatusCode.NotModified detected", ANI));
                            statusMsg = "no change";
                            break;
                        default:
                            log.Info(String.Format("{0} - default case got {1}", responseTask.Result.StatusCode));
                            var msg = responseTask.Result.Content.ReadAsStringAsync().Result;
                            log.Info(String.Format("{0} - GET {1} failed! Reason - {2}, {3}, {4}",
                                                            ANI,
                                                            SessionUri.AbsoluteUri,
                                                            responseTask.Result.StatusCode,
                                                            responseTask.Result.ReasonPhrase,
                                                            msg));
                            statusMsg = "disconnected";
                            break;
                    }
                    SendTwilioInterruptStatus(statusMsg);
                }
            });
            log.Info(String.Format("{0} - after async get", ANI));
        }
        public void StartCVSession()
        {
            try
            {
                log.Info(String.Format("{0} - StartCVSession started.\n", ANI));
                CVStartUpFailed = false;
                stateChangeURI = signalURI + "/state_change.cshtml?sessionid=" + ANI;
                newMessageURI = signalURI + "/new_message.cshtml?sessionid=" + ANI;
                SessionsUri = new Uri(BaseUri, "/ivr/api/sessions");
                notificationType = "CCXML";
                Client = new HttpClient { BaseAddress = BaseUri };
                Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                var param =
                    Convert.ToBase64String(
                        System.Text.Encoding.ASCII.GetBytes(String.Format("{0}:{1}",
                                                                            "account",
                                                                            "password")));

                Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("basic", param);
            }
            catch (UriFormatException ex)
            {
                log.Error(String.Format("{0} - Bad API server address - " + ex.Message, ANI));
            }

            var newSession = new NewSession
                            {
                                callerId = ANI,
                                callId = CallSid,
                                newMessageUri = newMessageURI,
                                stateChangeUri = stateChangeURI,
                                notificationType = notificationType
                            };
            try
            {
                log.Info(String.Format("{0} - StartCVSession inside try block ", ANI));
                log.Info(String.Format("{0} - stateChangeURI is {1}", ANI, newSession.stateChangeUri));
                log.Info(String.Format("{0} - newMessageURI is {1}", ANI, newSession.newMessageUri));
                log.Info(String.Format("{0} - callerId is {1}", ANI, newSession.callerId));
                log.Info(String.Format("{0} - callId is {1}", ANI, newSession.callId));
                log.Info(String.Format("{0} - notificationType is {1}", ANI, newSession.notificationType));
                log.Info(String.Format("{0} - SessionsUri.AbsoluteUri is {1}", ANI, SessionsUri.AbsoluteUri));

                Client.PostAsJsonAsync<NewSession>(SessionsUri.AbsoluteUri, newSession).ContinueWith(
                    responseTask =>
                    {
                        log.Info(String.Format("{0} - StartCVSession inside PostAsJsonAsync task ", ANI));
                        if (responseTask.Exception != null)
                        {
                            log.Info(String.Format("{0} - Post failed - {1}", ANI, responseTask.Exception.InnerException.Message));
                            log.Info(String.Format("{0} - responseTask.Exception.Message is {1}", ANI, responseTask.Exception.Message));
                            log.Info(String.Format("{0} - responseTask.Exception.InnerException.InnerException.Source is {1}", ANI, responseTask.Exception.InnerException.InnerException.Message));
                            log.Info(String.Format("{0} - responseTask.Exception.InnerException.InnerException.StackTrace is {1}", ANI, responseTask.Exception.InnerException.InnerException.StackTrace));
                            CVStartUpFailed = true;
                            RedirectTwilio(signalURI + "/main-menu.xml");
                        }
                        else
                        {
                            if (responseTask.Result.StatusCode == HttpStatusCode.Created)
                            {
                                log.Info(String.Format("{0} - StartCVSession status code created ", ANI));
                                SessionUri = responseTask.Result.Headers.Location;
                                this.SessionURI = SessionUri;
                                log.Info(String.Format("{0} - SessionUri is {1}", ANI, SessionUri));
                                string fullPath = "";
                                try
                                {
            //                                    log.Info(String.Format("{0} - filePath is {1}", ANI, filePath));
                                    fullPath = filePath + ANI + ".txt";
                                    log.Info(String.Format("{0} - fullPath is {1}", ANI, fullPath));
                                }
                                catch (Exception ex)
                                {
                                    log.Info(String.Format("{0} - exception is {1}", ANI, ex.Message));
                                }

                                StreamWriter swFile;
                                if (File.Exists(fullPath))
                                {
                                    File.Delete(fullPath);  // remove old file
                                }

                                // Create a file to write to.
                                swFile = File.CreateText(fullPath);
                                swFile.WriteLine(String.Format("{0}", SessionUri));
                                swFile.Close();

                                responseTask.Result.Content.ReadAsAsync<Session>(
                                    new List<MediaTypeFormatter> { jsonFormatter }).ContinueWith(
                                        contentTask =>
                                        {
                                            log.Info(String.Format("{0} - StartCVSession async read completed ", ANI));
                                            if (contentTask.Exception == null)
                                            {
                                                log.Info(String.Format("{0} - StartCVSession inside contentTask.Exception = null ", ANI));
                                                cvSession = contentTask.Result;
                                                if (cvSession != null)
                                                {
                                                    log.Info(String.Format("{0} - StartCVSession session created ", ANI));
                                                    ContinueCVSession();
                                                }
                                                else
                                                {
                                                    log.Info(String.Format("{0} - StartCVSession POST {1} did not return recognizable content!", ANI, SessionsUri.AbsoluteUri));
                                                    CVStartUpFailed = true;
                                                }
                                            }
                                            else
                                            {
                                                log.Info(String.Format("{0} - StartCVSession Cannot read the content from POST {1}\nError: {2}",
                                                        ANI, SessionsUri.AbsoluteUri, contentTask.Exception.InnerException.Message));
                                                CVStartUpFailed = true;
                                            }
                                        }
                                    );
                            }
                            else
                            {
                                var msg = responseTask.Result.Content.ReadAsStringAsync().Result;
                                log.Info(String.Format("{0} - StartCVSession POST {1} failed! Reason - {2}, {3}, {4}",
                                                                ANI,
                                                                SessionsUri.AbsoluteUri,
                                                                responseTask.Result.StatusCode,
                                                                responseTask.Result.ReasonPhrase,
                                                                msg));
                                CVStartUpFailed = true;
                            }
                        }
                    });
                log.Info(String.Format("{0} - StartCVSession after Post task", ANI));
            }
            catch (Exception ex)
            {
                log.Info(String.Format("{0} - error in StartCVSession - " + ex.Message, ANI));
                CVStartUpFailed = true;
            }
            log.Info(String.Format("{0} - leaving StartCVSession ", ANI));
        }