Example #1
1
        public async Task<ActionResult> About()
        {
            var graphClient = new GraphServiceClient(
                new DelegateAuthenticationProvider(
                    (requestMessage) =>
                    {
                        // Get back the access token.
                        var accessToken = ADALHelper.GetAccessTokenForCurrentUser();

                        if (!String.IsNullOrEmpty(accessToken))
                        {
                            // Configure the HTTP bearer Authorization Header
                            requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
                        }
                        else
                        {
                            throw new Exception("Invalid authorization context");
                        }

                        return (Task.FromResult(0));
                    }
                    ));

            try
            {
                var me = await graphClient.Me.Request().Select("DisplayName").GetAsync();
                ViewBag.Message = me.DisplayName;
            }
            catch (Exception)
            {
                // Skip any exception, so far
            }

            return View();
        }
Example #2
1
        public CalendarAPI(ref GraphServiceClient client, ref ClassLogger appLogger, ref ClassLogger sdkLogger)
        {
            InitializeComponent();
            graphClient = client;
            applogger = appLogger;
            sdklogger = sdkLogger;

            dItemBody = new Dictionary<string, List<ItemBody>>();
            dAttendees = new Dictionary<string, List<Attendee>>();
            dCategories = new Dictionary<string, List<string>>();
            dRecurrencePattern = new Dictionary<string, RecurrencePattern>();
            dRecurrenceRange = new Dictionary<string, RecurrenceRange>();
            dFileAttachments = new Dictionary<string, List<FileAttachment>>();
            dItemAttachments = new Dictionary<string, List<ItemAttachment>>();
            dReferenceAttachments = new Dictionary<string, List<ReferenceAttachment>>();
            dCalendarIds = new Dictionary<string, string>();

            #pragma warning disable 4014
            GetFoldersAsync();
            #pragma warning restore 4014
        }
Example #3
1
        public MainWindow()
        {
            InitializeComponent();

            // create the object to call the service
            GraphServiceClient client = new GraphServiceClient();

            //update the db with the latest info
             client.UpdateDB();

            //populate the comboboxes
            cbFromNode.ItemsSource = nodeList;
            cbFromNode.SelectedValuePath = "Key";
            cbFromNode.DisplayMemberPath  = "Value";
            cbFromNode.SelectedValue = 1;
            cbToNode.ItemsSource = nodeList;
            cbToNode.SelectedValuePath = "Key";
            cbToNode.DisplayMemberPath = "Value";
            cbToNode.SelectedValue = 2;

            //generate the graph
            GraphGenerate();
        }
Example #4
1
        public MailAPI(ref GraphServiceClient olClient, ref ClassLogger appLogger, ref ClassLogger sdkLogger)
        {
            InitializeComponent();
            graphClient = olClient;
            applogger = appLogger;
            sdklogger = sdkLogger;

            // init the dictionaries
            dRecips = new Dictionary<string, List<Recipient>>();
            dItemBody = new Dictionary<string, List<ItemBody>>();
            dBcc = new Dictionary<string, List<Recipient>>();
            dCc = new Dictionary<string, List<Recipient>>();
            dReplyTo = new Dictionary<string, List<Recipient>>();
            dCategories = new Dictionary<string, List<string>>();
            dFileAttachments = new Dictionary<string, List<FileAttachment>>();
            dItemAttachments = new Dictionary<string, List<ItemAttachment>>();
            dReferenceAttachments = new Dictionary<string, List<ReferenceAttachment>>();
            dFolderIds = new Dictionary<string, string>();

            #pragma warning disable 4014 
            GetFoldersAsync();
            #pragma warning restore 4014
        }
