public async Task <CalendarEvent> AddOrUpdateCalendarEvent(CalendarEvent calendarEvent)
        {
            // Query to see if event already exists. If so, do Update instead.
            string[] queryParameters =
            {
                String.Format(CultureInfo.InvariantCulture, "$filter=contains(Subject,'Spid:[{0}]')",
                              calendarEvent.Spid),
            };

            string requestUrl = String.Format(CultureInfo.InvariantCulture,
                                              "{0}/Me/Calendar/Events?{1}",
                                              _serviceInfo.ApiEndpoint,
                                              String.Join("&", queryParameters));

            int calendarItemCount = (await GetCalendarEventsRequest(requestUrl, true));

            if (calendarItemCount > 1)
            {
                return(null);
            }
            if (calendarItemCount == 1)
            {
                return(await UpdateCalendarEvent(calendarEvent));
            }

            requestUrl = String.Format(CultureInfo.InvariantCulture,
                                       "{0}/Me/Calendar/Events",
                                       _serviceInfo.ApiEndpoint);

            // string postData = JsonConvert.SerializeObject(calendarEvent);
            string postData = CommonCode.Serialize(calendarEvent);

            Func <HttpRequestMessage> requestCreator = () =>
            {
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, requestUrl);
                request.Content = new StringContent(postData);
                request.Headers.Add("Accept", "application/json;odata=minimalmetadata");
                request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                return(request);
            };

            HttpResponseMessage response = await Office365Helper.SendRequestAsync(_serviceInfo, _httpClient, requestCreator);

            string responseString = await response.Content.ReadAsStringAsync();

            if (!response.IsSuccessStatusCode)
            {
                await Office365Helper.ShowErrorMessageAsync(_serviceInfo, responseString);

                return(null);
            }

            // CalendarEvent c = JsonConvert.DeserializeObject<CalendarEvent>(responseString);
            CalendarEvent c = CommonCode.Deserialize <CalendarEvent>(responseString);

            return(c);
        }
        private async Task <int> GetCalendarEventsRequest(string requestUrl, bool firstPage)
        {
            string errorMessage = string.Empty;

            try
            {
                Func <HttpRequestMessage> requestCreator = () =>
                {
                    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
                    request.Headers.Add("Accept", "application/json;odata=minimalmetadata");
                    return(request);
                };

                HttpResponseMessage response = await Office365Helper.SendRequestAsync(_serviceInfo, _httpClient, requestCreator);

                string responseString = await response.Content.ReadAsStringAsync();

                if (!response.IsSuccessStatusCode)
                {
                    await Office365Helper.ShowErrorMessageAsync(_serviceInfo, responseString);

                    return(0);
                }

                JsonValue jsonResponse = JsonValue.Parse(responseString);
                JsonArray events       = jsonResponse.GetObject().GetNamedArray("value");
                if (events.Count > 0)
                {
                    foreach (JsonValue o in events)
                    {
                        //CalendarEvent c = JsonConvert.DeserializeObject<CalendarEvent>(o.Stringify());
                        CalendarEvent c    = CommonCode.Deserialize <CalendarEvent>(o.Stringify());
                        JsonObject    json = JsonObject.Parse(o.Stringify());
                        c.Id = json.GetNamedString("Id");
                        _events.Add(c);

                        _calendarItemIdForUpdate = c.Id;
                    }
                    return(events.Count);
                }
                else
                {
                    return(0);
                }
            }
            catch (Exception ex)
            {
                errorMessage = ex.Message;
            }

            await Office365Helper.ShowErrorMessageAsync("Unexpected error retrieving events", errorMessage);

            return(0);
        }
        public async Task <CalendarEvent> UpdateCalendarEvent(CalendarEvent calendarEvent)
        {
            string requestUrl = String.Format(CultureInfo.InvariantCulture,
                                              "{0}/Me/Calendar/Events('{1}')",
                                              _serviceInfo.ApiEndpoint,
                                              _calendarItemIdForUpdate);

            // string postData = JsonConvert.SerializeObject(calendarEvent);
            string postData = CommonCode.Serialize(calendarEvent);

            Func <HttpRequestMessage> requestCreator = () =>
            {
                var patch = new HttpMethod("PATCH");
                HttpRequestMessage request = new HttpRequestMessage(patch, requestUrl);
                request.Content = new StringContent(postData);
                request.Headers.Add("Accept", "application/json;odata=minimalmetadata");
                request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                return(request);
            };

            HttpResponseMessage response = await Office365Helper.SendRequestAsync(_serviceInfo, _httpClient, requestCreator);

            string responseString = await response.Content.ReadAsStringAsync();

            if (!response.IsSuccessStatusCode)
            {
                await Office365Helper.ShowErrorMessageAsync(_serviceInfo, responseString);

                return(null);
            }

            // CalendarEvent c = JsonConvert.DeserializeObject<CalendarEvent>(responseString);
            CalendarEvent c = CommonCode.Deserialize <CalendarEvent>(responseString);

            return(c);
        }
        public async Task <List <Session> > GetSessions()
        {
            List <Session> sessionList  = new List <Session>();
            string         errorMessage = String.Empty;

            try
            {
                // Obtain information for communicating with the service:
                Office365ServiceInfo serviceInfo = await Office365ServiceInfo.GetSharePointServiceInfoAsync(
                    AppSettings.SharePointHostResourceId,
                    AppSettings.SharePointSessionListUri);

                if (!serviceInfo.HasValidAccessToken)
                {
                    throw new Exception("Unable to get SharePoint ServiceInfo");
                }

                // Create a URL for retrieving the data:
                string[] queryParameters = new string[]
                {
                    "select=title,start,end,description,code"
                };

                string requestUrl = String.Format(CultureInfo.InvariantCulture,
                                                  "{0}/items?{1}",
                                                  serviceInfo.ApiEndpoint,
                                                  String.Join("&", queryParameters));

                // Prepare the HTTP request:
                using (HttpClient client = new HttpClient())
                {
                    Func <HttpRequestMessage> requestCreator = () =>
                    {
                        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
                        request.Headers.Add("Accept", "application/json;odata=verbose");
                        return(request);
                    };

                    // Send the request using a helper method, which will add an authorization header to the request,
                    // and automatically retry with a new token if the existing one has expired.
                    using (HttpResponseMessage response = await Office365Helper.SendRequestAsync(
                               serviceInfo, client, requestCreator))
                    {
                        // Read the response and deserialize the data:
                        string responseString = await response.Content.ReadAsStringAsync();

                        if (!response.IsSuccessStatusCode)
                        {
                            await Office365Helper.ShowErrorMessageAsync(serviceInfo, responseString);

                            return(sessionList);
                        }

                        //sessionList = JObject.Parse(responseString)["d"]["results"].ToObject<List<Session>>();
                        JsonValue  jsonResponse  = JsonValue.Parse(responseString);
                        JsonObject d             = jsonResponse.GetObject().GetNamedObject("d");
                        JsonArray  sessionsArray = d.GetObject().GetNamedArray("results");
                        if (sessionsArray.Count > 0)
                        {
                            foreach (JsonValue o in sessionsArray)
                            {
                                Session s = CommonCode.Deserialize <Session>(o.Stringify());
                                sessionList.Add(s);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                errorMessage = ex.Message;
            }

            if (!sessionList.Any())
            {
                await Office365Helper.ShowErrorMessageAsync("No Sessions Available.", errorMessage);
            }

            return(sessionList);
        }