async void OnSignInSignOut(object sender, EventArgs e)
        {
            if (SignInSignOutBtn.Text == "connect")
            {
                graphClient = AuthenticationHelper.GetAuthenticatedClient();
                var currentUserObject = await graphClient.Me.Request().GetAsync();

                App.Username  = currentUserObject.DisplayName;
                App.UserEmail = currentUserObject.UserPrincipalName;

                InfoText.Text             = "Hello, " + App.Username + ". " + AppResources.SendMailPrompt;
                MailButton.IsVisible      = true;
                EmailAddressBox.IsVisible = true;
                EmailAddressBox.Text      = App.UserEmail;
                SignInSignOutBtn.Text     = "disconnect";
            }
            else
            {
                AuthenticationHelper.SignOut();
                InfoText.Text             = AppResources.ConnectPrompt;
                SignInSignOutBtn.Text     = "connect";
                MailButton.IsVisible      = false;
                EmailAddressBox.Text      = "";
                EmailAddressBox.IsVisible = false;
            }
        }
Пример #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>
        public async Task ComposeAndSendMailAsync(string subject,
                                                  string bodyContent,
                                                  string recipients)
        {
            // Prepare the recipient list
            string[]         splitter = { ";" };
            var              splitRecipientsString = recipients.Split(splitter, StringSplitOptions.RemoveEmptyEntries);
            List <Recipient> recipientList         = new List <Recipient>();

            foreach (string recipient in splitRecipientsString)
            {
                recipientList.Add(new Recipient {
                    EmailAddress = new EmailAddress {
                        Address = recipient.Trim()
                    }
                });
            }

            try
            {
                var graphClient = AuthenticationHelper.GetAuthenticatedClient();

                var email = new Message
                {
                    Body = new ItemBody
                    {
                        Content     = bodyContent,
                        ContentType = BodyType.Html,
                    },
                    Subject      = subject,
                    ToRecipients = recipientList,
                };

                try
                {
                    await graphClient.Me.SendMail(email, true).Request().PostAsync();
                }
                catch (ServiceException exception)
                {
                    throw new Exception("We could not send the message: " + exception.Error == null ? "No error message returned." : exception.Error.Message);
                }
            }

            catch (Exception e)
            {
                throw new Exception("We could not send the message: " + e.Message);
            }
        }
Пример #3
0
        private async void PeopleButton_Clicked(object sender, EventArgs e)
        {
            graphClient = AuthenticationHelper.GetAuthenticatedClient();
            User currentUserObject = null;

            try
            {
                currentUserObject = await graphClient.Me.Request().GetAsync();
            }
            catch (Exception exception)
            {
                Debug.WriteLine(exception.StackTrace);
                return;
            }

            await Navigation.PushAsync(new PeoplePage(currentUserObject));
        }
Пример #4
0
        public static async Task <Permission> GetSharingLinkAsync(string Id)
        {
            Permission permission = null;

            try
            {
                var graphClient = AuthenticationHelper.GetAuthenticatedClient();
                permission = await graphClient.Me.Drive.Items[Id].CreateLink("view").Request().PostAsync();
            }

            catch (ServiceException)
            {
                return(null);
            }

            return(permission);
        }
Пример #5
0
        // Gets the stream content of the signed-in user's photo.
        // This snippet doesn't work with consumer accounts.
        public async Task <Stream> GetCurrentUserPhotoStreamAsync()
        {
            Stream currentUserPhotoStream = null;

            try
            {
                var graphClient = AuthenticationHelper.GetAuthenticatedClient();
                currentUserPhotoStream = await graphClient.Me.Photo.Content.Request().GetAsync();
            }

            // If the user account is MSA (not work or school), the service will throw an exception.
            catch (ServiceException)
            {
                return(null);
            }

            return(currentUserPhotoStream);
        }
Пример #6
0
        private async void MailButton_Click(object sender, EventArgs e)
        {
            var mailAddress = EmailAddressBox.Text;

            try
            {
                byte[] pic = await _mailHelper.ComposeAndSendMailAsync(AppResources.MailSubject, AppResources.MailContents, mailAddress);

                InfoText.Text = string.Format(AppResources.SendMailSuccess, mailAddress);
                var graphClient = AuthenticationHelper.GetAuthenticatedClient();
                ProfileImage.Source    = ImageSource.FromStream(() => new MemoryStream(pic));
                ProfileImage.IsVisible = true;
            }
            catch (ServiceException exception)
            {
                InfoText.Text = AppResources.MailErrorMessage;
                throw new Exception("We could not send the message: " + exception.Error == null ? "No error message returned." : exception.Error.Message);
            }
        }
Пример #7
0
        // Uploads the specified file to the user's root OneDrive directory.
        public async Task <DriveItem> UploadFileToOneDriveAsync(byte[] file)
        {
            DriveItem uploadedFile = null;

            try
            {
                var          graphClient = AuthenticationHelper.GetAuthenticatedClient();
                MemoryStream fileStream  = new MemoryStream(file);
                uploadedFile = await graphClient.Me.Drive.Root.ItemWithPath("me.png").Content.Request().PutAsync <DriveItem>(fileStream);
            }


            catch (ServiceException)
            {
                return(null);
            }

            return(uploadedFile);
        }