Example #5
1
        private static async Task UpdateUnifiedGroup(GraphServiceClient graphClient, String groupId)
        {
            var groupToUpdate = await graphClient.Groups[groupId]
                .Request()
                .GetAsync();

            groupToUpdate.DisplayName = "SDK Group - Updated!";
            groupToUpdate.Description += " - Updated!";

            try
            {
                var updatedGroup = await graphClient.Groups[groupId]
                    .Request()
                    .UpdateAsync(groupToUpdate);
            }
            catch (ServiceException ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Example #6
1
 private static async Task DeleteUnifiedGroup(GraphServiceClient graphClient, String groupId)
 {
     try
     {
         await graphClient.Groups[groupId]
             .Request()
             .DeleteAsync();
     }
     catch (ServiceException ex)
     {
         Console.WriteLine(ex.Message);
     }
 }
Example #7
1
        private static async Task RetrieveCurrentUserManagerAndReports(GraphServiceClient graphClient)
        {
            var managerPointer = await graphClient.Me.Manager.Request().GetAsync();
            var manager = await graphClient.Users[managerPointer.Id].Request().Select("DisplayName").GetAsync();
            if (manager != null)
            {
                Console.WriteLine("Your manager is: {0}", manager.DisplayName);
            }

            var reports = await graphClient.Me.DirectReports.Request().GetAsync();

            if (reports.Count > 0)
            {
                Console.WriteLine("Here are your direct reports:");
                foreach (var r in reports)
                {
                    var report = await graphClient.Users[r.Id].Request().Select("DisplayName").GetAsync();
                    Console.WriteLine(report.DisplayName);
                }
            }
            else
            {
                Console.WriteLine("You don't have direct reports!");
            }
        }
 public async Task<System.Collections.Generic.List<Microsoft.Graph.Group>> GetO365DemoGroups(GraphServiceClient graphService)
 {
     return (await graphService.Groups.Request().GetAllAsnyc()).Where(x => x.Description == "Property Group").ToList();
 }
 // GET: UserProfile
 public async Task<ActionResult> Index()
 {
     string tenantID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
     string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
     try
     {
         var graphToken = await AuthenticationHelper.GetGraphAccessToken();
         var authenticationProvider = new DelegateAuthenticationProvider(
         (requestMessage) =>
         {
             requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", graphToken);
             return Task.FromResult(0);
         });
         var graphClient = new GraphServiceClient(authenticationProvider);
         var user = await graphClient.Me.Request().GetAsync();
         return View(user);
     }
     catch (AdalException)
     {
         // Return to error page.
         return View("Error");
     }
     // if the above failed, the user needs to explicitly re-authenticate for the app to obtain the required token
     catch (Exception)
     {
         return View("Relogin");
     }
 }
Example #10
0
        public NewEventForm(ref GraphServiceClient olClient, ref ClassLogger appLogger, ref ClassLogger sdkLogger)
        {
            InitializeComponent();
            graphClient = olClient;
            applogger = appLogger;
            sdklogger = sdkLogger;

            // add 1/2 hour to the dtpend time
            dtpEndTime.Value = dtpEndTime.Value.AddMinutes(30);
        }
 public NewContactForm(ref GraphServiceClient olClient, ref ClassLogger appLogger, ref ClassLogger sdkLogger)
 {
     InitializeComponent();
     graphClient = olClient;
     applogger = appLogger;
     sdklogger = sdkLogger;
     emailAddresses = new List<EmailAddress>();
     businessPhones = new List<string>();
     homePhones = new List<string>();
 }
 public NewMessageForm(ref GraphServiceClient olClient, ref ClassLogger appLogger, ref ClassLogger sdkLogger)
 {
     InitializeComponent();
     graphClient = olClient;
     applogger = appLogger;
     sdklogger = sdkLogger;
     toRecipients = new List<Recipient>();
     ccRecipients = new List<Recipient>();
     bccRecipients = new List<Recipient>();
 }
 private async Task<GraphServiceClient> GetGraphServiceAsync()
 {
     var accessToken = await GetGraphAccessTokenAsync();
     var graphserviceClient = new GraphServiceClient(SettingsHelper.GraphResourceUrl,
                                 new DelegateAuthenticationProvider(
                                     (requestMessage) =>
                                     {
                                         requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
                                         return Task.FromResult(0);
                                     }));
     return graphserviceClient;
 }
Example #14
0
        private void button_Click(object sender, RoutedEventArgs e)
        {
            //call the service and calculate the shortest path and display it
            GraphServiceClient client = new GraphServiceClient();
            var start = Convert.ToInt32(cbFromNode.SelectedValue);
            var finish = Convert.ToInt32(cbToNode.SelectedValue);
            List<int> list =  client.ShortestPath(start, finish , vertices);

            List<string> path =  new List<string>();

            foreach (var i in list)
            {
                path.Add(nodeList[i]);
            }

            txtPath.Text = string.Join(" -> ", path);
        }
        private static GraphServiceClient CreateGraphClient(String accessToken, int retryCount = defaultRetryCount, int delay = defaultDelay)
        {
            // Creates a new GraphServiceClient instance using a custom PnPHttpProvider
            // which natively supports retry logic for throttled requests
            // Default are 10 retries with a base delay of 500ms
            var result = new GraphServiceClient(new DelegateAuthenticationProvider(
                        async (requestMessage) =>
                        {
                            if (!String.IsNullOrEmpty(accessToken))
                            {
                                // Configure the HTTP bearer Authorization Header
                                requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
                            }
                        }), new PnPHttpProvider(retryCount, delay));

            return (result);
        }
        public static async Task<GraphServiceClient> GetGraphServiceAsync(string url)
        {
            //var serviceRoot = new Uri(AADAppSettings.GraphResourceUrl);

            var accessToken = await GetAccessTokenAsync(AADAppSettings.GraphResourceId);
            //// AdalException thrown by GetAccessTokenAsync is swallowed 
            //// by GraphService so we need to wait here.
            //await accessToken;

            var graphserviceClient = new GraphServiceClient(url,
                                          new DelegateAuthenticationProvider(
                                                        (requestMessage) =>
                                                        {
                                                            requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken);

                                                            return Task.FromResult(0);
                                                        }));

            return graphserviceClient;
        }
Example #17
0
        public ContactsAPI(ref GraphServiceClient client, ref ClassLogger appLogger, ref ClassLogger sdkLogger)
        {
            InitializeComponent();
            graphClient = client;
            applogger = appLogger;
            sdklogger = sdkLogger;

            dBusinessPhones = new Dictionary<string, List<string>>();
            dHomePhones = new Dictionary<string, List<string>>();
            dCategories = new Dictionary<string, List<string>>();
            dChildren = new Dictionary<string, List<string>>();
            dImAddresses = new Dictionary<string, List<string>>();
            dEmailAddresses = new Dictionary<string, List<string>>();
            dHomeAddress = new Dictionary<string, PhysicalAddress>();
            dOtherAddress = new Dictionary<string, PhysicalAddress>();
            dBusinessAddress = new Dictionary<string, PhysicalAddress>();

            #pragma warning disable 4014
            GetFoldersAsync();
            #pragma warning restore 4014
        }
Example #18
0
        private static async Task SearchForFilesInOneDriveForBusiness(GraphServiceClient graphClient, String queryText)
        {
            var searchResults = await graphClient.Me.Drive.Root.Search(queryText).Request().GetAsync();
            Int32 pageCount = 0;

            while (true)
            {
                pageCount++;
                Console.WriteLine("Page: {0}", pageCount);
                foreach (var result in searchResults)
                {
                    Console.WriteLine("{0} - {1}\n{2}\n", result.Id, result.Name, result.WebUrl);
                    await DownloadFileFromOneDriveForBusiness(graphClient, result.Id);
                }

                if (searchResults.NextPageRequest != null)
                {
                    searchResults = await searchResults.NextPageRequest.GetAsync();
                }
                else
                {
                    break;
                }
            }
        }
Example #19
0
 private static async Task ShowMyDisplayName(GraphServiceClient graphClient)
 {
     var me = await graphClient.Me.Request().Select("DisplayName").GetAsync();
     Console.WriteLine("Your ID is: {0}", me.DisplayName);
 }
Example #20
0
        private static async Task AddGroupEvent(GraphServiceClient graphClient)
        {
            var unifiedGroups = await graphClient.Groups
                .Request()
                .Filter("groupTypes/any(grp: grp eq 'Unified')")
                .GetAsync();

            Event evt = new Event
            {
                Subject = "Created with Graph SDK",
                Body = new ItemBody
                {
                    Content = "<h1>Office 365 Party!</h1>",
                    ContentType = BodyType.Html,
                },
                Start = new DateTimeTimeZone
                {
                    DateTime = DateTime.Now.AddDays(1).ToUniversalTime().ToString("yyyy-MM-ddThh:mm:ss"),
                    TimeZone = "UTC",
                },
                End = new DateTimeTimeZone
                {
                    DateTime = DateTime.Now.AddDays(2).ToUniversalTime().ToString("yyyy-MM-ddThh:mm:ss"),
                    TimeZone = "UTC",
                },
                Location = new Location
                {
                    Address = new PhysicalAddress
                    {
                        City = "Redmond",
                        CountryOrRegion = "USA",
                        State = "WA",
                        Street = "Microsft Way",
                        PostalCode = "98052",
                    },
                    DisplayName = "Microsoft Corp. HQ",
                },
                Type = EventType.SingleInstance,
                ShowAs = FreeBusyStatus.Busy,
            };

            var groupEvents = await graphClient
                .Groups[unifiedGroups.FirstOrDefault().Id].Events
                .Request()
                .AddAsync(evt);
        }
Example #21
0
 private AzureDirectoryService()
 {
     _graphClient = new GraphServiceClient(new AzureAuthenticationProvider());
 }
        private static async Task UpdateOwners(string[] owners, GraphServiceClient graphClient, Group targetGroup)
        {
            foreach (var o in owners)
            {
                // Search for the user object
                var ownerQuery = await graphClient.Users
                                 .Request()
                                 .Filter($"userPrincipalName eq '{o}'")
                                 .GetAsync();

                var owner = ownerQuery.FirstOrDefault();

                if (owner != null)
                {
                    try
                    {
                        // And if any, add it to the collection of group's owners
                        await graphClient.Groups[targetGroup.Id].Owners.References.Request().AddAsync(owner);
                    }
                    catch (ServiceException ex)
                    {
                        if (ex.Error.Code == "Request_BadRequest" &&
                            ex.Error.Message.Contains("added object references already exist"))
                        {
                            // Skip any already existing owner
                        }
                        else
                        {
                            throw ex;
                        }
                    }
                }
            }

            // Remove any leftover owner
            var fullListOfOwners = await graphClient.Groups[targetGroup.Id].Owners.Request().Select("userPrincipalName, Id").GetAsync();
            var pageExists       = true;

            while (pageExists)
            {
                foreach (var owner in fullListOfOwners)
                {
                    var currentOwnerPrincipalName = (owner as Microsoft.Graph.User)?.UserPrincipalName;
                    if (!String.IsNullOrEmpty(currentOwnerPrincipalName) &&
                        !owners.Contains(currentOwnerPrincipalName, StringComparer.InvariantCultureIgnoreCase))
                    {
                        try
                        {
                            // If it is not in the list of current owners, just remove it
                            await graphClient.Groups[targetGroup.Id].Owners[owner.Id].Reference.Request().DeleteAsync();
                        }
                        catch (ServiceException ex)
                        {
                            if (ex.Error.Code == "Request_BadRequest")
                            {
                                // Skip any failing removal
                            }
                            else
                            {
                                throw ex;
                            }
                        }
                    }
                }

                if (fullListOfOwners.NextPageRequest != null)
                {
                    fullListOfOwners = await fullListOfOwners.NextPageRequest.GetAsync();
                }
                else
                {
                    pageExists = false;
                }
            }
        }
Example #23
0
 public static async Task DeleteEvent(string EventID, GraphServiceClient x)
 {
     await x.Me.Calendar.Events[EventID].Request().DeleteAsync();
 }
        private async void TaskViewModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            PlannerTaskViewModel plannerTaskViewModel = sender as PlannerTaskViewModel;

            if (Tasks.Contains(plannerTaskViewModel))
            {
                Dictionary <string, object> task = new Dictionary <string, object>();
                bool skipUpdate = false;
                switch (e.PropertyName)
                {
                case nameof(plannerTaskViewModel.AssignmentIds):
                    await GetAssignmentsAsync(plannerTaskViewModel);

                    PlannerAssignments assignments = new PlannerAssignments();

                    foreach (string assignee in plannerTaskViewModel.AssignmentIds)
                    {
                        assignments.AddAssignee(assignee);
                    }

                    task.Add(TaskAssignmentsJsonName, assignments);
                    break;

                case nameof(plannerTaskViewModel.Title):
                    task.Add(TaskTitleJsonName, plannerTaskViewModel.Title);
                    break;

                case nameof(plannerTaskViewModel.BucketId):
                    string bucketName = string.Empty;
                    foreach (PlannerBucket bucket in Buckets)
                    {
                        if (bucket.Id == plannerTaskViewModel.BucketId)
                        {
                            bucketName = bucket.Name;
                            break;
                        }
                    }

                    plannerTaskViewModel.BucketName = bucketName;
                    task.Add(TaskBucketIdJsonName, plannerTaskViewModel.BucketId);
                    if (string.IsNullOrEmpty(plannerTaskViewModel.BucketId))
                    {
                        skipUpdate = true;
                    }

                    break;

                case nameof(plannerTaskViewModel.DueDateTime):
                    task.Add(TaskDueDateTimeJsonName, plannerTaskViewModel.DueDateTime);
                    if (_list.ContainerFromItem(plannerTaskViewModel) is ListViewItem taskContainer)
                    {
                        var flyout = taskContainer.ContentTemplateRoot.FindDescendants <Button>().FirstOrDefault(s => s.Flyout != null)?.Flyout;
                        if (flyout != null)
                        {
                            flyout.Hide();
                        }
                    }

                    break;

                default:
                    skipUpdate = true;
                    break;
                }

                if (!skipUpdate)
                {
                    plannerTaskViewModel.IsUpdating = true;
                    try
                    {
                        GraphServiceClient graphClient = await GraphServiceHelper.GetGraphServiceClientAsync();

                        if (graphClient != null)
                        {
                            PlannerTask taskToUpdate = await graphClient.Planner.Tasks[plannerTaskViewModel.Id].Request().GetAsync();
                            if (task.ContainsKey(TaskAssignmentsJsonName))
                            {
                                PlannerAssignments assignments  = task[TaskAssignmentsJsonName] as PlannerAssignments;
                                string[]           oldAssignees = taskToUpdate.Assignments.Assignees.ToArray();
                                string[]           newAssignees = assignments.Assignees.ToArray();
                                foreach (string userId in oldAssignees)
                                {
                                    if (!newAssignees.Contains(userId))
                                    {
                                        assignments.AddAssignee(userId);
                                        assignments[userId] = null;
                                    }
                                }
                            }

                            plannerTaskViewModel.ETag = taskToUpdate.GetEtag();
                            using (HttpRequestMessage request = graphClient.Planner.Tasks[plannerTaskViewModel.Id].Request().GetHttpRequestMessage())
                            {
                                request.Method = new HttpMethod(HttpMethodPatch);
                                string json = JsonConvert.SerializeObject(task);
                                request.Content = new StringContent(json, System.Text.Encoding.UTF8, MediaTypeJson);
                                request.Headers.Add(HttpHeaderIfMatch, plannerTaskViewModel.ETag);
                                await graphClient.AuthenticationProvider.AuthenticateRequestAsync(request);

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

                                response.Dispose();
                            }
                        }
                    }
                    catch (Exception exception)
                    {
                        MessageDialog messageDialog = new MessageDialog(exception.Message);
                        await messageDialog.ShowAsync();
                    }

                    plannerTaskViewModel.IsUpdating = false;
                }
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="graphClient"></param>
        /// <param name="emailID"></param>
        /// <param name="groupName"></param>
        /// <returns>Return value represents returnStatus, message, userObjectID, groupID respectively</returns>
        public async Task <Tuple <bool, string, string, string> > AssociateUserWithAGroup(GraphServiceClient graphClient, string emailID, string groupName)
        {
            bool   ActionStatus = false;
            string message      = string.Empty;

            string groupid = "", userObjectID = "";

            if (graphClient == null || string.IsNullOrEmpty(emailID) || string.IsNullOrEmpty(groupName))
            {
                return(new Tuple <bool, string, string, string>(ActionStatus, "Invalid input", null, null));
            }

            try
            {
                IGraphServiceUsersCollectionPage _usersFilteredId = await graphClient.Users.Request().Filter($"Mail eq '" + emailID + "' or UserPrincipalName eq '" + emailID + "'").GetAsync();

                userObjectID = _usersFilteredId.Select(a => a.Id).SingleOrDefault().ToString();

                if (!string.IsNullOrEmpty(userObjectID))
                {
                    //find group Id by groupname
                    IGraphServiceGroupsCollectionPage groupsCollectionPage = graphClient.Groups.Request().Filter($"DisplayName eq '" + groupName + "'").GetAsync().Result;

                    if (groupsCollectionPage != null)
                    {
                        groupid = groupsCollectionPage.Select(a => a.Id).SingleOrDefault().ToString();

                        if (groupid != null)
                        {
                            //check if the user is already associated
                            var associatedmember = await graphClient.Groups[groupid].Members.Request().GetAsync();
                            if (associatedmember.Where(a => a.Id == userObjectID).FirstOrDefault() == null)
                            {
                                Microsoft.Graph.User userToAdd = await graphClient.Users[userObjectID].Request().GetAsync();
                                await graphClient.Groups[groupid].Members.References.Request().AddAsync(userToAdd);

                                ActionStatus = true;
                                message      = "User association with group was successful";
                            }
                            else
                            {
                                message = "User already associated with the group";
                            }
                        }
                        else
                        {
                            message = "Invalid group";
                        }
                    }
                    else
                    {
                        message = "Invalid group";
                    }
                }
                else
                {
                    message = "Invalid user";
                }
            }
            catch (Exception ex)
            {
                message = ex.Message + (ex.InnerException != null ? Environment.NewLine + ex.InnerException.Message : "");
            }

            return(new Tuple <bool, string, string, string>(ActionStatus, message, userObjectID, groupid));
        }
Example #26
0
        public static void CheckForNameChange(List <User> users, GraphServiceClient graphClient)
        {
            Queue <User> work = new Queue <User>();

            foreach (var user in users)
            {
                work.Enqueue(user);
            }

            int wait = 0;

            while (work.Count > 0)
            {
                wait++;
                Thread.Sleep(25);

                var temp = work.Dequeue();

                /*
                 * User teneoUser;
                 * try
                 * {
                 *  teneoUser = graphClient.Users[temp.Id].Request().GetAsync().Result;
                 * }
                 * catch { teneoUser = null; }*/
                if (temp.Mail != null)
                {
                    if (temp.Mail.Contains("teneo.com"))
                    {
                        Console.WriteLine(temp.DisplayName + " has been updated, sending mail.");
                        String html = System.IO.File.ReadAllText("C:/Rebrand/Misc/Notification.html");
                        html = html.Replace("TENEOAZUREFIRSTNAME", temp.GivenName);
                        // Send mail of MySite reflecting UPN change
                        Message notification = MailHelper.ComposeMail("Your Teneo Email Has Been Updated",
                                                                      html,
                                                                      new List <string>()
                        {
                            temp.Mail
                        });
                        graphClient.Me.SendMail(notification, false).Request().PostAsync();

                        // Changing OneDrive Permissions
                        //var result = UpdatePermissions("C:/Rebrand/Teneo_PEM.txt", graphClient, temp.Id);

                        //if (result != null) { OneDrive.Enqueue(result); }

                        // Send asynchronous call to permission rewrite for this user.
                    }
                    else
                    {
                        Console.WriteLine("\t" + temp.DisplayName + " has not changed yet. . . ");
                        // update user object
                        temp = graphClient.Users[temp.Id].Request().GetAsync().Result;
                        Console.WriteLine("\tupdated user object and re-queueing.");
                        work.Enqueue(temp);
                    }
                }

                /* List<String> moreToDo = new List<String>();
                 * if (wait == 25)
                 * {
                 *   for(int x = 0; x < OneDrive.Count;x++)
                 *   {
                 *       var moreWork = OneDrive.Dequeue();
                 *       var stillMore = UpdatePermissions("C:/Rebrand/Teneo_PEM.txt", graphClient, moreWork);
                 *
                 *       if (stillMore != null) { moreToDo.Add(stillMore); }
                 *   }
                 * }
                 *
                 * OneDrive = new Queue<string>(moreToDo);*/
            }
        }
Example #27
0
        public static String UpdatePermissions2(String filePath, GraphServiceClient graphClient)
        {
            // Gather all shareditem meta data in a string array variable
            // input is file path for current chunk
            var list = System.IO.File.ReadAllLines(filePath);

            Queue <String> work    = new Queue <string>(list);
            List <String>  updated = new List <String>();

            Console.WriteLine("Total Permissions to Recreate is " + work.Count);
            // Loop through queue until it is empty
            while (work.Count > 0)
            {
                bool upnChanged   = false;
                bool DoesNotExist = false;

                // take one line of input from queue
                var temp = work.Dequeue();

                var split        = temp.Split(';');
                var username     = split[0];
                var userid       = split[1];
                var folderid     = split[2];
                var permissionid = split[3];
                var grantedto    = split[4];

                Console.WriteLine(username);
                Console.WriteLine(userid);
                Console.WriteLine(folderid);
                Console.WriteLine(permissionid);
                Console.WriteLine(grantedto);

                if (updated.Contains(userid))
                {
                    upnChanged = true;
                }
                else
                {
                    var rootCheck = graphClient.Users[userid].Drive.Root.Request().GetAsync().Result;
                    if (rootCheck is null)
                    {
                        DoesNotExist = true;
                    }
                    else
                    {
                        if (rootCheck.WebUrl.Contains("teneo_com"))
                        {
                            upnChanged = true;
                            updated.Add(userid);
                        }
                        else
                        {
                            upnChanged = false;
                        }
                    }
                }

                if (upnChanged)
                {
                    try
                    {
                        // upn has been updated, recreate permissions
                        // graphClient.Users[userid].Drive.Items[folderid].Permissions[permissionid].Request().DeleteAsync().
                        var currentPermission = graphClient.Users[userid].Drive.Items[folderid].Permissions[permissionid].Request().GetAsync().Result;

                        // Run Delete and then await success
                        Console.WriteLine("Deleting Permission. . ." + permissionid);
                        var deleteTask = graphClient.Users[userid].Drive.Items[folderid].Permissions[permissionid].Request().DeleteAsync();
                        while (deleteTask.IsCompleted != true)
                        {
                            Thread.Sleep(100);
                        }
                        Console.WriteLine("Deleted");

                        if (deleteTask.IsFaulted)
                        {
                            Console.WriteLine("Failed to Delete this Permission");
                            work.Enqueue(temp);
                        }
                        else
                        {
                            List <DriveRecipient> invitees = new List <DriveRecipient>()
                            {
                                new DriveRecipient()
                                {
                                    Email = (graphClient.Users[grantedto].Request().GetAsync().Result).Mail
                                }
                            };
                            Console.WriteLine("Creating new permission. . .");
                            var createTask = graphClient.Users[userid].Drive.Items[folderid].Invite(invitees, true, new List <String>()
                            {
                                "write"
                            }, true, "Teneo rebrand permission re-established").Request().PostAsync();
                            while (createTask.IsCompleted != true)
                            {
                                if (createTask.IsFaulted)
                                {
                                    Console.WriteLine("Error in creating invite");
                                }
                            }
                            if ((createTask.Result).Count > 0)
                            {
                                Console.WriteLine("Invite Sent for " + folderid);
                            }
                        }
                    }
                    catch
                    {
                        Console.WriteLine("This Permission Errored Out.");
                        DoesNotExist = false;
                    }
                }
                else if (DoesNotExist)
                {
                }
                else
                {
                    work.Enqueue(temp);
                }
                Thread.Sleep(50);
            }
            return(null);
        }
 public GraphUsersProvider(GraphServiceClient serviceClient) : base(serviceClient, "https://graph.microsoft.com/v1.0/users")
 {
 }
Example #29
0
 //TODO dont user client secret ? or use ISecureClientSecret ?
 public EutGraphContext()
 {
     _graphClient = new GraphServiceClient(new AdalNaiveAuthenticationProvider(EutConfiguration.Current.TenantAuthorityMSOnline));
 }
Example #30
0
 //dla knt
 public static Task <string> StworzNowyEvent(Knt kontakt, GraphServiceClient graphServiceClient, string srsTopicTemplate, string srsDescriptionTemplate, string srsCalendarId)
 {
     throw new NotImplementedException();
 }
        public async Task <Tuple <bool, string, Microsoft.Graph.User> > GetUserByEmail(GraphServiceClient graphClient, string UserEmailAddress)
        {
            bool   ActionStatus = false;
            string message      = string.Empty;

            Microsoft.Graph.User returnUser = null;

            try
            {
                IGraphServiceUsersCollectionPage _usersFilteredId = await graphClient.Users.Request().Filter($"Mail eq '" + UserEmailAddress + "' or UserPrincipalName eq '" + UserEmailAddress + "'").GetAsync();

                returnUser = _usersFilteredId.FirstOrDefault();

                ActionStatus = true;
                message      = "Valid user found";
            }
            catch (Exception ex)
            {
                message = ex.Message + (ex.InnerException != null ? Environment.NewLine + ex.InnerException.Message : "");
            }

            return(new Tuple <bool, string, Microsoft.Graph.User>(ActionStatus, message, returnUser));
        }
 public Users(GraphServiceClient graphServiceClient)
 {
     _graphServiceClient = graphServiceClient;
 }
        private static async Task <DeviceIdentity> CreateDeviceIdentityInCustomerTenantAsync(string deviceIdentityProvisioningAppId)
        {
            // Create the MSAL public client application to allow the customer tenant administrator to sign in.
            // https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/System-Browser-on-.Net-Core
            var client = PublicClientApplicationBuilder.Create(deviceIdentityProvisioningAppId)
                         .WithRedirectUri("http://localhost")                     // Required for MSAL
                         .WithAuthority(AadAuthorityAudience.AzureAdMultipleOrgs) // For multi-tenant applications (excluding consumer accounts)
                         .Build();

            // Create the Graph Service client with an interactive authentication provider that uses the MSAL public client application.
            // Creating an Application or Service Principal using Delegated Permissions requires Application.ReadWrite.All, Directory.AccessAsUser.All (both require admin consent in the target tenant):
            // - https://docs.microsoft.com/en-us/graph/api/application-post-applications?view=graph-rest-1.0&tabs=http
            // - https://docs.microsoft.com/en-us/graph/api/serviceprincipal-post-serviceprincipals?view=graph-rest-1.0&tabs=http)
            // Note that these are the required permissions to create the device identity in the target tenant, which is unrelated from the final permissions the device will get.
            var scopes       = new[] { "Application.ReadWrite.All", "Directory.AccessAsUser.All" };
            var graphService = new GraphServiceClient(new InteractiveAuthenticationProvider(client, scopes, Microsoft.Identity.Client.Prompt.SelectAccount));

            // Get information about the customer tenant.
            var currentOrganization = (await graphService.Organization.Request().GetAsync()).Single();
            var currentTenantId     = currentOrganization.Id;

            // Register an application representing the device.
            var deviceIdentityApplication = new Application
            {
                DisplayName            = $"Device {Guid.NewGuid().ToString()}",
                Description            = "Created by Device Identity Provisioning Service",
                SignInAudience         = "AzureADMyOrg", // Limit exposure of this app registration to the customer tenant
                RequiredResourceAccess = new[]
                {
                    // Specify which permissions the device will ultimately need; in this case we use certain Graph API permissions to prove the point but this could be any Application Permission on any API.
                    new RequiredResourceAccess
                    {
                        ResourceAppId  = "00000003-0000-0000-c000-000000000000", // Request that the device can access the Microsoft Graph API
                        ResourceAccess = new []
                        {
                            new ResourceAccess {
                                Type = "Role", Id = new Guid("798ee544-9d2d-430c-a058-570e29e34338")
                            },                                                                                           // Request an Application Permission (i.e. "Role") for the permission "Calendars.Read"
                            new ResourceAccess {
                                Type = "Role", Id = new Guid("df021288-bdef-4463-88db-98f22de89214")
                            },                                                                                           // Request an Application Permission (i.e. "Role") for the permission "User.Read.All"
                        }
                    }
                }
            };

            deviceIdentityApplication = await graphService.Applications.Request().AddAsync(deviceIdentityApplication);

            Console.WriteLine($"Application created for device \"{deviceIdentityApplication.DisplayName}\": App ID = \"{deviceIdentityApplication.AppId}\"");
            await Task.Delay(1000); // Safety buffer

            // Create a client credential for the device.
            // https://docs.microsoft.com/en-us/graph/api/application-addpassword?view=graph-rest-1.0&tabs=http
            var clientCredential = await graphService.Applications[deviceIdentityApplication.Id].AddPassword(new PasswordCredential()).Request().PostAsync();

            Console.WriteLine($"Credential created for device: Client Secret = \"{clientCredential.SecretText}\"");
            await Task.Delay(1000); // Safety buffer

            // Create the Service Principal for the device's app registration, as this will ultimately receive the required permissions (App Roles).
            var deviceIdentityServicePrincipal = await graphService.ServicePrincipals.Request().AddAsync(new ServicePrincipal {
                AppId = deviceIdentityApplication.AppId
            });

            Console.WriteLine($"Service Principal created for device: ID = \"{deviceIdentityApplication.Id}\"");
            await Task.Delay(1000); // Safety buffer

            // Perform an admin consent (i.e. add the App Role Assignment) using the customer tenant admin's privileges for each requested resource access in the device app registration.
            foreach (var requiredResourceAccess in deviceIdentityApplication.RequiredResourceAccess)
            {
                // Look up the Service Principal of the Resource AppId in the target tenant.
                var targetResourceServicePrincipal = (await graphService.ServicePrincipals.Request().Filter($"appId eq '{requiredResourceAccess.ResourceAppId}'").GetAsync()).Single();

                // Create the App Role Assignment for each requested resource.
                foreach (var appRole in requiredResourceAccess.ResourceAccess)
                {
                    var deviceAppRoleAssignment = new AppRoleAssignment
                    {
                        AppRoleId   = appRole.Id,
                        PrincipalId = new Guid(deviceIdentityServicePrincipal.Id),
                        ResourceId  = new Guid(targetResourceServicePrincipal.Id)
                    };
                    // https://docs.microsoft.com/en-us/graph/api/serviceprincipal-post-approleassignments?view=graph-rest-1.0&tabs=http
                    deviceAppRoleAssignment = await graphService.ServicePrincipals[deviceIdentityServicePrincipal.Id].AppRoleAssignments.Request().AddAsync(deviceAppRoleAssignment);
                }
            }

            return(new DeviceIdentity
            {
                DisplayName = deviceIdentityApplication.DisplayName,
                Id = deviceIdentityApplication.Id,
                AppId = deviceIdentityApplication.AppId,
                TenantId = currentTenantId,
                ClientSecret = clientCredential.SecretText,
                CreatedDateTime = deviceIdentityApplication.CreatedDateTime
            });
        }
Example #34
0
        private static async Task ListUnifiedGroups(GraphServiceClient graphClient)
        {
            var pagedGroups = await graphClient.Groups
                .Request()
                .Filter("groupTypes/any(grp: grp eq 'Unified')")
                .GetAsync();
            Int32 pageCount = 0;

            while (true)
            {
                pageCount++;
                Console.WriteLine("Page: {0}", pageCount);
                foreach (var group in pagedGroups)
                {
                    Console.WriteLine("{0} - {1} - {2}", group.Id, group.DisplayName, group.Description);
                }

                if (pagedGroups.NextPageRequest != null)
                {
                    pagedGroups = await pagedGroups.NextPageRequest.GetAsync();
                }
                else
                {
                    break;
                }
            }
        }
        public async Task <Tuple <bool, string, List <Microsoft.Graph.User> > > GetGuestUsers(GraphServiceClient graphClient)
        {
            bool   isOk    = false;
            string message = "";

            List <Microsoft.Graph.User> users = new List <Microsoft.Graph.User>();

            try
            {
                var userpage = graphClient.Users.Request().GetAsync().Result;

                if (userpage != null)
                {
                    users = userpage.AsEnumerable().ToList();
                }

                isOk = true;
            }
            catch (Exception ex)
            {
                message = ex.Message + (ex.InnerException != null ? Environment.NewLine + ex.InnerException.Message : "");
            }

            return(new Tuple <bool, string, List <Microsoft.Graph.User> >(isOk, message, users));
        }
Example #36
0
        private static async Task GetGroupEvents(GraphServiceClient graphClient)
        {
            var unifiedGroups = await graphClient.Groups
                .Request()
                .Filter("groupTypes/any(grp: grp eq 'Unified')")
                .GetAsync();

            var groupEvents = await graphClient
                .Groups[unifiedGroups.FirstOrDefault().Id].Events
                .Request()
                .GetAsync();
            Int32 pageCount = 0;

            while (true)
            {
                pageCount++;
                Console.WriteLine("Page: {0}", pageCount);
                foreach (var e in groupEvents)
                {
                    Console.WriteLine("{0} - {1}", e.Id, e.Subject);
                }

                if (groupEvents.NextPageRequest != null)
                {
                    groupEvents = await groupEvents.NextPageRequest.GetAsync();
                }
                else
                {
                    break;
                }
            }
        }
Example #37
0
        public static async Task <Group> GetGroupByDisplayNameAsync(this GraphServiceClient service, string displayName)
        {
            var groups = (await service.Groups.Request().Filter(string.Format("displayName eq '{0}'", displayName)).Top(1).GetAsync()).CurrentPage;

            return(groups.Count > 0 ? groups[0] : null);
        }
Example #38
0
 public static async Task <string> UpdateEvent(string idKalendarza, Knt kontakt, GraphServiceClient graphServiceClient, string srsTopicTemplate, string srsDescriptionTemplate)
 {
     throw new NotImplementedException();
 }
Example #39
0
 private static async Task SendMail(GraphServiceClient graphClient,
     String recipientMail, String recipientName)
 {
     try
     {
         await graphClient.Me.SendMail(new Message
         {
             Subject = "Sent from Graph SDK",
             Body = new ItemBody
             {
                 Content = "<h1>Hello from Graph SDK!</h1>",
                 ContentType = BodyType.Html,
             },
             ToRecipients = new Recipient[] {
                 new Recipient
                 {
                     EmailAddress = new EmailAddress
                     {
                         Address = recipientMail,
                         Name = recipientName,
                     }
                 }
             },
             Importance = Importance.High,
         },
         true).Request().PostAsync();
     }
     catch (ServiceException ex)
     {
         Console.WriteLine(ex.Error);
     }
 }
Example #40
0
        public async Task <ActionResult> MSOLoginRedirect()
        {
            string encryptedCompanyID = string.Empty;
            string encodedCompanyID   = string.Empty;

            string rolename = string.Empty;

            //GenerateRandomCryptographicKey cmsKey
            string cmsKey = string.Empty;

            cmsKey = GenerateRandomKey(12);

            try
            {
                GraphServiceClient graphClient = SDKHelper.GetAuthenticatedClient();

                string useremail = await graphService.GetMyEmailAddress(graphClient);

                MyCard.Domain.User user = null;

                MyCard.Domain.Company company = null;
                company = await _companyRepository.GetFirstOrDefaultAsync(o => o.Email == useremail);

                Expression <Func <MyCard.Domain.User, object> >[] includes =
                {
                    x => x.UserRoles
                };

                if (company != null)
                {
                    user = await _userRepository.GetFirstOrDefaultAsync(o => o.Email == useremail, default(CancellationToken), includes);

                    encryptedCompanyID = MyCard.Helper.EncryptionHelper.EncryptString(Convert.ToString(user.CompanyId));
                    encodedCompanyID   = HttpUtility.UrlEncode(encryptedCompanyID);

                    foreach (var item in user.UserRoles)
                    {
                        if (item.RoleId == 1)
                        {
                            rolename = "super_admin";
                        }
                        else if (item.RoleId == 2)
                        {
                            rolename = "company_owner";
                        }
                        else
                        {
                            rolename = "user";
                        }
                    }

                    if (rolename == "company_owner")
                    {
                        var authTicket = new FormsAuthenticationTicket(
                            1,
                            user.Name + "|" + user.Id + "|" + user.CompanyId + "|" + encodedCompanyID + "|" + cmsKey, //user id
                            DateTime.Now,
                            DateTime.Now.AddDays(3),                                                                  // expiry
                            false,                                                                                    //true to remember
                            rolename,                                                                                 //roles
                            "/"
                            );

                        //encrypt the ticket and add it to a cookie
                        HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket));
                        Response.Cookies.Add(cookie);

                        //if(company.CustomerType=="Freemium")
                        //{
                        //    return RedirectToAction("Index", "CompanyDashboard");
                        //}

                        //Update Cms_key here
                        company = await _companyRepository.GetFirstOrDefaultAsync(o => o.Id == user.CompanyId);

                        company.CmsAccessKey = cmsKey;


                        _companyRepository.SetModified(company);
                        await _companyRepository.UnitOfWork.CommitAsync();

                        PurchaseOrder poUpload = _purchaseOrderRepository.GetFilteredElements(x => x.CompanyId == user.CompanyId).OrderByDescending(x => x.Id).FirstOrDefault();

                        if (poUpload != null)
                        {
                            if (poUpload.OrderFile == null || poUpload.FileName == null)
                            {
                                return(RedirectToAction("UploadPO", "CompanyDashboard"));
                            }
                            else
                            {
                                return(RedirectToAction("Index", "CompanyDashboard"));
                            }
                        }
                        else
                        {
                            return(RedirectToAction("Purchase", "CompanyDashboard"));
                        }
                    }
                    else
                    {
                        //ViewBag.Message = MyCard.Web.Resources.ErrorMessages.UserNamePasswordNotMatch;
                        return(RedirectToAction("Login", "CompanyDashboard"));
                    }
                }
                else
                {
                    //Get Organisation Data
                    //IGraphServiceOrganizationCollectionPage organization = await graphClient.Organization.Request().GetAsync();

                    GraphServiceClient graphClient1 = SDKHelper.GetAuthenticatedClient();
                    IGraphServiceOrganizationCollectionPage organization = await graphService.GetOrganisationInfo(graphClient1);

                    if (organization.Count == 0)
                    {
                        return(View("~/Views/Shared/GoToLogin.cshtml"));
                    }

                    //Commenting Below as the Freemium is now being disabled.
                    //Adding new requirement of Freemium and Premium
                    //return RedirectToAction("CompanyLicense", "Home");


                    GraphServiceClient graphClient2 = SDKHelper.GetAuthenticatedClient();

                    // Get the current user's email address.
                    //Microsoft.Graph.User me = await graphClient.Me.Request().Select("mail, userPrincipalName, displayName, jobTitle").GetAsync();
                    Microsoft.Graph.User me = await graphService.GetUserInfo(graphClient2);

                    //me.Mail ?? me.UserPrincipalName;
                    string email       = me.Mail ?? me.UserPrincipalName;
                    string displayName = me.DisplayName;
                    string companyName = organization.CurrentPage[0].DisplayName;
                    string website     = organization.CurrentPage[0].VerifiedDomains.ElementAt(0).Name; //me.MySite;
                    string jobTitle    = me.JobTitle;

                    RegistrationViewModel model = new RegistrationViewModel();
                    model.EmailID       = email;
                    model.CustomerName  = displayName;
                    model.DomainName    = website;
                    model.Name          = companyName;
                    model.BusinessTitle = jobTitle;

                    ViewBag.PageType = "Register";

                    return(View("~/Views/Registration/Register.cshtml", model));
                }
            }
            catch
            {
                return(RedirectToAction("Login", "CompanyDashboard"));
            }
        }
