/// <summary>
        /// Send an HTTP request, with authorization. If the request fails due to an unauthorized exception,
        ///     this method will try to renew the access token in serviceInfo and try again.
        /// </summary>
        public static async Task <HttpResponseMessage> SendRequestAsync(
            Office365ServiceInfo serviceInfo, HttpClient client, Func <HttpRequestMessage> requestCreator)
        {
            using (HttpRequestMessage request = requestCreator.Invoke())
            {
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", serviceInfo.AccessToken);
                request.Headers.UserAgent.Add(new ProductInfoHeaderValue(AppPrincipalId, String.Empty));
                HttpResponseMessage response = await client.SendAsync(request);

                // Check if the server responded with "Unauthorized". If so, it might be a real authorization issue, or
                //     it might be due to an expired access token. To be sure, renew the token and try one more time:
                if (response.StatusCode == HttpStatusCode.Unauthorized)
                {
                    Office365Cache.GetAccessToken(serviceInfo.ResourceId).RemoveFromCache();
                    serviceInfo.AccessToken = GetAccessTokenFromRefreshToken(serviceInfo.ResourceId);

                    // Create and send a new request:
                    using (HttpRequestMessage retryRequest = requestCreator.Invoke())
                    {
                        retryRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", serviceInfo.AccessToken);
                        retryRequest.Headers.UserAgent.Add(new ProductInfoHeaderValue(AppPrincipalId, String.Empty));
                        response = await client.SendAsync(retryRequest);
                    }
                }

                // Return either the original response, or the response from the second attempt:
                return(response);
            }
        }
Exemple #2
0
        public static async Task <UserProfile> GetUserProfileRequest()
        {
            UserProfile userProfile  = null;
            string      errorMessage = string.Empty;

            try
            {
                // Obtain information for communicating with the service:
                Office365ServiceInfo serviceInfo = await Office365ServiceInfo.GetActiveDirectoryServiceInfoAsync();

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

                // Create a URL for retrieving the data:
                string[] queryParameters = { "api-version=2013-11-08" };
                string   requestUrl      = String.Format(CultureInfo.InvariantCulture,
                                                         "{0}/me?{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=minimalmetadata");
                        return(request);
                    };

                    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(userProfile);
                        }

                        userProfile = JsonConvert.DeserializeObject <UserProfile>(responseString);
                    }
                }
            }
            catch (Exception ex)
            {
                errorMessage = ex.Message;
            }

            return(userProfile);
        }
        private static async Task <SampleModel.Exchange.CalendarEvent[]> GetCalendarEvents()
        {
            // Obtain information for communicating with the service:
            Office365ServiceInfo serviceInfo = await Office365ServiceInfo.GetExchangeServiceInfoAsync();

            if (!serviceInfo.HasValidAccessToken)
            {
                return(null);
            }

            // Create a URL for retrieving the data:
            string[] queryParameters =
            {
                String.Format(CultureInfo.InvariantCulture, "$filter=End ge {0}Z", DateTime.UtcNow.ToString("s")),
                "$top=10",
                "$select=Subject,Start,End"
            };
            string requestUrl = String.Format(CultureInfo.InvariantCulture,
                                              "{0}/Me/Calendar/Events?{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=minimalmetadata");
                    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(null);
                    }

                    var events = JObject.Parse(responseString)["value"].ToObject <SampleModel.Exchange.CalendarEvent[]>();
                    events = events.OrderBy(e => e.Start).ToArray();
                    return(events);
                }
            }
        }
        private static async Task <SampleModel.SharePoint.SharePointFile[]> GetSharePointFiles()
        {
            // Obtain information for communicating with the service:
            Office365ServiceInfo serviceInfo = await Office365ServiceInfo.GetSharePointOneDriveServiceInfoAsync();

            if (!serviceInfo.HasValidAccessToken)
            {
                return(null);
            }

            // Create a URL for retrieving the data:
            string[] queryParameters =
            {
                "$orderby=Name",
                "$expand=Author",
                "$select=Name,Author,TimeLastModified"
            };
            string requestUrl = String.Format(CultureInfo.InvariantCulture,
                                              "{0}/Folders('Shared%20with%20Everyone')/Files?{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(null);
                    }

                    return(JObject.Parse(responseString)["d"]["results"].ToObject <SampleModel.SharePoint.SharePointFile[]>());
                }
            }
        }