Пример #8
0
        async void OnSignInSignOut(object sender, EventArgs e)
        {
            if (SignInSignOutBtn.Text == "connect")
            {
                graphClient = AuthenticationHelper.GetAuthenticatedClient();
                User currentUserObject = null;
                try
                {
                    currentUserObject = await graphClient.Me.Request().GetAsync();
                }
                catch (Exception exception)
                {
                    Debug.WriteLine(exception.StackTrace);

                    return;
                }
                App.Username  = currentUserObject.DisplayName;
                App.UserEmail = currentUserObject.UserPrincipalName;

                InfoText.Text             = "Hello, " + App.Username + ". " + AppResources.SendMailPrompt;
                MailButton.IsVisible      = true;
                EmailAddressBox.IsVisible = true;
                EmailAddressBox.Text      = App.UserEmail;
                SignInSignOutBtn.Text     = "disconnect";
                PeopleButton.IsVisible    = true;
            }
            else
            {
                AuthenticationHelper.SignOut();
                InfoText.Text             = AppResources.ConnectPrompt;
                SignInSignOutBtn.Text     = "connect";
                MailButton.IsVisible      = false;
                EmailAddressBox.Text      = "";
                EmailAddressBox.IsVisible = false;
                PeopleButton.IsVisible    = false;
            }
        }
Пример #9
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>
        public 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)
            {
                var assembly = typeof(MailHelper).GetTypeInfo().Assembly;
                photoStream = assembly.GetManifestResourceStream("XamarinConnect.test.jpg");
            }

            MemoryStream photoStreamMS = new MemoryStream();

            // Copy stream to MemoryStream object so that it can be converted to byte array.
            photoStream.CopyTo(photoStreamMS);

            DriveItem photoFile = await UploadFileToOneDriveAsync(photoStreamMS.ToArray());

            MessageAttachmentsCollectionPage attachments = new MessageAttachmentsCollectionPage();

            attachments.Add(new FileAttachment
            {
                ODataType    = "#microsoft.graph.fileAttachment",
                ContentBytes = photoStreamMS.ToArray(),
                ContentType  = "image/png",
                Name         = "me.png"
            });

            // Get the sharing link and insert it into the message body.
            Permission sharingLink = await GetSharingLinkAsync(photoFile.Id);

            string bodyContentWithSharingLink = String.Format(bodyContent, sharingLink.Link.WebUrl);


            // Prepare the recipient list
            string[]         splitter = { ";" };
            var              splitRecipientsString = recipients.Split(splitter, StringSplitOptions.RemoveEmptyEntries);
            List <Recipient> recipientList         = new List <Recipient>();

            foreach (string recipient in splitRecipientsString)
            {
                recipientList.Add(new Recipient {
                    EmailAddress = new EmailAddress {
                        Address = recipient.Trim()
                    }
                });
            }

            try
            {
                var graphClient = AuthenticationHelper.GetAuthenticatedClient();

                var email = new Message
                {
                    Body = new ItemBody
                    {
                        Content     = bodyContentWithSharingLink,
                        ContentType = BodyType.Html,
                    },
                    Subject      = subject,
                    ToRecipients = recipientList,
                    Attachments  = attachments
                };

                try
                {
                    await graphClient.Me.SendMail(email, true).Request().PostAsync();
                }
                catch (ServiceException exception)
                {
                    throw new Exception("We could not send the message: " + exception.Error == null ? "No error message returned." : exception.Error.Message);
                }
            }

            catch (Exception e)
            {
                throw new Exception("We could not send the message: " + e.Message);
            }
        }
        public async void GetPeople()
        {
            //Debug.WriteLine("GetAuthClient...");
            var graphClient = AuthenticationHelper.GetAuthenticatedClient();

            try
            {
                //Debug.WriteLine("Attempting request...");
                //var me = await graphClient.Me.Request().GetAsync();

                /*  Version 1.2.1 of Microsoft.Graph
                 * The  Microsoft.Graph .NET Library doesn't have a method to list people
                 * The People list will return the people relevent to a person based on thier emails and other documents..a score is attached among other properties
                 *
                 * To call this API with the assistance of the Microsoft.Graph API we will get the Me request URL for the signed in user and
                 * obtain the people list for them by appending /people onto the URL and calling the API with it.
                 * The JSON object is handled dynamically since the returned JSON has three objects and we are only concerned with one of them--the list of people.
                 *
                 * the latest version of Microsoft.Graph has a Me.People call built in.
                 */
                //string requestUrl = graphClient.Me.Request().RequestUrl;
                string requestUrl = graphClient.Users.Request().RequestUrl;

                requestUrl = requestUrl + "('" + CurrentUser.Id + "')/people";

                Debug.WriteLine(requestUrl);

                HttpRequestMessage hrm = new HttpRequestMessage(HttpMethod.Get, requestUrl);


                await graphClient.AuthenticationProvider.AuthenticateRequestAsync(hrm);

                var http = graphClient.HttpProvider;

                HttpResponseMessage response = await graphClient.HttpProvider.SendAsync(hrm);

                if (response.IsSuccessStatusCode)
                {
                    var content = await response.Content.ReadAsStringAsync();

                    //var people = graphClient.HttpProvider.Serializer.DeserializeObject<People>(content);

                    dynamic dyn = JsonConvert.DeserializeObject(content);

                    foreach (var obj in dyn.value)
                    {
                        People.Add(new User()
                        {
                            DisplayName = obj.displayName, Id = obj.id, Mail = obj.mail, UserPrincipalName = obj.userPrincipalName
                        });
                    }


                    //Debug.WriteLine(content);
                }
            }
            catch (Exception exp)
            {
                Debug.WriteLine(exp.Message);  //<sarcasm> some awesome, fine-grained error handling </sarcasm>
            }
        }