Example #41
0
        private static async Task SearchGroupFiles(GraphServiceClient graphClient, String searchText)
        {
            var unifiedGroups = await graphClient.Groups
                .Request()
                .Filter("groupTypes/any(grp: grp eq 'Unified')")
                .GetAsync();

            var groupDriveItems = await graphClient
                .Groups[unifiedGroups.FirstOrDefault().Id].Drive.Root.Search(searchText)
                .Request()
                .GetAsync();
            Int32 pageCount = 0;

            while (true)
            {
                pageCount++;
                Console.WriteLine("Page: {0}", pageCount);
                foreach (var driveItem in groupDriveItems)
                {
                    Console.WriteLine("{0} - {1}", driveItem.Id, driveItem.Name);
                }

                if (groupDriveItems.NextPageRequest != null)
                {
                    groupDriveItems = await groupDriveItems.NextPageRequest.GetAsync();
                }
                else
                {
                    break;
                }
            }
        }
Example #42
0
 public static void Initialize(IAuthenticationProvider authProvider)
 {
     graphClient = new GraphServiceClient(authProvider);
 }
Example #43
0
        private static async Task AddGroupConversationThread(GraphServiceClient graphClient)
        {
            var posts = new ConversationThreadPostsCollectionPage();
            posts.Add(new Post
            {
                Body = new ItemBody
                {
                    Content = "Welcome to this group!",
                    ContentType = BodyType.Text,
                }
            });

            var ct = new ConversationThread
            {
                Topic = "The Microsoft Graph SDK!",
                Posts = posts
            };

            var unifiedGroups = await graphClient.Groups
                .Request()
                .Filter("groupTypes/any(grp: grp eq 'Unified')")
                .GetAsync();

            var groupEvents = await graphClient
                .Groups[unifiedGroups.FirstOrDefault().Id].Threads
                .Request()
                .AddAsync(ct);
        }
