This repository has been archived by the owner on Nov 16, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 14
/
UserSnippets.cs
1580 lines (1225 loc) · 57.7 KB
/
UserSnippets.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license.
//See LICENSE in the project root for license information.
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Graph;
using Windows.ApplicationModel.Resources;
using Windows.Storage;
using Windows.Storage.Streams;
using System.Runtime.InteropServices.WindowsRuntime;
namespace Microsoft_Graph_Snippets_SDK
{
public class UserSnippets
{
static string ExcelFileId = null;
public static async Task<string> UploadLargeFile()
{
try
{
var graphClient = AuthenticationHelper.GetAuthenticatedClient();
StorageFile file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync("LargeFileUploadResource.bmp");
using (Stream fileStream = (await file.OpenReadAsync()).AsStreamForRead())
{
// Create the upload session. The access token is no longer required as you have session established for the upload.
// POST /v1.0/drive/root:/UploadLargeFile.bmp:/microsoft.graph.createUploadSession
var uploadSession = await graphClient.Me.Drive.Root.ItemWithPath("LargeFileUploadResource.bmp").CreateUploadSession().Request().PostAsync();
var maxChunkSize = 320 * 1024; // 320 KB - Change this to your chunk size. 5MB is the default.
var provider = new ChunkedUploadProvider(uploadSession, graphClient, fileStream, maxChunkSize);
// Setup the chunk request necessities
var chunkRequests = provider.GetUploadChunkRequests();
var readBuffer = new byte[maxChunkSize];
var trackedExceptions = new List<Exception>();
DriveItem itemResult = null;
//upload the chunks
foreach (var request in chunkRequests)
{
// Do your updates here: update progress bar, etc.
// ...
// Send chunk request
var result = await provider.GetChunkRequestResponseAsync(request, readBuffer, trackedExceptions);
if (result.UploadSucceeded)
{
itemResult = result.ItemResponse;
}
}
// Check that upload succeeded
if (itemResult == null)
{
// Retry the upload
// ...
}
return "Success";
}
}
catch (ServiceException e)
{
Debug.WriteLine("We could not upload the file: " + e.Error.Message);
return null;
}
}
// Returns information about the signed-in user
public static async Task<string> GetMeAsync()
{
string currentUserName = null;
try
{
var graphClient = AuthenticationHelper.GetAuthenticatedClient();
var currentUserObject = await graphClient.Me.Request().GetAsync();
currentUserName = currentUserObject.DisplayName;
if (currentUserName != null)
{
Debug.WriteLine("Got user: " + currentUserName);
}
}
catch (ServiceException e)
{
Debug.WriteLine("We could not get the current user: " + e.Error.Message);
return null;
}
return currentUserName;
}
// Returns all of the users in the directory of the signed-in user's tenant.
public static async Task<IGraphServiceUsersCollectionPage> GetUsersAsync()
{
IGraphServiceUsersCollectionPage users = null;
try
{
var graphClient = AuthenticationHelper.GetAuthenticatedClient();
users = await graphClient.Users.Request().GetAsync();
foreach ( var user in users)
{
Debug.WriteLine("User: " + user.DisplayName);
}
return users;
}
catch (ServiceException e)
{
Debug.WriteLine("We could not get users: " + e.Error.Message);
return null;
}
}
// Creates a new user in the signed-in user's tenant.
// This snippet requires an admin work account.
public static async Task<string> CreateUserAsync(string userName)
{
string createdUserId = null;
try
{
var graphClient = AuthenticationHelper.GetAuthenticatedClient();
//Get tenant domain from the Organization object. We use this domain to create the
//user's email address.
var passwordProfile = new PasswordProfile();
passwordProfile.Password = "pass@word1";
var organization = await graphClient.Organization.Request().GetAsync();
var domain = organization.CurrentPage[0].VerifiedDomains.ElementAt(0).Name;
var user = await graphClient.Users.Request().AddAsync(new User
{
AccountEnabled = true,
DisplayName = "User " + userName,
MailNickname = userName,
PasswordProfile = passwordProfile,
UserPrincipalName = userName + "@" + domain
});
createdUserId = user.Id;
Debug.WriteLine("Created user: " + createdUserId);
}
catch (ServiceException e)
{
Debug.WriteLine("We could not create a user: " + e.Error.Message);
return null;
}
return createdUserId;
}
// Gets the signed-in user's drive.
public static async Task<string> GetCurrentUserDriveAsync()
{
string currentUserDriveId = null;
try
{
var graphClient = AuthenticationHelper.GetAuthenticatedClient();
var currentUserDrive = await graphClient.Me.Drive.Request().GetAsync();
currentUserDriveId = currentUserDrive.Id;
if (currentUserDriveId != null)
{
Debug.WriteLine("Got user drive: " + currentUserDriveId);
}
}
catch (ServiceException e)
{
Debug.WriteLine("We could not get the current user drive: " + e.Error.Message);
return null;
}
return currentUserDriveId;
}
// Gets the signed-in user's calendar events.
public static async Task<IUserEventsCollectionPage> GetEventsAsync()
{
IUserEventsCollectionPage events = null;
try
{
var graphClient = AuthenticationHelper.GetAuthenticatedClient();
events = await graphClient.Me.Events.Request().GetAsync();
foreach (var myEvent in events)
{
Debug.WriteLine("Got event: " + myEvent.Id);
}
}
catch (ServiceException e)
{
Debug.WriteLine("We could not get the current user's events: " + e.Error.Message);
return null;
}
return events;
}
// Creates a new event in the signed-in user's tenant.
// Important note: This will create a user with a weak password. Consider deleting this user after you run the sample.
public static async Task<string> CreateEventAsync()
{
string createdEventId = null;
//List of attendees
List<Attendee> attendees = new List<Attendee>();
var attendee = new Attendee();
var emailAddress = new EmailAddress();
emailAddress.Address = "mara@fabrikam.com";
attendee.EmailAddress = emailAddress;
attendee.Type = AttendeeType.Required;
attendees.Add(attendee);
//Event body
var eventBody = new ItemBody();
eventBody.Content = "Status updates, blocking issues, and next steps";
eventBody.ContentType = BodyType.Text;
//Event start and end time
var eventStartTime = new DateTimeTimeZone();
eventStartTime.DateTime = new DateTime(2014, 12, 1, 9, 30, 0).ToString("o");
eventStartTime.TimeZone = "UTC";
var eventEndTime = new DateTimeTimeZone();
eventEndTime.TimeZone = "UTC";
eventEndTime.DateTime = new DateTime(2014, 12, 1, 10, 0, 0).ToString("o");
//Create an event to add to the events collection
var location = new Location();
location.DisplayName = "Water cooler";
var newEvent = new Event();
newEvent.Subject = "weekly sync";
newEvent.Location = location;
newEvent.Attendees = attendees;
newEvent.Body = eventBody;
newEvent.Start = eventStartTime;
newEvent.End = eventEndTime;
try
{
var graphClient = AuthenticationHelper.GetAuthenticatedClient();
var createdEvent = await graphClient.Me.Events.Request().AddAsync(newEvent);
createdEventId = createdEvent.Id;
if (createdEventId != null)
{
Debug.WriteLine("Created event: " + createdEventId);
}
}
catch (ServiceException e)
{
Debug.WriteLine("We could not create an event: " + e.Error.Message);
return null;
}
return createdEventId;
}
// Updates the subject of an existing event in the signed-in user's tenant.
public static async Task<bool> UpdateEventAsync(string eventId)
{
bool eventUpdated = false;
try
{
var graphClient = AuthenticationHelper.GetAuthenticatedClient();
var eventToUpdate = new Event();
eventToUpdate.Subject = "Sync of the week";
//eventToUpdate.IsAllDay = true;
var updatedEvent = await graphClient.Me.Events[eventId].Request().UpdateAsync(eventToUpdate);
if (updatedEvent != null)
{
Debug.WriteLine("Updated event: " + eventToUpdate.Id);
eventUpdated = true;
}
}
catch (ServiceException e)
{
Debug.WriteLine("We could not update the event: " + e.Error.Message);
eventUpdated = false;
}
return eventUpdated;
}
// Deletes an existing event in the signed-in user's tenant.
public static async Task<bool> DeleteEventAsync(string eventId)
{
bool eventDeleted = false;
try
{
var graphClient = AuthenticationHelper.GetAuthenticatedClient();
var eventToDelete = await graphClient.Me.Events[eventId].Request().GetAsync();
await graphClient.Me.Events[eventId].Request().DeleteAsync();
Debug.WriteLine("Deleted event: " + eventToDelete.Id);
eventDeleted = true;
}
catch (ServiceException e)
{
Debug.WriteLine("We could not delete the event: " + e.Error.Message);
eventDeleted = false;
}
return eventDeleted;
}
// Gets user's calendar view.
public static async Task<ICalendarCalendarViewCollectionPage> GetMyCalendarViewAsync()
{
ICalendarCalendarViewCollectionPage calendar = null;
try
{
var graphClient = AuthenticationHelper.GetAuthenticatedClient();
List<QueryOption> options = new List<QueryOption>();
options.Add(new QueryOption("startDateTime", DateTime.Now.ToString("o")));
options.Add(new QueryOption("endDateTime", DateTime.Now.AddDays(7).ToString("o")));
calendar = await graphClient.Me.Calendar.CalendarView.Request(options).GetAsync();
if (calendar?.Count > 0)
{
foreach (Event current in calendar)
{
Debug.WriteLine(current.Subject);
}
}
}
catch (ServiceException e)
{
Debug.WriteLine("We could not get the calendar view: " + e.Error.Message);
return null;
}
return calendar;
}
// Accept a meeting request.
public static async Task<bool> AcceptMeetingRequestAsync(string id)
{
bool meetingAccepted = false;
try
{
var graphClient = AuthenticationHelper.GetAuthenticatedClient();
var responseText = ResourceLoader.GetForCurrentView().GetString("GenericText");
await graphClient.Me.Events[id].Accept(responseText).Request().PostAsync();
Debug.WriteLine("Accepted meeting: " + id);
meetingAccepted = true;
}
catch (ServiceException e)
{
Debug.WriteLine("We could not get accept the meeting: " + e.Error.Message);
}
return meetingAccepted;
}
// Returns the first page of the signed-in user's messages.
public static async Task<IUserMessagesCollectionPage> GetMessagesAsync()
{
IUserMessagesCollectionPage messages = null;
try
{
var graphClient = AuthenticationHelper.GetAuthenticatedClient();
messages = await graphClient.Me.Messages.Request().GetAsync();
foreach ( var message in messages)
{
Debug.WriteLine("Got message: " + message.Subject);
}
return messages;
}
catch (ServiceException e)
{
Debug.WriteLine("We could not get messages: " + e.Error.Message);
return null;
}
}
public static async Task<IMailFolderMessagesCollectionPage> GetMessagesThatHaveAttachmentsAsync()
{
IMailFolderMessagesCollectionPage messages = null;
try
{
var graphClient = AuthenticationHelper.GetAuthenticatedClient();
messages = await graphClient.Me.MailFolders.Inbox.Messages.Request().Filter("hasAttachments eq true").Expand("attachments").GetAsync();
foreach ( var message in messages)
{
// This snippet displays information about the first attachment in each message
Attachment firstAttachment = message.Attachments[0];
Debug.WriteLine("Got message with attachment: " + message.Subject);
Debug.WriteLine("Attachment name: " + firstAttachment.Name);
Debug.WriteLine("Attachment content type: " + firstAttachment.ContentType);
}
}
catch (ServiceException e)
{
Debug.WriteLine("We could not get messages that have attachments: " + e.Error.Message);
return null;
}
return messages;
}
// Sends message to a specified address.
public static async Task<bool> SendMessageAsync(
string Subject,
string Body,
string RecipientAddress
)
{
bool emailSent = false;
//Create recipient list
List<Recipient> recipientList = new List<Recipient>();
recipientList.Add(new Recipient { EmailAddress = new EmailAddress { Address = RecipientAddress.Trim() } });
//Create message
var email = new Message
{
Body = new ItemBody
{
Content = Body,
ContentType = BodyType.Html,
},
Subject = Subject,
ToRecipients = recipientList,
};
try
{
var graphClient = AuthenticationHelper.GetAuthenticatedClient();
await graphClient.Me.SendMail(email, true).Request().PostAsync();
Debug.WriteLine("Message sent");
emailSent = true;
}
catch (ServiceException e)
{
Debug.WriteLine("We could not send the message. The request returned this status code: " + e.Error.Message);
emailSent = false;
}
return emailSent;
}
// Sends message with an attachment to a specified address.
public static async Task<bool> SendMessageWithAttachmentAsync(
string Subject,
string Body,
string RecipientAddress
)
{
bool emailSent = false;
//Create recipient list
List<Recipient> recipientList = new List<Recipient>();
recipientList.Add(new Recipient { EmailAddress = new EmailAddress { Address = RecipientAddress.Trim() } });
// Create an attachment and add it to the attachments collection.
StorageFile file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync("excelTestResource.xlsx");
Stream fileStream = (await file.OpenReadAsync()).AsStreamForRead();
MemoryStream fileStreamMS = new MemoryStream();
// Copy stream to MemoryStream object so that it can be converted to byte array.
fileStream.CopyTo(fileStreamMS);
MessageAttachmentsCollectionPage attachments = new MessageAttachmentsCollectionPage();
attachments.Add(new FileAttachment
{
ODataType = "#microsoft.graph.fileAttachment",
ContentBytes = fileStreamMS.ToArray(),
ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
Name = "excelTestResource.xlsx"
});
//Create message
var email = new Message
{
Body = new ItemBody
{
Content = Body,
ContentType = BodyType.Html,
},
Subject = Subject,
ToRecipients = recipientList,
Attachments = attachments
};
try
{
var graphClient = AuthenticationHelper.GetAuthenticatedClient();
await graphClient.Me.SendMail(email, true).Request().PostAsync();
Debug.WriteLine("Message sent");
emailSent = true;
}
catch (ServiceException e)
{
Debug.WriteLine("We could not send the message with an attachment. The request returned this status code: " + e.Error.Message);
emailSent = false;
}
return emailSent;
}
// Reply to a specified message
public static async Task<bool> ReplyToMessageAsync(string Id)
{
bool replySent = false;
string responseText = ResourceLoader.GetForCurrentView().GetString("GenericText");
try
{
var graphClient = AuthenticationHelper.GetAuthenticatedClient();
await graphClient.Me.Messages[Id].Reply(responseText).Request().PostAsync();
Debug.WriteLine("Reply sent");
replySent = true;
}
catch (ServiceException e)
{
Debug.WriteLine("We could not reply to the message. The request returned this status code: " + e.Error.Message);
replySent = false;
}
return replySent;
}
// Move a specified message. This creates a new copy of the message to the specified folder.
public static async Task<Message> MoveMessageAsync(string Id, string folderName)
{
Message message = null;
try
{
var graphClient = AuthenticationHelper.GetAuthenticatedClient();
message = await graphClient.Me.Messages[Id].Move(folderName).Request().PostAsync();
Debug.WriteLine("Message " + Id + " moved to " + folderName );
}
catch (ServiceException e)
{
Debug.WriteLine("We could not move the message. The request returned this status code: " + e.Error.Message);
}
return message;
}
// Gets the signed-in user's manager.
// This snippet doesn't work with personal accounts.
public static async Task<string> GetCurrentUserManagerAsync()
{
string currentUserManagerId = null;
try
{
var graphClient = AuthenticationHelper.GetAuthenticatedClient();
var currentUserManager = await graphClient.Me.Manager.Request().GetAsync();
currentUserManagerId = currentUserManager.Id;
Debug.WriteLine("Got manager: " + currentUserManagerId);
}
catch (ServiceException e)
{
Debug.WriteLine("We could not get the current user's manager: " + e.Error.Message);
return null;
}
return currentUserManagerId;
}
// Gets the signed-in user's direct reports.
// This snippet doesn't work with consumer accounts.
public static async Task<IUserDirectReportsCollectionWithReferencesPage> GetDirectReportsAsync()
{
IUserDirectReportsCollectionWithReferencesPage directReports = null;
try
{
var graphClient = AuthenticationHelper.GetAuthenticatedClient();
directReports = await graphClient.Me.DirectReports.Request().GetAsync();
foreach (User direct in directReports)
{
Debug.WriteLine("Got direct report: " + direct.DisplayName);
}
return directReports;
}
catch (ServiceException e)
{
Debug.WriteLine("We could not get direct reports: " + e.Error.Message);
return null;
}
}
// Gets the signed-in user's photo.
// This snippet doesn't work with consumer accounts.
public static async Task<string> GetCurrentUserPhotoAsync()
{
string currentUserPhotoId = null;
try
{
var graphClient = AuthenticationHelper.GetAuthenticatedClient();
var userPhoto = await graphClient.Me.Photo.Request().GetAsync();
currentUserPhotoId = userPhoto.Id;
Debug.WriteLine("Got user photo: " + currentUserPhotoId);
}
catch (ServiceException e)
{
Debug.WriteLine("We could not get the current user photo: " + e.Error.Message);
return null;
}
return currentUserPhotoId;
}
// Gets the stream content of the signed-in user's photo.
// This snippet doesn't work with consumer accounts.
public static async Task<Stream> GetCurrentUserPhotoStreamAsync()
{
Stream currentUserPhotoStream = null;
try
{
var graphClient = AuthenticationHelper.GetAuthenticatedClient();
currentUserPhotoStream = await graphClient.Me.Photo.Content.Request().GetAsync();
Debug.WriteLine("Got user photo stream: " + currentUserPhotoStream.ToString());
}
catch (ServiceException e)
{
Debug.WriteLine("We could not get the current user photo: " + e.Error.Message);
return null;
}
return currentUserPhotoStream;
}
// Gets the groups that the signed-in user is a member of.
// This snippet requires an admin work account.
public static async Task<IUserMemberOfCollectionWithReferencesPage> GetCurrentUserGroupsAsync()
{
IUserMemberOfCollectionWithReferencesPage memberOfGroups = null;
try
{
var graphClient = AuthenticationHelper.GetAuthenticatedClient();
memberOfGroups = await graphClient.Me.MemberOf.Request().GetAsync();
foreach (var group in memberOfGroups)
{
Debug.WriteLine("Got group: " + group.Id);
}
return memberOfGroups;
}
catch (ServiceException e)
{
Debug.WriteLine("We could not get user groups: " + e.Error.Message);
return null;
}
}
public static async Task<IDriveItemChildrenCollectionPage> GetCurrentUserFilesAsync()
{
IDriveItemChildrenCollectionPage files = null;
try
{
var graphClient = AuthenticationHelper.GetAuthenticatedClient();
files = await graphClient.Me.Drive.Root.Children.Request().GetAsync();
foreach (DriveItem item in files)
{
Debug.WriteLine("Got file: " + item.Name);
}
return files;
}
catch (ServiceException e)
{
Debug.WriteLine("We could not get user files: " + e.Error.Message);
return null;
}
}
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();
Debug.WriteLine("Got sharing link for file: " + permission.Link.WebUrl);
}
catch (ServiceException e)
{
Debug.WriteLine("We could not get the sharing link: " + e.Error.Message);
return null;
}
return permission;
}
// Creates a text file in the user's root directory.
public static async Task<string> CreateFileAsync(string fileName, string fileContent)
{
string createdFileId = null;
DriveItem fileToCreate = new DriveItem();
//Read fileContent string into a stream that gets passed as the file content
byte[] byteArray = Encoding.ASCII.GetBytes(fileContent);
MemoryStream fileContentStream = new MemoryStream(byteArray);
fileToCreate.Content = fileContentStream;
try
{
var graphClient = AuthenticationHelper.GetAuthenticatedClient();
var createdFile = await graphClient.Me.Drive.Root.ItemWithPath(fileName).Content.Request().PutAsync<DriveItem>(fileContentStream);
createdFileId = createdFile.Id;
Debug.WriteLine("Created file Id: " + createdFileId);
}
//Known bug -- file created but ServiceException "Value cannot be null" thrown
//Workaround: catch the exception, make sure that it is the one that is expected, get the item and itemID
catch (ServiceException se)
{
if (se.InnerException.Message.Contains("Value cannot be null"))
{
var graphClient = AuthenticationHelper.GetAuthenticatedClient();
var createdFile = await graphClient.Me.Drive.Root.ItemWithPath(fileName).Request().GetAsync();
createdFileId = createdFile.Id;
return createdFileId;
}
else
{
Debug.WriteLine("We could not create the file. The request returned this status code: " + se.Error.Message);
return null;
}
}
return createdFileId;
}
// Downloads the content of an existing file.
public static async Task<Stream> DownloadFileAsync(string fileId)
{
Stream fileContent = null;
try
{
var graphClient = AuthenticationHelper.GetAuthenticatedClient();
var downloadedFile = await graphClient.Me.Drive.Items[fileId].Content.Request().GetAsync();
fileContent = downloadedFile;
Debug.WriteLine("Downloaded file content for file: " + fileId);
}
catch (ServiceException e)
{
Debug.WriteLine("We could not download the file. The request returned this status code: " + e.Error.Message);
return null;
}
return fileContent;
}
// Adds content to a file in the user's root directory.
public static async Task<bool> UpdateFileAsync(string fileId, string fileContent)
{
bool fileUpdated = false;
try
{
var graphClient = AuthenticationHelper.GetAuthenticatedClient();
//Read fileContent string into a stream that gets passed as the file content
byte[] byteArray = Encoding.ASCII.GetBytes(fileContent);
MemoryStream fileContentStream = new MemoryStream(byteArray);
var updatedFile = await graphClient.Me.Drive.Items[fileId].Content.Request().PutAsync<DriveItem>(fileContentStream); ;
if (updatedFile != null)
{
Debug.WriteLine("Updated file Id: " + updatedFile.Id);
fileUpdated = true;
}
}
//Known bug -- file created but ServiceException "Value cannot be null" thrown
//Workaround: catch the exception, make sure that it is the one that is expected, return true
catch (ServiceException se)
{
if (se.InnerException.Message.Contains("Value cannot be null"))
{
return true;
}
else
{
Debug.WriteLine("We could not create the file. The request returned this status code: " + se.Message);
return false;
}
}
return fileUpdated;
}
// Deletes a file in the user's root directory.
public static async Task<bool> DeleteFileAsync(string fileId)
{
bool fileDeleted = false;
try
{
var graphClient = AuthenticationHelper.GetAuthenticatedClient();
var fileToDelete = graphClient.Me.Drive.Items[fileId].Request().GetAsync();
await graphClient.Me.Drive.Items[fileId].Request().DeleteAsync();
Debug.WriteLine("Deleted file Id: " + fileToDelete.Id);
fileDeleted = true;
}
catch (ServiceException e)
{
Debug.WriteLine("We could not delete the file. The request returned this status code: " + e.Error.Message);
fileDeleted = false;
}
return fileDeleted;
}
// Renames a file in the user's root directory.
public static async Task<bool> RenameFileAsync(string fileId, string newFileName)
{
bool fileRenamed = false;
try
{
var graphClient = AuthenticationHelper.GetAuthenticatedClient();
var fileToRename = new DriveItem();
fileToRename.Name = newFileName;
var renamedFile = await graphClient.Me.Drive.Items[fileId].Request().UpdateAsync(fileToRename);
if (renamedFile != null)
{
Debug.WriteLine("Renamed file Id: " + renamedFile.Id);
fileRenamed = true;
}
}
catch (ServiceException e)
{
Debug.WriteLine("We could not rename the file. The request returned this status code: " + e.Error.Message);
fileRenamed = false;
}
return fileRenamed;
}
// Creates a folder in the user's root directory.
// This does not work with consumer accounts.
public static async Task<string> CreateFolderAsync(string folderName)
{
string createFolderId = null;
DriveItem folderToCreate = new DriveItem();
folderToCreate.Name = folderName;
var folder = new Folder();
folderToCreate.Folder = folder;
try
{
var graphClient = AuthenticationHelper.GetAuthenticatedClient();
var createdFolder = await graphClient.Me.Drive.Root.Children.Request().AddAsync(folderToCreate);
if (createdFolder != null)
{
createFolderId = createdFolder.Id;
Debug.WriteLine("Created folder Id: " + createFolderId);