GetTokenForUserAsync() 공개 정적인 메소드

Get Token for User.
public static GetTokenForUserAsync ( ) : Task
리턴 Task
예제 #1
0
        public static async Task <string> GetSharingLinkAsync(string Id)
        {
            string  sharingLinkUrl = null;
            JObject jResult        = null;

            try
            {
                HttpClient client = new HttpClient();
                var        token  = await AuthenticationHelper.GetTokenForUserAsync();

                client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);

                string postContent           = "{'type': 'view','scope': 'anonymous'}";
                var    createBody            = new StringContent(postContent, System.Text.Encoding.UTF8, "application/json");
                Uri    photoEndpoint         = new Uri("https://graph.microsoft.com/v1.0/me/drive/items/" + Id + "/createLink");
                HttpResponseMessage response = await client.PostAsync(photoEndpoint, createBody);

                if (response.IsSuccessStatusCode)
                {
                    string responseContent = await response.Content.ReadAsStringAsync();

                    jResult = JObject.Parse(responseContent);
                    JToken sharingLink = jResult["link"];
                    sharingLinkUrl = (string)sharingLink["webUrl"];
                }
                else
                {
                    return(null);
                }
            }

            catch (Exception e)
            {
                throw new Exception("We could not get the sharing link. The request returned this status code: " + e.Message);
            }

            return(sharingLinkUrl);
        }
예제 #2
0
        /// <summary>
        /// Compose and send a new email.
        /// </summary>
        /// <param name="subject">The subject line of the email.</param>
        /// <param name="bodyContent">The body of the email.</param>
        /// <param name="recipients">A semicolon-separated list of email addresses.</param>
        /// <returns></returns>
        internal async Task ComposeAndSendMailAsync(string subject,
                                                    string bodyContent,
                                                    string recipients)
        {
            // Get current user photo
            Stream photoStream = await GetCurrentUserPhotoStreamAsync();


            // If the user doesn't have a photo, or if the user account is MSA, we use a default photo

            if (photoStream == null)
            {
                StorageFile file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync("test.jpg");

                photoStream = (await file.OpenReadAsync()).AsStreamForRead();
            }

            MemoryStream photoStreamMS = new MemoryStream();

            // Copy stream to MemoryStream object so that it can be converted to byte array.
            photoStream.CopyTo(photoStreamMS);
            byte[] photoStreamBytes  = photoStreamMS.ToArray();
            string photoStreamBase64 = Convert.ToBase64String(photoStreamBytes);

            string photoFileId = await UploadFileToOneDriveAsync(photoStreamMS.ToArray());

            string attachments = "{'contentBytes':'" + photoStreamBase64 + "',"
                                 + "'@odata.type' : '#microsoft.graph.fileAttachment',"
                                 + "'contentType':'image/png',"
                                 + "'name':'me.png'}";

            // Get the sharing link and insert it into the message body.
            string sharingLinkUrl = await GetSharingLinkAsync(photoFileId);

            string bodyContentWithSharingLink = String.Format(bodyContent, sharingLinkUrl);

            // Prepare the recipient list
            string[] splitter = { ";" };
            var      splitRecipientsString = recipients.Split(splitter, StringSplitOptions.RemoveEmptyEntries);
            string   recipientsJSON        = null;

            int n = 0;

            foreach (string recipient in splitRecipientsString)
            {
                if (n == 0)
                {
                    recipientsJSON += "{'EmailAddress':{'Address':'" + recipient.Trim() + "'}}";
                }
                else
                {
                    recipientsJSON += ", {'EmailAddress':{'Address':'" + recipient.Trim() + "'}}";
                }
                n++;
            }

            try
            {
                HttpClient client = new HttpClient();
                var        token  = await AuthenticationHelper.GetTokenForUserAsync();

                client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);

                // Build contents of post body and convert to StringContent object.
                // Using line breaks for readability.
                string postBody = "{'Message':{"
                                  + "'Body':{ "
                                  + "'Content': '" + bodyContentWithSharingLink + "',"
                                  + "'ContentType':'HTML'},"
                                  + "'Subject':'" + subject + "',"
                                  + "'ToRecipients':[" + recipientsJSON + "],"
                                  + "'Attachments':[" + attachments + "]},"
                                  + "'SaveToSentItems':true}";

                var emailBody = new StringContent(postBody, System.Text.Encoding.UTF8, "application/json");

                HttpResponseMessage response = await client.PostAsync(new Uri("https://graph.microsoft.com/v1.0/me/microsoft.graph.SendMail"), emailBody);

                if (!response.IsSuccessStatusCode)
                {
                    throw new Exception("We could not send the message: " + response.StatusCode.ToString());
                }
            }

            catch (Exception e)
            {
                throw new Exception("We could not send the message: " + e.Message);
            }
        }