Example #44
0
        private static void DeletePermissionsById(GraphServiceClient connection, string resourceId, string permissionId)
        {
            var request = connection.Drive.Items[resourceId].Permissions[permissionId].Request();

            request.DeleteAsync().Wait();
        }
Example #45
0
        private static async Task ManageCurrentUserPicture(GraphServiceClient graphClient)
        {
            // Get the photo of the current user
            var userPhotoStream = await graphClient.Me.Photo.Content.Request().GetAsync();

            using (FileStream fs = new FileStream(@"..\..\user-photo-original.png", FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
            {
                userPhotoStream.CopyTo(fs);
            }

            // Upload a new photo for the current user
            using (FileStream fs = new FileStream(@"..\..\user-photo-two.png", FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                try
                {
                    await graphClient.Me.Photo.Content.Request().PutAsync(fs);
                }
                catch (ServiceException ex)
                {
                    Console.WriteLine(ex.Error);
                    if (ex.IsMatch(GraphErrorCode.AccessDenied.ToString()))
                    {
                        Console.WriteLine("Access Denied! Fix permission scopes ...");
                    }
                    else if (ex.IsMatch(GraphErrorCode.ThrottledRequest.ToString()))
                    {
                        Console.WriteLine("Please retry ...");
                    }
                }
            }
        }
Example #46
0
        static async Task <string> GetUniqueMailAlias(CreateGroupRequest request)
        {
            string name         = string.IsNullOrEmpty(request.Alias) ? request.Name : request.Alias;
            string prefix       = request.Prefix;
            string suffix       = request.Suffix;
            string mailNickname = ReRemoveIllegalChars.Replace(name, "").ToLower();

            prefix = ReRemoveIllegalChars.Replace(prefix + "", "").ToLower();
            suffix = ReRemoveIllegalChars.Replace(suffix + "", "").ToLower();

            string prefixSeparator = string.Empty;

            if (!string.IsNullOrWhiteSpace(prefix) && request.UsePrefixInMailAlias)
            {
                prefixSeparator = string.IsNullOrWhiteSpace(request.PrefixSeparator) ? "-" : request.PrefixSeparator;
            }
            string suffixSeparator = string.Empty;

            if (!string.IsNullOrWhiteSpace(suffix) && request.UseSuffixInMailAlias)
            {
                suffixSeparator = string.IsNullOrWhiteSpace(request.SuffixSeparator) ? "-" : request.SuffixSeparator;
            }

            int maxCharsInEmail = 40 - prefix.Length - prefixSeparator.Length - suffixSeparator.Length - suffix.Length;

            if (mailNickname.Length > maxCharsInEmail)
            {
                mailNickname = mailNickname.Substring(0, maxCharsInEmail);
            }

            mailNickname = $"{prefix}{prefixSeparator}{mailNickname}{suffixSeparator}{suffix}";

            if (string.IsNullOrWhiteSpace(mailNickname))
            {
                mailNickname = new Random().Next(0, 9).ToString();
            }

            GraphServiceClient client = ConnectADAL.GetGraphClient();

            while (true)
            {
                IGraphServiceGroupsCollectionPage groupExist = await client.Groups.Request()
                                                               .Filter($"groupTypes/any(grp: grp eq 'Unified') and MailNickname eq '{mailNickname}'").Top(1)
                                                               .GetAsync();

                if (groupExist.Count > 0)
                {
                    string number = new Random().Next(0, 9).ToString();
                    if (string.IsNullOrWhiteSpace(suffixSeparator + suffix))
                    {
                        mailNickname += new Random().Next(0, 9).ToString();
                    }
                    else
                    {
                        int suffixIdx = mailNickname.IndexOf(suffixSeparator + suffix);
                        mailNickname = mailNickname.Insert(suffixIdx, number);
                    }
                }
                else
                {
                    break;
                }
            }
            return(mailNickname);
        }
Example #47
0
        private static async Task UploadFileToOneDriveForBusiness(GraphServiceClient graphClient)
        {
            var newFile = new Microsoft.Graph.DriveItem
            {
                File = new Microsoft.Graph.File(),
                Name = "user-photo-two.png",
            };

            newFile = await graphClient.Me.Drive.Root.Children.Request().AddAsync(newFile);
            using (FileStream fs = new FileStream(@"..\..\user-photo-two.png", FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                var newFileContent = await graphClient.Me.Drive.Items[newFile.Id].Content.Request().PutAsync<DriveItem>(fs);
            }

            Console.WriteLine("Uploaded file with ID: {0}", newFile.Id);
        }
        static async System.Threading.Tasks.Task Main(string[] args)
        {
            //Setup Auth
            string clientId     = "fd0ae99b-0717-4985-90a2-829f473c9c36";
            string tenantID     = "c73250cd-044c-4f51-beb8-020d87ee8daa";
            string clientSecret = "SfS2_O_jBDvPM-a526EwG_0rn-n5qJ-xSc";

            IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
                                                                           .Create(clientId)
                                                                           .WithTenantId(tenantID)
                                                                           .WithClientSecret(clientSecret)
                                                                           .Build();

            ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClientApplication);
            GraphServiceClient       graphClient  = new GraphServiceClient(authProvider);


            try
            {
                var @event = new Event
                {
                    Subject = "Meeting with Customer, Customer Name-Omer Amin",
                    Body    = new ItemBody
                    {
                        ContentType = BodyType.Html,
                        Content     = "Add Content here"
                    },
                    Start = new DateTimeTimeZone
                    {
                        DateTime = "2020-09-20T12:00:00",
                        TimeZone = "Pacific Standard Time"
                    },
                    End = new DateTimeTimeZone
                    {
                        DateTime = "2020-09-20T14:00:00",
                        TimeZone = "Pacific Standard Time"
                    },
                    Location = new Location
                    {
                        DisplayName = "Online"
                    },
                    Attendees = new List <Attendee>()
                    {
                        new Attendee
                        {
                            EmailAddress = new EmailAddress
                            {
                                Address = "*****@*****.**",
                                Name    = "Omer Amin"
                            },
                            Type = AttendeeType.Required
                        }
                    },
                    IsOnlineMeeting       = true,
                    OnlineMeetingProvider = OnlineMeetingProviderType.TeamsForBusiness
                };

                Task <Event> taskEvent = graphClient.Users["*****@*****.**"].Calendar.Events
                                         .Request()
                                         .AddAsync(@event);

                Console.WriteLine("Meeting ID - " + taskEvent.Result.Id);
                Console.WriteLine("WebLink - " + taskEvent.Result.OnlineMeeting.JoinUrl);



                //Sleep for 5 seconds, and then delete the meeting using the meeting ID.
                Console.WriteLine("\nSleep for 5 seconds");
                Thread.Sleep(5000);

                Console.WriteLine("Deleting meeting");
                await graphClient.Users["*****@*****.**"].Calendar.Events[taskEvent.Result.Id]
                .Request()
                .DeleteAsync();
            }
            catch (ServiceException e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.Error.Code);
                Console.WriteLine(e.StackTrace);
                throw;
            }


            //Specify meeting parameters, and then Add to user's calendar. This will return the Teams meeting link in OnlineMeeting.JoinUrl property.



            Console.WriteLine("Meeting Deleted");
        }
Example #49
0
        private static async Task DownloadFileFromOneDriveForBusiness(GraphServiceClient graphClient, String driveItemId)
        {
            var file = await graphClient.Me.Drive.Items[driveItemId].Request().Select("id,Name").GetAsync();
            var fileContent = await graphClient.Me.Drive.Items[driveItemId].Content.Request().GetAsync();

            using (FileStream fs = new FileStream(@"..\..\" + file.Name, FileMode.CreateNew, FileAccess.Write, FileShare.None))
            {
                fileContent.CopyTo(fs);
            }
        }
Example #50
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "post")] CreateGroupRequest request, TraceWriter log)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(request.Name))
                {
                    throw new ArgumentException("Parameter cannot be null", "Name");
                }
                if (string.IsNullOrWhiteSpace(request.Description))
                {
                    throw new ArgumentException("Parameter cannot be null", "Description");
                }
                string mailNickName = await GetUniqueMailAlias(request);

                string             displayName = GetDisplayName(request);
                GraphServiceClient client      = ConnectADAL.GetGraphClient(GraphEndpoint.Beta);
                var newGroup = new Group
                {
                    DisplayName     = displayName,
                    Description     = GetDescription(request.Description, 1000),
                    MailNickname    = mailNickName,
                    MailEnabled     = true,
                    SecurityEnabled = false,
                    Visibility      = request.Public ? "Public" : "Private",
                    GroupTypes      = new List <string> {
                        "Unified"
                    },
                    Classification = request.Classification
                };
                var addedGroup = await client.Groups.Request().AddAsync(newGroup);

                var createGroupResponse = new CreateGroupResponse
                {
                    GroupId     = addedGroup.Id,
                    DisplayName = displayName,
                    Mail        = addedGroup.Mail
                };
                try
                {
                    if (!request.AllowToAddGuests)
                    {
                        var groupUnifiedGuestSetting = new GroupSetting()
                        {
                            DisplayName = "Group.Unified.Guest",
                            TemplateId  = "08d542b9-071f-4e16-94b0-74abb372e3d9",
                            Values      = new List <SettingValue> {
                                new SettingValue()
                                {
                                    Name = "AllowToAddGuests", Value = "false"
                                }
                            }
                        };
                        log.Info($"Setting setting in Group.Unified.Guest (08d542b9-071f-4e16-94b0-74abb372e3d9), AllowToAddGuests = false");
                        await client.Groups[addedGroup.Id].Settings.Request().AddAsync(groupUnifiedGuestSetting);
                    }
                }
                catch (Exception e)
                {
                    log.Error($"Error setting AllowToAddGuests for group {addedGroup.Id}: {e.Message }\n\n{e.StackTrace}");
                }
                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                {
                    Content = new ObjectContent <CreateGroupResponse>(createGroupResponse, new JsonMediaTypeFormatter())
                }));
            }
            catch (Exception e)
            {
                log.Error($"Error:  {e.Message }\n\n{e.StackTrace}");
                return(await Task.FromResult(new HttpResponseMessage(HttpStatusCode.ServiceUnavailable)
                {
                    Content = new ObjectContent <string>(e.Message, new JsonMediaTypeFormatter())
                }));
            }
        }
