static void Main(string[] args) { Console.WriteLine("Welcome to the C# Console Connect Sample!\n"); try { //********************************************************************* // setup Microsoft Graph Client for user. //********************************************************************* if (Constants.ClientId != "ENTER_YOUR_CLIENT_ID") { graphClient = AuthenticationHelper.GetAuthenticatedClient(); if (graphClient != null) { var user = graphClient.Me.Request().GetAsync().Result; string userId = user.Id; string mailAddress = user.UserPrincipalName; string displayName = user.DisplayName; Console.WriteLine("Hello, " + displayName + ". Would you like to get your trending information?"); Console.WriteLine("Press any key to continue."); Console.ReadKey(); Console.WriteLine(); // TODO: Enter code to access trending information. Console.WriteLine("\n\nPress any key to continue."); Console.ReadKey(); } else { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("We weren't able to create a GraphServiceClient for you. Please check the output for errors."); Console.ResetColor(); Console.ReadKey(); return; } } else { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("You haven't configured a value for ClientId in Constants.cs. Please follow the Readme instructions for configuring this application."); Console.ResetColor(); Console.ReadKey(); return; } } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Getting your trending information failed with the following message: {0}", ex.Message); if (ex.InnerException != null) { Console.WriteLine("Error detail: {0}", ex.InnerException.Message); } Console.ResetColor(); Console.ReadKey(); return; } }
public static Permission GetSharingLinkAsync(string Id) { Permission permission = null; try { var graphClient = AuthenticationHelper.GetAuthenticatedClient(); permission = graphClient.Me.Drive.Items[Id].CreateLink("view").Request().PostAsync().Result; } catch (ServiceException) { return(null); } return(permission); }
// Gets the stream content of the signed-in user's photo. // This snippet doesn't work with consumer accounts. public static Stream GetCurrentUserPhotoStreamAsync() { Stream currentUserPhotoStream = null; try { var graphClient = AuthenticationHelper.GetAuthenticatedClient(); currentUserPhotoStream = graphClient.Me.Photo.Content.Request().GetAsync().Result; } // If the user account is MSA (not work or school), the service will throw an exception. catch (Exception) { return(null); } return(currentUserPhotoStream); }
// Uploads the specified file to the user's root OneDrive directory. public static DriveItem UploadFileToOneDriveAsync(byte[] file) { DriveItem uploadedFile = null; try { var graphClient = AuthenticationHelper.GetAuthenticatedClient(); MemoryStream fileStream = new MemoryStream(file); uploadedFile = graphClient.Me.Drive.Root.ItemWithPath("me.png").Content.Request().PutAsync <DriveItem>(fileStream).Result; } catch (ServiceException) { return(null); } return(uploadedFile); }
/// <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 static void ComposeAndSendMailAsync(string subject, string bodyContent, string recipients) { // Get current user photo Stream photoStream = GetCurrentUserPhotoStreamAsync(); // If the user doesn't have a photo, or if the user account is MSA, we use a default photo if (photoStream == null) { photoStream = new FileStream("test.jpg", FileMode.Open); } MemoryStream photoStreamMS = new MemoryStream(); // Copy stream to MemoryStream object so that it can be converted to byte array. photoStream.CopyTo(photoStreamMS); photoStream.Close(); DriveItem photoFile = 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 = 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 { 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); } }
static void Main(string[] args) { Console.WriteLine("Welcome to the C# Console Connect Sample!\n"); try { //********************************************************************* // setup Microsoft Graph Client for user. //********************************************************************* if (Constants.ClientId != "ENTER_YOUR_CLIENT_ID") { graphClient = AuthenticationHelper.GetAuthenticatedClient(); if (graphClient != null) { bool sendMail = true; while (sendMail) { var user = graphClient.Me.Request().GetAsync().Result; string userId = user.Id; string mailAddress = user.UserPrincipalName; string displayName = user.DisplayName; Console.WriteLine("Hello, " + displayName + ". Would you like to send an email to yourself or someone else?"); Console.WriteLine("Enter the address to which you'd like to send a message. If you enter nothing, the message will go to your address."); string userInputAddress = Console.ReadLine(); string messageAddress = String.IsNullOrEmpty(userInputAddress) ? mailAddress : userInputAddress; MailHelper.ComposeAndSendMailAsync("Welcome to Microsoft Graph development with C# and the Microsoft Graph Connect sample", Constants.EmailContent, messageAddress); Console.WriteLine("\nEmail sent! \n Want to send another message? Type 'y' for yes and any other key to exit."); ConsoleKeyInfo userInputSendMail = Console.ReadKey(); sendMail = (userInputSendMail.KeyChar == 'y') ? true : false; Console.WriteLine(); } } else { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("We weren't able to create a GraphServiceClient for you. Please check the output for errors."); Console.ResetColor(); Console.ReadKey(); return; } } else { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("You haven't configured a value for ClientId in Constants.cs. Please follow the Readme instructions for configuring this application."); Console.ResetColor(); Console.ReadKey(); return; } } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Sending an email failed with the following message: {0}", ex.Message); if (ex.InnerException != null) { Console.WriteLine("Error detail: {0}", ex.InnerException.Message); } Console.ResetColor(); Console.ReadKey(); return; } }