Exemple #5
0
        public static async Task SendMail(Message mailMessage)
        {
            // Obtain information for communicating with the service:
            Office365ServiceInfo serviceInfo = await Office365ServiceInfo.GetExchangeServiceInfoAsync();

            if (!serviceInfo.HasValidAccessToken)
            {
                await Office365Helper.ShowErrorMessageAsync("Unable to get Exchange ServiceInfo", string.Empty);

                return;
            }

            HttpClient client = new HttpClient();

            // Create a URL for retrieving the data:
            string[] queryParameters = new string[]
            {
                "MessageDisposition=SendOnly"
            };

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

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

            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);
            };

            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);
                }

                // TODO maybe display a confirmation.
            }
        }
Exemple #6
0
        private static async Task <SampleModel.ActiveDirectory.UserProfile> GetActiveDirectoryProfile()
        {
            // Obtain information for communicating with the service:
            Office365ServiceInfo serviceInfo = await Office365ServiceInfo.GetActiveDirectoryServiceInfoAsync();

            if (!serviceInfo.HasValidAccessToken)
            {
                return(null);
            }

            // Create a URL for retrieving the data:
            string[] queryParameters = { "api-version=2013-11-08" };
            string   requestUrl      = String.Format(CultureInfo.InvariantCulture,
                                                     "{0}/{1}/users/{2}?{3}",
                                                     serviceInfo.ApiEndpoint,
                                                     WebUtility.UrlEncode(Office365Helper.TenantId),
                                                     WebUtility.UrlEncode(Office365Helper.UserId),
                                                     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=minimalmetadata");
                    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(null);
                    }

                    return(JsonConvert.DeserializeObject <SampleModel.ActiveDirectory.UserProfile>(responseString));
                }
            }
        }
        public async Task <ActionResult> Index()
        {
            // Obtain information for communicating with the service:
            Office365ServiceInfo serviceInfo = Office365ServiceInfo.GetExchangeServiceInfo();

            if (!serviceInfo.HasValidAccessToken)
            {
                return(Redirect(serviceInfo.GetAuthorizationUrl(Request.Url)));
            }

            string requestUrl = String.Format(CultureInfo.InvariantCulture,
                                              "{0}/Me/Inbox/Messages",
                                              serviceInfo.ApiEndpoint
                                              );

            // 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.metadata=full");
                    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 Office365CommonController.SendRequestAsync(
                           serviceInfo, client, requestCreator))
                {
                    // Read the response and deserialize the data:
                    string responseString = await response.Content.ReadAsStringAsync();

                    if (!response.IsSuccessStatusCode)
                    {
                        return(Office365CommonController.ShowErrorMessage(serviceInfo, responseString));
                    }

                    var messageContext = Newtonsoft.Json.JsonConvert.DeserializeObject <Message_odataContext>(responseString);

                    var messages = messageContext.Messages;

                    return(View(messages));
                }
            }
        }
        /// <summary>
        /// A static method that routes errors to a single centralized error-handler.
        /// This method will attempt to extract a human-readable error from the response string,
        /// based on the the format of the data and the error handling scheme of the service.
        /// </summary>
        public static ActionResult ShowErrorMessage(Office365ServiceInfo serviceInfo, string responseString)
        {
            string message, errorDetails;

            try
            {
                message      = serviceInfo.ParseErrorMessage(responseString);
                errorDetails = responseString;
            }
            catch (Exception e)
            {
                message      = "An unexpected error has occurred.";
                errorDetails = "Exception when parsing response string: " + e.ToString() +
                               "\n\nResponse string was " + responseString;
            }
            return(ShowErrorMessage(message, errorDetails));
        }
        public static async Task <CalendarEvents> CreateCalendarInstance()
        {
            CalendarEvents calendarEvents = new CalendarEvents();

            // Obtain information for communicating with the service:
            calendarEvents._serviceInfo = await Office365ServiceInfo.GetExchangeServiceInfoAsync();

            if (!calendarEvents._serviceInfo.HasValidAccessToken)
            {
                await Office365Helper.ShowErrorMessageAsync("Unable to get Exchange ServiceInfo", string.Empty);

                return(null);
            }

            calendarEvents._httpClient = new HttpClient();

            return(calendarEvents);
        }
        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);
        }