Example #51
0
        private async Task CallGraph()
        {
            if (_graphServiceClient == null)
            {
                _graphServiceClient = _graphservice.GetAuthenticatedGraphClient(typeof(WPFAuthorizationProvider));
            }

            stopThemePolling        = true;
            stopGraphPolling        = false;
            signInPanel.Visibility  = Visibility.Collapsed;
            lblTheme.Visibility     = Visibility.Collapsed;
            loadingPanel.Visibility = Visibility.Visible;
            var(profile, presence)  = await System.Threading.Tasks.Task.Run(() => GetBatchContent());

            var photo = await System.Threading.Tasks.Task.Run(() => GetPhoto());

            if (photo == null)
            {
                MapUI(presence, profile, new BitmapImage(new Uri("pack://application:,,,/PresenceLight;component/images/UnknownProfile.png")));
            }
            else
            {
                MapUI(presence, profile, LoadImage(photo));
            }
            if (!string.IsNullOrEmpty(Config.HueApiKey) && !string.IsNullOrEmpty(Config.HueIpAddress) && !string.IsNullOrEmpty(Config.SelectedHueLightId))
            {
                await _hueService.SetColor(presence.Availability, Config.SelectedHueLightId);
            }

            if (Config.IsLIFXEnabled && !string.IsNullOrEmpty(Config.LIFXApiKey))
            {
                await _lifxService.SetColor(presence.Availability, (Selector)Config.SelectedLIFXItemId);
            }

            loadingPanel.Visibility     = Visibility.Collapsed;
            this.signInPanel.Visibility = Visibility.Collapsed;
            hueIpAddress.IsEnabled      = false;

            dataPanel.Visibility = Visibility.Visible;
            await SettingsService.SaveSettings(Config);

            while (true)
            {
                if (stopGraphPolling)
                {
                    stopGraphPolling      = false;
                    notificationIcon.Text = PresenceConstants.Inactive;
                    notificationIcon.Icon = new BitmapImage(new Uri(IconConstants.GetIcon(String.Empty, IconConstants.Inactive)));
                    return;
                }
                await Task.Delay(Convert.ToInt32(Config.PollingInterval * 1000));

                try
                {
                    presence = await System.Threading.Tasks.Task.Run(() => GetPresence());

                    if (!string.IsNullOrEmpty(Config.HueApiKey) && !string.IsNullOrEmpty(Config.HueIpAddress) && !string.IsNullOrEmpty(Config.SelectedHueLightId))
                    {
                        await _hueService.SetColor(presence.Availability, Config.SelectedHueLightId);
                    }

                    if (Config.IsLIFXEnabled && !string.IsNullOrEmpty(Config.LIFXApiKey))
                    {
                        await _lifxService.SetColor(presence.Availability, (Selector)Config.SelectedLIFXItemId);
                    }

                    MapUI(presence, null, null);
                }
                catch { }
            }
        }
        public async Task <Tuple <bool, string, string> > GetAccessReviewProgramControlList(GraphServiceClient graphclient, string accessToken, string graphUrl)
        {
            bool   ActionStatus = false;
            string message = string.Empty, jsonResult = "";

            if (graphclient == null)
            {
                return(new Tuple <bool, string, string>(false, "Invalid input data", jsonResult));
            }
            else
            {
                try
                {
                    var uri = "/beta/programControls";
                    jsonResult = await ExecuteMSGraphRequest <object>(accessToken, graphUrl, uri, HttpMethod.Get);

                    ActionStatus = true;
                }
                catch (Exception ex)
                {
                    message = ex.Message + (ex.InnerException != null ? Environment.NewLine + ex.InnerException.Message : "");
                }
            }

            return(new Tuple <bool, string, string>(ActionStatus, message, jsonResult));
        }
