/// <summary>
        /// Retreieve selected Task 
        /// </summary>
        /// <param name="activity"></param>
        private async void GetTask(Guid id)
        {
            Views.Shell.SetBusy(true, "Getting Task...");

            if (id == null || id == Guid.Empty)
            {
                CurrentActivity = new Activity()
                {
                    Subject = "Check in with " + CurrentContact.FullName + " on " + DateTime.Now.Date.ToString("d"),
                    ActualEnd = DateTime.Now.Date
                };
            }
            else
            {
                // Retrieve a Task            
                CurrentActivity = await crmservice.RetrieveTask(id);
            }

            Views.Shell.SetBusy(false);
        }
        /// <summary>
        /// This method firstly create task, then complete it if passed task does not have id.
        /// If passed entity has id, then change state back to active first, update data, then 
        /// complete it again.
        /// </summary>
        /// <param name="activity">Activity Record to update</param>
        /// <param name="contact">Contact Record for regarding information</param>
        public async Task UpsertTask(Activity activity, Contact contact)
        {
            // Get AccessToken
            _proxy.AccessToken = await ADALHelper.GetTokenSilent();

            // Instantiate a Task entity.
            Entity task = new Entity("task");
            task["subject"] = activity.Subject;
            task["actualstart"] = activity.ActualEnd.Date;
            task["actualend"] = activity.ActualEnd.Date;
            task["description"] = activity.Notes;
            task["regardingobjectid"] = new EntityReference("contact", contact.Id);
            task.Id = activity.Id;

            // If passed data does not have id, then its new operation.
            if (task.Id == null || task.Id == Guid.Empty)
            {
                // Create record first
                Guid taskId = await _proxy.Create(task);


                // Then complete it
                SetStateRequest setStateRequest = new SetStateRequest()
                {
                    EntityMoniker = new EntityReference("task", taskId),
                    State = new OptionSetValue(1),
                    Status = new OptionSetValue(5)
                };
                await _proxy.Execute(setStateRequest);
            }
            else
            {
                // First set state back to active
                SetStateRequest setStateRequest = new SetStateRequest()
                {
                    EntityMoniker = new EntityReference("task", task.Id),
                    State = new OptionSetValue(0),
                    Status = new OptionSetValue(3)
                };
                await _proxy.Execute(setStateRequest);

                // then update task
                await _proxy.Update(task);

                // finally complete it again
                setStateRequest = new SetStateRequest()
                {
                    EntityMoniker = new EntityReference("task", task.Id),
                    State = new OptionSetValue(1),
                    Status = new OptionSetValue(5)
                };
                await _proxy.Execute(setStateRequest);
            }
        }
        /// <summary>
        /// This method delete task record
        /// </summary>
        /// <param name="activity">Activity Record to delete</param>
        public async Task DeleteTask(Activity activity)
        {
            // Get AccessToken
            _proxy.AccessToken = await ADALHelper.GetTokenSilent();

            // Delete record
            await _proxy.Delete("task", activity.Id);            
        }
        /// <summary>
        /// This method retrieves Activities for the Contact record
        /// </summary>
        /// <param name="id">Contact Id</param>
        /// <returns>List of Completed Activities</returns>
        public async Task<List<Activity>> RetrieveActivitiesOfContact(Guid id)
        {
            // Get AccessToken
            _proxy.AccessToken = await ADALHelper.GetTokenSilent();

            var searchResults = new List<Activity>();

            string fetch = String.Format(@"<fetch version='1.0' output-format='xml-platform' top='50' mapping='logical' distinct='false'>
  <entity name='activitypointer'>
    <attribute name='activitytypecode' />
    <attribute name='subject' />
    <attribute name='statecode' />
    <attribute name='actualend' />
    <order attribute='actualend' descending='true' />
    <filter type='and'>
      <condition attribute='statecode' operator='eq' value='1' />
    </filter>
    <link-entity name='contact' from='contactid' to='regardingobjectid' alias='aa'>
      <filter type='and'>
        <condition attribute='contactid' operator='eq' value='{0}' />
      </filter>
    </link-entity>
  </entity>
</fetch>", id.ToString());

            EntityCollection results = await _proxy.RetrieveMultiple(new FetchExpression(fetch));

            // If there is results then process it.
            if (results.Entities.Count > 0)
            {
                foreach (Entity activityresult in results.Entities)
                {
                    // Instantiate Contact and fullfill partially
                    // Instantiate Activity 
                    Activity activity = new Activity()
                    {
                        Id = activityresult.Id,
                        Subject = activityresult["subject"].ToString(),
                        ActualEndDate = ((System.DateTime)activityresult["actualend"]).ToString("d"),
                        ActivityTypeCode = activityresult["activitytypecode"].ToString()
                    };

                    // Assign icon depending on ActivityTypeCode. Add additional case when you need to.
                    switch (activityresult["activitytypecode"].ToString())
                    {
                        case "appointment":
                            activity.ActivityIcon = "../Assets/icon-activity-appt.png";
                            break;
                        case "task":
                            activity.ActivityIcon = "../Assets/icon-activity-note.png";
                            break;
                        case "phonecall":
                            activity.ActivityIcon = "../Assets/icon-activity-phone.png";
                            break;
                        default:
                            activity.ActivityIcon = "../Assets/icon-activity-generic.png";
                            break;
                    }
                    searchResults.Add(activity);
                }
            }

            return searchResults;
        }
        /// <summary>
        /// This method retrives a taks as late bound. 
        /// </summary>
        /// <param name="id">Activity Id</param>
        /// <returns>Activity Record</returns>
        public async Task<Activity> RetrieveTask(Guid id)
        {
            // Get AccessToken
            _proxy.AccessToken = await ADALHelper.GetTokenSilent();

            Entity result = await _proxy.Retrieve("task", id, new ColumnSet("subject", "actualend", "description"));

            Activity activity = new Activity()
            {
                Id = result.Id,
                Subject = result["subject"].ToString(),
                ActualEnd = new DateTimeOffset((result.Contains("actualend")) ? ((DateTime)result["actualend"]) : DateTime.Now),
                Notes = (result.Contains("description")) ? result["description"].ToString() : ""
            };

            // return result
            return activity;
        }
 /// <summary>
 /// CheckIn contact
 /// </summary>
 public void CheckIn()
 {
     CurrentActivity = null;
     if (IsCheckInVisible)
     {
         CurrentActivity = new Activity()
         {
             Subject = "Check in with " + CurrentContact.FullName + " on " + DateTime.Now.Date.ToString("d"),
             ActualEnd = DateTime.Now.Date
         };
     }
     else
         this.NavigationService.Navigate(typeof(CheckInPage), Guid.Empty);
 }
        /// <summary>
        /// This method delete task record
        /// </summary>
        /// <param name="activity">Activity Record to delete</param>
        public async Task DeleteTask(Activity activity)
        {
            // Get AccessToken
            _proxy.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", await ADALHelper.GetTokenSilent());
            HttpRequestMessage deleteReq = new HttpRequestMessage(new HttpMethod("PATCH"), "tasks(" + activity.Id + ")");

            await _proxy.DeleteAsync("tasks(" + activity.Id + ")");
        }
        /// <summary>
        /// This method firstly create task, then complete it if passed task does not have id.
        /// If passed entity has id, then change state back to active first, update data, then 
        /// complete it again.
        /// </summary>
        /// <param name="activity">Activity Record to update</param>
        /// <param name="contact">Contact Record for regarding information</param>
        public async Task UpsertTask(Activity activity, Contact contact)
        {
            // Get AccessToken
            _proxy.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", await ADALHelper.GetTokenSilent());
            
            // If passed data does not have id, then its new operation.
            if (activity.Id == null || activity.Id == Guid.Empty)
            {                
                // Create task object
                JObject task = new JObject();
                task["subject"] = activity.Subject;

                task["actualstart"] = activity.ActualEnd;
                task["actualend"] = activity.ActualEnd;
                task["description"] = activity.Notes;
                task["*****@*****.**"] = "/contacts(" + contact.Id + ")";
                
                // Create record first
                HttpRequestMessage createReq = new HttpRequestMessage(HttpMethod.Post, "tasks");
                createReq.Content = new StringContent(JsonConvert.SerializeObject(
                    task, new JsonSerializerSettings() { DefaultValueHandling = DefaultValueHandling.Ignore }));

                createReq.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

                HttpResponseMessage result = await _proxy.SendAsync(createReq);

                // Then update the status to close it.
                task = new JObject();
                task["statecode"] = 1;
                task["statuscode"] = 5;
                HttpRequestMessage updateReq = new HttpRequestMessage(new HttpMethod("PATCH"), result.Headers.Location.LocalPath);
                updateReq.Content = new StringContent(JsonConvert.SerializeObject(
                    task, new JsonSerializerSettings() { DefaultValueHandling = DefaultValueHandling.Ignore }), Encoding.UTF8, "application/json");

                result = await _proxy.SendAsync(updateReq);
            }
            else
            {
                // Create Task object to re-open completed task
                JObject task = new JObject();
                task["statecode"] = 0;
                task["statuscode"] = 3;

                HttpRequestMessage updateReq = new HttpRequestMessage(new HttpMethod("PATCH"), "tasks(" + activity.Id + ")");

                updateReq.Content = new StringContent(JsonConvert.SerializeObject(
                    task, new JsonSerializerSettings() { DefaultValueHandling = DefaultValueHandling.Ignore }));
                updateReq.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

                HttpResponseMessage result = await _proxy.SendAsync(updateReq);

                // Create task object to have new values. Set to complete it.
                task = new JObject();
                task["subject"] = activity.Subject;

                task["actualstart"] = activity.ActualEnd;
                task["actualend"] = activity.ActualEnd;
                task["description"] = activity.Notes;
                task["statecode"] = 1;
                task["statuscode"] = 5;

                updateReq = new HttpRequestMessage(new HttpMethod("PATCH"), "tasks(" + activity.Id + ")");

                updateReq.Content = new StringContent(JsonConvert.SerializeObject(
                    task, new JsonSerializerSettings() { DefaultValueHandling = DefaultValueHandling.Ignore }));
                updateReq.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

                result = await _proxy.SendAsync(updateReq);
            }
        }
        /// <summary>
        /// This method retrives a taks as late bound. 
        /// </summary>
        /// <param name="id">Activity Id</param>
        /// <returns>Activity Record</returns>
        public async Task<Activity> RetrieveTask(Guid id)
        {
            // Get AccessToken
            _proxy.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", await ADALHelper.GetTokenSilent());

            HttpResponseMessage retrieveRes = await _proxy.GetAsync("tasks(" + id + ")?$select=subject,actualend,description");

            JToken result = JObject.Parse(retrieveRes.Content.ReadAsStringAsync().Result);

            Activity activity = new Activity()
            {
                Id = id,
                Subject = result["subject"].ToString(),
                ActualEnd = new DateTimeOffset((result["actualend"] != null) ? ((DateTime)result["actualend"]) : DateTime.Now),
                Notes = (result["description"] != null) ? result["description"].ToString() : ""
            };

            // return result
            return activity;
        }
        /// <summary>
        /// This method retrieves Activities for the Contact record
        /// </summary>
        /// <param name="id">Contact Id</param>
        /// <returns>List of Completed Activities</returns>
        public async Task<List<Activity>> RetrieveActivitiesOfContact(Guid id)
        {
            // Get AccessToken
            _proxy.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", await ADALHelper.GetTokenSilent());

            var searchResults = new List<Activity>();

            string fetch = String.Format(@"<fetch version='1.0' output-format='xml-platform' top='50' mapping='logical' distinct='false'>
  <entity name='activitypointer'>
    <attribute name='activityid' />
    <attribute name='activitytypecode' />
    <attribute name='subject' />
    <attribute name='statecode' />
    <attribute name='actualend' />
    <order attribute='actualend' descending='true' />
    <filter type='and'>
      <condition attribute='statecode' operator='eq' value='1' />
    </filter>
    <link-entity name='contact' from='contactid' to='regardingobjectid' alias='aa'>
      <filter type='and'>
        <condition attribute='contactid' operator='eq' value='{0}' />
      </filter>
    </link-entity>
  </entity>
</fetch>", id.ToString());

            // Use FetchXML to get data
            HttpResponseMessage retrieveRes = await _proxy.GetAsync(string.Format("activitypointers?fetchXml={0}", System.Uri.EscapeDataString(fetch)));
            JToken results = JObject.Parse(retrieveRes.Content.ReadAsStringAsync().Result)["value"];

            foreach (JToken activityresult in results)
            {
                // Instantiate Contact and fullfill partially
                // Instantiate Activity 
                Activity activity = new Activity()
                {
                    Id = (Guid)activityresult["activityid"],
                    Subject = activityresult["subject"].ToString(),
                    ActualEndDate = ((System.DateTime)activityresult["actualend"]).ToString("d"),
                    ActivityTypeCode = activityresult["activitytypecode"].ToString()
                };

                // Assign icon depending on ActivityTypeCode. Add additional case when you need to.
                switch (activityresult["activitytypecode"].ToString())
                {
                    case "appointment":
                        activity.ActivityIcon = "../Assets/icon-activity-appt.png";
                        break;
                    case "task":
                        activity.ActivityIcon = "../Assets/icon-activity-note.png";
                        break;
                    case "phonecall":
                        activity.ActivityIcon = "../Assets/icon-activity-phone.png";
                        break;
                    default:
                        activity.ActivityIcon = "../Assets/icon-activity-generic.png";
                        break;
                }
                searchResults.Add(activity);
            }

            return searchResults;
        }