Example #53
0
        /// <summary>
        /// Method to update the Workforce Integration ID to the schedule.
        /// </summary>
        /// <param name="teamsId">The Shift team Id.</param>
        /// <param name="graphClient">The Graph Client.</param>
        /// <param name="wfIID">The Workforce Integration Id.</param>
        /// <param name="accessToken">The MS Graph Access token.</param>
        /// <returns>A unit of execution that contains the success or failure Response.</returns>
        public async Task <bool> AddWFInScheduleAsync(
            string teamsId,
            GraphServiceClient graphClient,
            string wfIID,
            string accessToken)
        {
            if (graphClient is null)
            {
                throw new ArgumentNullException(nameof(graphClient));
            }

            try
            {
                var sched = await graphClient.Teams[teamsId].Schedule
                            .Request()
                            .GetAsync().ConfigureAwait(false);

                var schedule = new Schedule
                {
                    Enabled  = true,
                    TimeZone = sched.TimeZone,
                    WorkforceIntegrationIds = new List <string>()
                    {
                        wfIID
                    },
                };

                var requestString = JsonConvert.SerializeObject(schedule);
                var httpClient    = this.httpClientFactory.CreateClient("GraphBetaAPI");
                using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Put, "teams/" + teamsId + "/schedule")
                {
                    Headers =
                    {
                        { HttpRequestHeader.Authorization.ToString(), $"Bearer {accessToken}" },
                    },
                    Content = new StringContent(requestString, Encoding.UTF8, "application/json"),
                })
                {
                    var response = await httpClient.SendAsync(httpRequestMessage).ConfigureAwait(false);

                    if (response.IsSuccessStatusCode)
                    {
                        var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                        return(true);
                    }
                    else
                    {
                        var failedResponseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                        var failedResponseProps = new Dictionary <string, string>()
                        {
                            { "FailedResponse", failedResponseContent },
                        };

                        this.telemetryClient.TrackTrace(BusinessLogicResource.AddWorkForceIntegrationToSchedule, failedResponseProps);
                        return(false);
                    }
                }
            }
            catch (Exception ex)
            {
                this.telemetryClient.TrackException(ex);
                throw;
            }
        }
 public HomeController(ITokenAcquisition tokenAcquisition,
                       GraphServiceClient graphServiceClient)
 {
     this.m_tokenAcquisition   = tokenAcquisition;
     this.m_graphServiceClient = graphServiceClient;
 }
Example #55
0
        public static OneDriveResultWithData <OneDrivePermission[]> GetResourcePermissions(GraphServiceClient connection, string resourceId)
        {
            CheckConnectionOrException(connection);

            OneDriveResultWithData <OneDrivePermission[]> result = ProcessRequest <OneDrivePermission[]>(() =>
            {
                var permissions           = ListPermissionsById(connection, resourceId);
                OneDrivePermission[] data = new OneDrivePermission[permissions.Length];
                for (int i = 0; i < permissions.Length; i++)
                {
                    data[i] = CreateOneDrivePermission(permissions[i]);
                }
                return(data);
            });

            return(result);
        }
Example #56
0
 public void Initialize(GraphServiceClient graphServiceClient)
 {
     _graphServiceClient = graphServiceClient;
     IsInitialized       = true;
 }
Example #57
0
        // Get the current user's email address from their profile.
        public async Task <IGraphServiceOrganizationCollectionPage> GetOrganisationInfo(GraphServiceClient graphClient)
        {
            // Get the current user.
            // This sample only needs the user's email address, so select the mail and userPrincipalName properties.
            // If the mail property isn't defined, userPrincipalName should map to the email for all account types.
            IGraphServiceOrganizationCollectionPage org = await graphClient.Organization.Request().GetAsync();

            return(org);
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services
            // Use OpenId authentication
            .AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
            // <AddSignInSnippet>
            // Specify this is a web app and needs auth code flow
            .AddMicrosoftIdentityWebApp(options => {
                Configuration.Bind("AzureAd", options);

                options.Prompt = "select_account";

                var authCodeHandler = options.Events.OnAuthorizationCodeReceived;

                options.Events.OnAuthorizationCodeReceived += async context => {
                    // Invoke the original handler first
                    // This allows the Microsoft.Identity.Web library to
                    // add the user to its token cache
                    await authCodeHandler(context);

                    var tokenAcquisition = context.HttpContext.RequestServices
                                           .GetRequiredService <ITokenAcquisition>();

                    var graphClient = new GraphServiceClient(
                        new DelegateAuthenticationProvider(async(request) => {
                        var token = await tokenAcquisition
                                    .GetAccessTokenForUserAsync(GraphConstants.Scopes, user: context.Principal);
                        request.Headers.Authorization =
                            new AuthenticationHeaderValue("Bearer", token);
                    })
                        );

                    // Get user information from Graph
                    var user = await graphClient.Me.Request()
                               .Select(u => new {
                        u.DisplayName,
                        u.Mail,
                        u.UserPrincipalName,
                        u.MailboxSettings
                    })
                               .GetAsync();

                    context.Principal.AddUserGraphInfo(user);

                    // Get the user's photo
                    // If the user doesn't have a photo, this throws
                    try
                    {
                        var photo = await graphClient.Me
                                    .Photos["48x48"]
                                    .Content
                                    .Request()
                                    .GetAsync();

                        context.Principal.AddUserGraphPhoto(photo);
                    }
                    catch (ServiceException ex)
                    {
                        if (ex.IsMatch("ErrorItemNotFound"))
                        {
                            context.Principal.AddUserGraphPhoto(null);
                        }
                        else
                        {
                            throw ex;
                        }
                    }
                };

                options.Events.OnAuthenticationFailed = context => {
                    var error = WebUtility.UrlEncode(context.Exception.Message);
                    context.Response
                    .Redirect($"/Home/ErrorWithMessage?message=Authentication+error&debug={error}");
                    context.HandleResponse();

                    return(Task.FromResult(0));
                };

                options.Events.OnRemoteFailure = context => {
                    if (context.Failure is OpenIdConnectProtocolException)
                    {
                        var error = WebUtility.UrlEncode(context.Failure.Message);
                        context.Response
                        .Redirect($"/Home/ErrorWithMessage?message=Sign+in+error&debug={error}");
                        context.HandleResponse();
                    }

                    return(Task.FromResult(0));
                };
            })
            // </AddSignInSnippet>
            // Add ability to call web API (Graph)
            // and get access tokens
            .EnableTokenAcquisitionToCallDownstreamApi(options => {
                Configuration.Bind("AzureAd", options);
            }, GraphConstants.Scopes)
            // <AddGraphClientSnippet>
            // Add a GraphServiceClient via dependency injection
            .AddMicrosoftGraph(options => {
                options.Scopes = string.Join(' ', GraphConstants.Scopes);
            })
            // </AddGraphClientSnippet>
            // Use in-memory token cache
            // See https://github.com/AzureAD/microsoft-identity-web/wiki/token-cache-serialization
            .AddInMemoryTokenCaches();

            // Require authentication
            services.AddControllersWithViews(options =>
            {
                var policy = new AuthorizationPolicyBuilder()
                             .RequireAuthenticatedUser()
                             .Build();
                options.Filters.Add(new AuthorizeFilter(policy));
            })
            // Add the Microsoft Identity UI pages for signin/out
            .AddMicrosoftIdentityUI();
        }
Example #59
-1
        private static async Task CreateUnifiedGroup(GraphServiceClient graphClient)
        {
            String randomSuffix = Guid.NewGuid().ToString("N");

            // Prepare the group resource object
            Group newGroup = new Group
            {
                DisplayName = "SDK Group " + randomSuffix,
                Description = "This has been created via Graph SDK",
                MailNickname = "sdk-" + randomSuffix,
                MailEnabled = true,
                SecurityEnabled = false,
                GroupTypes = new List<string> { "Unified" },
            };

            Group addedGroup = null;

            try
            {
                // Add the group to the collection of groups
                addedGroup = await graphClient.Groups.Request().AddAsync(newGroup);

                // Retry up to 10 times within 5 seconds, because the 
                // Office 365 Group sometime takes long to be ready
                Int32 retryCount = 0;
                while (true)
                {
                    retryCount++;

                    try
                    {
                        if (retryCount > 10) break;
                        System.Threading.Thread.Sleep(TimeSpan.FromMilliseconds(500));

                        // Upload a new photo for the Group (with retry logic)
                        using (FileStream fs = new FileStream(@"..\..\AppIcon.png", FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            await graphClient.Groups[addedGroup.Id].Photo.Content.Request().PutAsync(fs);
                            break;
                        }
                    }
                    catch
                    {
                        // Ignore any exception, just wait for a while and retry
                    }
                }

            }
            catch (ServiceException ex)
            {
                Console.WriteLine(ex.Error);
                if (ex.IsMatch(GraphErrorCode.AccessDenied.ToString()))
                {
                    Console.WriteLine("Access Denied! Fix permission scopes ...");
                }
                else if (ex.IsMatch(GraphErrorCode.ThrottledRequest.ToString()))
                {
                    Console.WriteLine("Please retry ...");
                }
            }

            // Add owners to the group
            var ownerQuery = await graphClient.Users
                .Request()
                .Filter("userPrincipalName eq '*****@*****.**'")
                .GetAsync();
            var owner = ownerQuery.FirstOrDefault();

            if (owner != null)
            {
                try
                {
                    await graphClient.Groups[addedGroup.Id].Owners.References.Request().AddAsync(owner);
                }
                catch (ServiceException ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }

            // Add members to the group
            var memberOneQuery = await graphClient.Users
                .Request()
                .Filter("userPrincipalName eq '*****@*****.**'")
                .GetAsync();
            var memberTwoQuery = await graphClient.Users
                .Request()
                .Filter("userPrincipalName eq '*****@*****.**'")
                .GetAsync();
            var memberOne = memberOneQuery.FirstOrDefault();
            var memberTwo = memberTwoQuery.FirstOrDefault();

            if (memberOne != null)
            {
                try
                {
                    await graphClient.Groups[addedGroup.Id].Members.References.Request().AddAsync(memberOne);
                }
                catch (ServiceException ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }

            if (memberTwo != null)
            {
                try
                {
                    await graphClient.Groups[addedGroup.Id].Members.References.Request().AddAsync(memberTwo);
                }
                catch (ServiceException ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }

            await UpdateUnifiedGroup(graphClient, addedGroup.Id);

            Console.WriteLine("Press ENTER to delete the just created group!");
            Console.ReadLine();

            await DeleteUnifiedGroup(graphClient, addedGroup.Id);
        }
Example #60
-3
        static async Task UseMSGraphSDKWithMSAL()
        {
            GraphServiceClient graphClient = new GraphServiceClient(
                new DelegateAuthenticationProvider(
                    async (requestMessage) =>
                    {
                        // Configure the permissions
                        String[] scopes = {
                        "User.Read",
                        "User.ReadBasic.All",
                        "Mail.Send",
                        "Mail.Read",
                        "Group.ReadWrite.All",
                        "Sites.Read.All",
                        "Directory.AccessAsUser.All",
                        "Files.ReadWrite",
                        };

                        // Acquire an access token for the given scope.
                        MSAL_clientApplication.RedirectUri = "urn:ietf:wg:oauth:2.0:oob";
                        var authenticationResult = await MSAL_clientApplication.AcquireTokenAsync(scopes);

                        // Get back the access token.
                        MSAL_AccessToken = authenticationResult.Token;

                        // Configure the HTTP bearer Authorization Header
                        requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", MSAL_AccessToken);
                    }));

            await ShowMyDisplayName(graphClient);

            await SelectUsers(graphClient);

            await FilterUsers(graphClient);

            await FilterAndOrderUsers(graphClient);

            await PartitionInboxMessages(graphClient);

            await ExpandFiles(graphClient);

            await BrowseUsersPages(graphClient);

            await CreateUnifiedGroup(graphClient);

            await SendMail(graphClient, "*****@*****.**", "Paolo Pialorsi");

            await ListUnifiedGroups(graphClient);

            await GetGroupFiles(graphClient);

            await SearchGroupFiles(graphClient, "sample");

            await GetGroupConversations(graphClient);

            await GetGroupEvents(graphClient);

            await AddGroupConversationThread(graphClient);

            await AddGroupEvent(graphClient);

            await ManageCurrentUserPicture(graphClient);

            await RetrieveCurrentUserManagerAndReports(graphClient);

            await UploadFileToOneDriveForBusiness(graphClient);

            await SearchForFilesInOneDriveForBusiness(graphClient, "contract");
        }