private static async Task CopyFlightLogToTeamFilesAsync(GraphService graphClient, string groupId)
        {
            // Upload flight log to team files
            // Get root site to determine SP host name
            var rootSite = await graphClient.GetSharePointSiteAsync("root");

            // Get flight admin site
            var adminSite = await graphClient.GetSharePointSiteAsync(
                $"{rootSite.SiteCollection.Hostname}:/sites/{flightAdminSite}");

            logger.Info("Got flight admin site");

            // Get the flight log document
            var flightLog = await graphClient.GetOneDriveItemAsync(
                adminSite.Id, $"root:/{flightLogFile}");

            logger.Info("Got flight log document");

            // Get the files folder in the team OneDrive
            var teamDrive = await graphClient.GetTeamOneDriveFolderAsync(groupId, "General");

            logger.Info("Got team OneDrive General folder");

            // Copy the file from SharePoint to team drive
            var teamDriveReference = new ItemReference
            {
                DriveId = teamDrive.ParentReference.DriveId,
                Id      = teamDrive.Id
            };

            await graphClient.CopySharePointFileAsync(adminSite.Id, flightLog.Id, teamDriveReference);

            logger.Info("Copied file to team files");
        }
示例#2
0
 public void Start()
 {
     pauseMenu.SetActive(false);
     saveDialog.SetActive(false);
     settingsMenu.SetActive(false);
     graphService = FindObjectOfType <GraphService>();
 }
 public static void SignOut()
 {
     AuthenticationContext.TokenCache.Clear();
     graphClient       = null;
     LoggedInUser      = null;
     LoggedInUserEmail = null;
 }
        // Create calendar event.
        public async Task <IActionResult> CreateEvent(string recipients, string eventId)
        {
            if (string.IsNullOrEmpty(recipients))
            {
                TempData["Message"] = "Please add a valid email address to the recipients list!";
                return(RedirectToAction("Index"));
            }

            try
            {
                string InfernoAPIKey = _configuration.GetValue <string>("InfernoAPIKey");

                // Initialize the GraphServiceClient.
                var graphClient = _graphServiceClientFactory.GetAuthenticatedGraphClient((ClaimsIdentity)User.Identity);

                // Send the email.
                var result = await GraphService.CreateEvent(graphClient, InfernoAPIKey, recipients, eventId, HttpContext);

                // Reset the current user's email address and the status to display when the page reloads.
                TempData["Message"] = result ? "Success! Your calendar event was created." : "";
                return(RedirectToAction("Index"));
            }
            catch (ServiceException se)
            {
                if (se.Error.Code == "Caller needs to authenticate.")
                {
                    return(new EmptyResult());
                }
                return(RedirectToAction("Error", "Home", new { message = "Error: " + se.Error.Message }));
            }
            catch (Exception e)
            {
                return(RedirectToAction("Error", "Home", new { message = "Error: " + e.Message }));
            }
        }
        public async Task GetMembers()
        {
            // Arrange
            var credentials = new VssBasicCredential(string.Empty, this.PAT);
            var url         = $"https://dev.azure.com/{this.Organization}";
            var connection  = new VssConnection(new Uri(url), credentials);

            var applicationGroup = new ApplicationGroup {
                Name = "Contributors"
            };
            var teamProject = new TeamProject {
                Id = new Guid("755bb057-51ac-43f6-a91a-54103f19b800"), Name = "Antidrift"
            };

            var expected = new List <string> {
                "Antidrift Team"
            };

            var target = new GraphService(connection);

            // Act
            var actual = await target.GetMembers(teamProject, applicationGroup).ConfigureAwait(false);

            // Assert
            actual.Should().Contain(expected);

            await Task.CompletedTask.ConfigureAwait(false);
        }
        public async Task GetSecureScoreInvalidPeriodAsync()
        {
            IGraphService graph;

            try
            {
                using (MockContext context = MockContext.Start(GetType().Name))
                {
                    HttpMockServer.Initialize(GetType().Name, "GetSecureScoreInvalidPeriodAsync", HttpRecorderMode.Playback);

                    graph = new GraphService(
                        new Uri(GraphServiceEndpoint),
                        new TestServiceCredentials("STUB_TOKEN"),
                        HttpMockServer.CreateInstance());

                    await graph.GetSecureScoreAsync(
                        0,
                        default(CancellationToken)).ConfigureAwait(false);

                    context.Stop();
                }
            }
            finally
            {
                graph = null;
            }
        }
        public void GraphServiceConstructorUnitTest()
        {
            Assert.Inconclusive("TODO");

            Fallen8 fallen8 = null; // TODO: Initialize to an appropriate value
            var     target  = new GraphService(fallen8);
        }
        // Load user's profile.
        public async Task <IActionResult> Index(string email)
        {
            if (User.Identity.IsAuthenticated)
            {
                // Get users's email.
                email             = email ?? User.FindFirst("preferred_username")?.Value;
                ViewData["Email"] = email;

                // Get user's id for token cache.
                var identifier = User.FindFirst(Startup.ObjectIdentifierType)?.Value;

                // Initialize the GraphServiceClient.
                var graphClient = _graphSdkHelper.GetAuthenticatedClient(identifier);

                ViewData["Response"] = await GraphService.GetUserJson(graphClient, email, HttpContext);

                ViewData["Drives"] = await GraphService.GetDrives(graphClient, email, HttpContext);

                ViewData["Picture"] = await GraphService.GetPictureBase64(graphClient, email, HttpContext);

                ViewData["User"] = await GraphService.GetUser(graphClient, email, HttpContext);
            }

            return(View());
        }
 public EventController()
 {
     graphClient                = SDKHelper.GetAuthenticatedClient();
     graphService               = new GraphService(graphClient);
     managedEventRepository     = new ManagedEventRepository(graphClient);
     schemaExtensionsRepository = new SchemaExtensionsRepository(graphClient);
 }
示例#10
0
        /// <summary>
        /// This method is used to prompt to login screen.
        /// </summary>
        /// <returns>True if sign in successfully, otherwise false</returns>
        public async Task <bool> SignInAsync()
        {
            var success = false;

            try
            {
                success = await GraphService.TryLoginAsync();
            }
            catch (Exception ex)
            {
                SignInFailed?.Invoke(this, new SignInFailedEventArgs(ex));
            }

            if (success)
            {
                AutomationProperties.SetName(this, string.Empty);

                Flyout = GenerateMenuItems();

                SignInCompleted?.Invoke(this, new SignInEventArgs()
                {
                    GraphClient = GraphService.GraphProvider
                });

                return(true);
            }

            return(false);
        }
示例#11
0
        public async Task <List <SecureScore> > ConvertAsync(SecureScoreAttribute input, CancellationToken cancellationToken)
        {
            GraphService       graphService;
            List <SecureScore> secureScore;

            try
            {
                graphService = new GraphService(
                    new Uri(input.Resource),
                    new ServiceCredentials(
                        input.ApplicationId,
                        await vault.GetSecretAsync(options.KeyVaultEndpoint, input.SecretName).ConfigureAwait(false),
                        input.Resource,
                        input.CustomerId));

                secureScore = await graphService.GetSecureScoreAsync(int.Parse(input.Period, CultureInfo.CurrentCulture), cancellationToken).ConfigureAwait(false);

                return(secureScore);
            }
            catch (ServiceClientException ex)
            {
                log.LogError(ex, $"Encountered an error when processing {input.CustomerId}");
                return(null);
            }
            finally
            {
                graphService = null;
            }
        }
示例#12
0
        private static async Task SendNotificationAsync(GraphService graphClient, List <User> users, string groupName, string newDepartureGate)
        {
            // Ideally loop through all the members here and send each a notification
            // The notification API is currently limited to only send to the logged-in user
            // So to do this, would need to manage tokens for each user.
            // For now, just send to the authenticated user.
            var notification = new Notification
            {
                TargetHostName     = notifAppId,
                AppNotificationId  = "testDirectToastNotification",
                GroupName          = "TestGroup",
                ExpirationDateTime = DateTimeOffset.UtcNow.AddDays(1).ToUniversalTime(),
                Priority           = "High",
                DisplayTimeToLive  = 30,
                Payload            = new NotificationPayload
                {
                    VisualContent = new NotificationVisualContent
                    {
                        Title = $"{groupName} gate change",
                        Body  = $"Departure gate has been changed to {newDepartureGate}"
                    }
                },
                TargetPolicy = new NotificationTargetPolicy
                {
                    PlatformTypes = new string[] { "windows", "android", "ios" }
                }
            };

            await graphClient.SendNotification(notification);
        }
示例#13
0
        // Send an email message from the current user.
        public async Task <IActionResult> SendEmail(string recipients)
        {
            if (string.IsNullOrEmpty(recipients))
            {
                TempData["Message"] = "Please add a valid email address to the recipients list!";
                return(RedirectToAction("Index"));
            }

            try
            {
                // Get user's id for token cache.
                var identifier = User.FindFirst(Startup.ObjectIdentifierType)?.Value;

                // Initialize the GraphServiceClient.
                var graphClient = _graphSdkHelper.GetAuthenticatedClient(identifier);

                // Send the email.
                await GraphService.SendEmail(graphClient, _env, recipients, HttpContext);

                // Reset the current user's email address and the status to display when the page reloads.
                TempData["Message"] = "Success! Your mail was sent.";
                return(RedirectToAction("Index"));
            }
            catch (ServiceException se)
            {
                if (se.Error.Code == "Caller needs to authenticate.")
                {
                    return(new EmptyResult());
                }
                return(RedirectToAction("Error", "Home", new { message = "Error: " + se.Error.Message }));
            }
        }
        public async Task <Graph.Event> CreateGroupRepairEventAsync(GraphService graphService, ScheduleRepairModel model)
        {
            var incident = await GetIncidentByIdAsync(model.IncidentId);

            var    property            = incident.sl_propertyID;
            var    unifiedGroupFetcher = graphService.groups.GetById(property.sl_group);
            string body = string.Format("<p>{0}</p><br/><br/><p>Incident ID: <span id='x_IncidentID'>{1}</span><br/><br/>Property ID: <span id='x_PropertyID'>{2}</span></p>",
                                        incident.sl_dispatcherComments,
                                        incident.Id,
                                        property.Id
                                        );

            var newEvent = new Graph.Event
            {
                Subject = "Repair Event",
                Body    = new Graph.ItemBody
                {
                    Content     = body,
                    ContentType = Graph.BodyType.HTML
                },
                ShowAs   = Graph.FreeBusyStatus.Busy,
                Start    = model.TimeSlotsSelectedValue.ToUniversalTime(),
                End      = (model.TimeSlotsSelectedValue.AddHours(1)).ToUniversalTime(),
                Location = new Graph.Location
                {
                    DisplayName = incident.sl_roomID.Title
                },
                Reminder = 60 * 24
            };
            await unifiedGroupFetcher.Events.AddEventAsync(newEvent);

            return(newEvent);
        }
 public VirtualSessionsController(IStorage <VirtualSession> virtualSessionsStorage, IStorage <Member> membersStorage)
 {
     this._mailer = new VirtualSessionsMailer();
     this._virtualSessionsStorage = virtualSessionsStorage;
     this._membersStorage         = membersStorage;
     this._graphService           = new GraphService();
 }
示例#16
0
        public static async Task SyncUsersInbox(User user)
        {
            GraphService graphService  = new GraphService();
            var          graphMessages = await graphService.SyncInbox();

            await ParseSyncItems(user.Id, graphMessages);
        }
        public async Task GetSecureScoreAsync()
        {
            IGraphService      graph;
            List <SecureScore> score;

            try
            {
                using (MockContext context = MockContext.Start(GetType().Name))
                {
                    HttpMockServer.Initialize(GetType().Name, "GetSecureScoreAsync", HttpRecorderMode.Playback);

                    graph = new GraphService(
                        new Uri(GraphServiceEndpoint),
                        new TestServiceCredentials("STUB_TOKEN"),
                        HttpMockServer.CreateInstance());

                    score = await graph.GetSecureScoreAsync(
                        1,
                        default(CancellationToken)).ConfigureAwait(false);

                    Assert.IsNotNull(score);
                    Assert.AreEqual(score.Count, 1);

                    context.Stop();
                }
            }
            finally
            {
                graph = null;
                score = null;
            }
        }
        public async Task CreateUnifiedGroupsForPropertiesAsync(GraphService graphService)
        {
            var properties = Task.Run(() => CSOMUtil.GetListItems(clientContext, "Properties"));

            var members = new List <IUser>();

            {
                var dispatcher = await graphService.GetFirstUserAsync(u => u.mail == AppSettings.DispatcherEmail);

                var inspectors = await graphService.GetGroupMembersAsync("Inspectors");

                var repairPeople = await graphService.GetGroupMembersAsync("Repair People");

                if (dispatcher != null)
                {
                    members.Add(dispatcher);
                }
                members.AddRange(inspectors);
                members.AddRange(repairPeople);
            }

            foreach (var property in await properties)
            {
                var group = await graphService.GetGroupByDisplayNameAsync((string)property["Title"]);

                if (group == null)
                {
                    group = await CreateUnifiedGroupForPropertyAsync(graphService, property, members);
                }
                property["sl_group"] = group.objectId;
                property.Update();
            }
            clientContext.ExecuteQuery();
        }
示例#19
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
            .AddAzureAD(options => Configuration.Bind("AzureAD", options));

            services.Configure <OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
            {
                options.Events = new OpenIdConnectEvents
                {
                    OnTokenValidated = async ctx =>
                    {
                        var roleGroups = new Dictionary <string, string>();
                        Configuration.Bind("AuthorizationGroups", roleGroups);

                        var graphService = await GraphService.CreateOnBehalfOfUserAsync(ctx.SecurityToken.RawData, Configuration);
                        var memberGroups = await graphService.CheckMemberGroupsAsync(roleGroups.Keys);

                        var claims      = memberGroups.Select(groupGuid => new Claim(ClaimTypes.Role, roleGroups[groupGuid]));
                        var appIdentity = new ClaimsIdentity(claims);
                        ctx.Principal.AddIdentity(appIdentity);
                    }
                };
            });

            services.Configure <CookieAuthenticationOptions>(AzureADDefaults.CookieScheme, options => options.AccessDeniedPath = "/accessdenied");
        }
示例#20
0
        private static async Task NotifyTeamAsync(string accessToken, NotifyFlightTeamRequest request)
        {
            // Initialize Graph client
            var graphClient = new GraphService(accessToken, logger);

            // Find groups with specified SharePoint item ID
            var groupsToNotify = await graphClient.FindGroupsBySharePointItemIdAsync(request.SharePointItemId);

            foreach (var group in groupsToNotify.Value)
            {
                // Post a Teams chat
                await PostTeamChatNotification(graphClient, group.Id, request.NewDepartureGate);

                /* Below code requires extra configuration to work.
                 * if (sendCrossDeviceNotifications)
                 * {
                 *  // Get the group members
                 *  var members = await graphClient.GetGroupMembersAsync(group.Id);
                 *
                 *  // Send notification to each member
                 *  await SendNotificationAsync(graphClient, members.Value, group.DisplayName, request.NewDepartureGate);
                 * }
                 */
            }
        }
        public async Task <ActionResult <List <Flight> > > GetFlights(
            [FromHeader] string authorization,
            [FromQuery] string queryType)
        {
            var token = await GraphService.ValidateBearerToken(authorization);

            if (string.IsNullOrEmpty(token))
            {
                return(new UnauthorizedResult());
            }

            var callingUser = await GraphService.GetUserInfo(token);

            if (callingUser.IsFlightAdmin)
            {
                // Get all flights from master list
                return(await GraphService.GetAllFlightsFromList());
            }
            else
            {
                if (!string.IsNullOrEmpty(queryType) && queryType.ToLower() == "available")
                {
                    // Get flights from master list that have open slots
                    return(await GraphService.GetOpenFlightsFromList(callingUser.EmailAddress));
                }
                else
                {
                    // Get current user's flights from calendar
                    return(await GraphService.GetAssignedFlights(token));
                }
            }
        }
示例#22
0
        public void ServiceMustGet()
        {
            var service = new GraphService(this.context);
            var result  = service.Get();

            Assert.NotNull(result);
        }
示例#23
0
        public async Task <List <Alert> > ConvertAsync(SecurityAlertsAttribute input, CancellationToken cancellationToken)
        {
            GraphService  graphService;
            IVaultService vaultService;
            List <Alert>  alerts;

            try
            {
                vaultService = new KeyVaultService(input.KeyVaultEndpoint);

                graphService = new GraphService(new Uri(input.Resource),
                                                new ServiceCredentials(
                                                    input.ApplicationId,
                                                    await vaultService.GetSecretAsync(input.SecretName).ConfigureAwait(false),
                                                    input.Resource,
                                                    input.CustomerId));

                alerts = await graphService.GetAlertsAsync().ConfigureAwait(false);

                return(alerts);
            }
            catch (ServiceClientException ex)
            {
                log.LogError(ex, $"Encountered {ex.Message} when processing {input.CustomerId}");
                return(null);
            }
            finally
            {
                graphService = null;
                vaultService = null;
            }
        }
示例#24
0
        static async Task <GraphService> GetGraphClientAsync()
        {
            var errorAuthenticating = false;

            try
            {
                await SignInAsync();

                if (!string.IsNullOrEmpty(accessToken) && IsValidDomain(LoggedUserEmail) &&
                    AppSettings.OutlookIntegration)
                {
                    var tenantId    = (LastTenantId ?? OutlookTenandId) + UriSchemeDelimiter;
                    var serviceRoot = new Uri("https://graph.microsoft.com/beta/" + tenantId);
                    graphClient = new GraphService(serviceRoot, async() =>
                    {
                        await RetrieveAccessTokenAndUserInfoAsync();

                        return(accessToken);
                    });
                }
            }
            catch (Exception)
            {
                errorAuthenticating = true;
            }

            if (errorAuthenticating)
            {
                graphClient = await GetGraphClientAsync();
            }

            return(graphClient);
        }
        private static async Task ProvisionTeamAsync(string accessToken, CreateFlightTeamRequest request)
        {
            // Initialize Graph client
            var graphClient = new GraphService(accessToken, logger);

            // Create the unified group
            var group = await CreateUnifiedGroupAsync(graphClient, request);

            // Create the team in the group
            var teamChannel = await InitializeTeamInGroupAsync(graphClient, group.Id,
                                                               $"Welcome to Flight {request.FlightNumber}!");

            // Copy flight log template to team files
            await CopyFlightLogToTeamFilesAsync(graphClient, group.Id);

            // Create Planner plan and tasks
            await CreatePreflightPlanAsync(graphClient, group.Id, teamChannel.Id, request.DepartureTime);

            // Create SharePoint list
            await CreateChallengingPassengersListAsync(graphClient, group.Id, teamChannel.Id);

            // Create SharePoint page
            if (createSharepointPage)
            {
                await CreateSharePointPageAsync(graphClient, group.Id, request.FlightNumber);
            }
        }
示例#26
0
        private static async Task <string> ProcessDelta(GraphService graphClient, ILogger log, string driveId = null, string deltaLink = null)
        {
            string deltaRequestUrl = deltaLink;

            TeamProvisioning.Initialize(graphClient, log);

            var delta = await graphClient.GetListDelta(driveId, deltaRequestUrl);

            foreach (var item in delta.CurrentPage)
            {
                await ProcessDriveItem(graphClient, item);
            }

            while (delta.NextPageRequest != null)
            {
                // There are more pages of results
                delta = await delta.NextPageRequest.GetAsync();

                foreach (var item in delta.CurrentPage)
                {
                    await ProcessDriveItem(graphClient, item);
                }
            }

            // Get the delta link
            object newDeltaLink;

            delta.AdditionalData.TryGetValue("@odata.deltaLink", out newDeltaLink);

            return(newDeltaLink.ToString());
        }
        private async void SaveMeetingAsync()
        {
            if (Meeting.IsAllDay)
            {
                EnsureAllDay();
            }

            Meeting newMeeting;

            using (new Loading(this))
            {
                newMeeting = await(string.IsNullOrEmpty(Meeting.Id) ?
                                   GraphService.CreateEvent(Meeting) :
                                   GraphService.UpdateEvent(Meeting));
            }

            if (newMeeting != null)
            {
                foreach (var att in _attachments.Where(x => string.IsNullOrEmpty(x.Id)))
                {
                    using (new Loading(this))
                    {
                        await GraphService.AddEventAttachment(newMeeting.Id, att);
                    }
                }

                UI.Publish(newMeeting);
                GoBack();
            }
        }
示例#28
0
        private async Task <string> GetAuthToken()
        {
            GraphService graphService = new GraphService();
            string       sResult      = await graphService.GetAuthToken();

            return(sResult);
        }
示例#29
0
        private async void Download_Click(object sender, RoutedEventArgs e)
        {
            if (_list.SelectedItem is DriveItem driveItem)
            {
                await GraphService.TryLoginAsync();

                GraphServiceClient graphServiceClient = GraphService.GraphProvider;
                FileSavePicker     picker             = new FileSavePicker();
                picker.FileTypeChoices.Add(AllFilesMessage, new List <string>()
                {
                    driveItem.Name.Substring(driveItem.Name.LastIndexOf("."))
                });
                picker.SuggestedFileName      = driveItem.Name;
                picker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
                StorageFile file = await picker.PickSaveFileAsync();

                if (file != null)
                {
                    using (Stream inputStream = await graphServiceClient.Drives[_driveId].Items[driveItem.Id].Content.Request().GetAsync())
                    {
                        using (Stream outputStream = await file.OpenStreamForWriteAsync())
                        {
                            await inputStream.CopyToAsync(outputStream);
                        }
                    }
                }
            }
        }
示例#30
0
 public void Start()
 {
     _ghostNode           = CreateGhostNode();
     _graphService        = FindObjectOfType <GraphService>();
     _toolPanelController = FindObjectOfType <ToolPanelController>();
     _attachedCamera      = Camera.main;
 }
 /// <summary>
 /// Get Active Directory Client for Application.
 /// </summary>
 /// <returns>ActiveDirectoryClient for Application.</returns>
 public static GraphService GetActiveDirectoryClientAsApplication()
 {
     Uri servicePointUri = new Uri(Constants.Url);
     Uri serviceRoot = new Uri(servicePointUri, Constants.TenantId);
     GraphService activeDirectoryClient = new GraphService(serviceRoot,
         async () => await AcquireTokenAsyncForApplication());
     return activeDirectoryClient;
 }
示例#32
0
        static void DisplayCurrentUserInfo_DotNet()
        {
            // create .NET client proxy for Unified API
              GraphService client = new GraphService(new Uri(urlHostTenancy), AcquireTokenForUser);

              // call across Internet and wait for response
              IUser user = client.Me.ExecuteAsync().Result;

              Console.WriteLine("Current user info obtained with .NET Client");
              Console.WriteLine("-------------------------------------------");
              Console.WriteLine("Current user info obtained with REST:");
              Console.WriteLine("Display Name: " + user.displayName);
              Console.WriteLine("First Name: " + user.givenName);
              Console.WriteLine("Last Name: " + user.surname);
              Console.WriteLine("User Principal Name: " + user.userPrincipalName);
              Console.WriteLine();
        }
示例#33
0
        static void DisplayFiles_DotNet()
        {
            // create .NET client proxy for Unified API
              GraphService client = new GraphService(new Uri(urlHostTenancy), AcquireTokenForUser);

              // get files from OneDrive site of current user
              var files = client.Me.files.Query.ExecuteAsync().Result;

              Console.WriteLine("Current user files obtained with .NET Client");
              Console.WriteLine("--------------------------------------------");
              foreach (Microsoft.Graph.Item item in files) {
            Console.WriteLine(" - " + item.name + " [" + (item.size/1000).ToString("#.0") + " MB]");
              }
              Console.WriteLine();
        }
        public async Task<IGroup> CreateUnifiedGroupForPropertyAsync(GraphService graphService, ListItem propertyItem, IEnumerable<Graph.IUser> members)
        {
            var propertyTitle = propertyItem["Title"] as string;
            var propertyOwnerName = propertyItem["sl_owner"] as string;
            var propertyOwner = await graphService.GetFirstUserAsync(i => i.displayName == propertyOwnerName);

            // Create group
            var group = new Graph.Group
            {
                displayName = propertyTitle,
                mailNickname = propertyTitle.Replace(" ", ""),
                securityEnabled = false,
                mailEnabled = true,
                groupType = "Unified",
                description = "Property Group",
            };
            try
            {
                await graphService.groups.AddGroupAsync(group);
            }
            catch { }

            // Add users to group
            var groupMembers = new HashSet<Graph.IUser>(members);
            var groupOwners = new HashSet<Graph.IUser>();
            var adminUserName = HttpContext.Current.User.Identity.Name;
            var admin = await graphService.GetFirstUserAsync(i => i.mail == adminUserName);
            if (admin != null)
            {
                groupMembers.Add(admin);
                groupOwners.Add(admin);
            }
            if (propertyOwner != null)
            {
                groupMembers.Add(propertyOwner);
                groupOwners.Add(propertyOwner);
            }
            
            foreach (var user in groupMembers.OfType<Graph.User>())
            {
                group.members.Add(user);
                try
                {
                    await group.SaveChangesAsync();
                }
                catch { }
            }

            foreach (var user in groupOwners.OfType<Graph.User>())
            {
                group.owners.Add(user);
                try
                {
                    await group.SaveChangesAsync();
                }
                catch { }
            }

            return group;
        }
        public async Task CreateUnifiedGroupsForPropertiesAsync(GraphService graphService)
        {
            var properties = Task.Run(() => CSOMUtil.GetListItems(clientContext, "Properties"));

            var members = new List<IUser>();
            {
                var dispatcher = await graphService.GetFirstUserAsync(u => u.mail == AppSettings.DispatcherEmail);
                var inspectors = await graphService.GetGroupMembersAsync("Inspectors");
                var repairPeople = await graphService.GetGroupMembersAsync("Repair People");

                if (dispatcher != null) members.Add(dispatcher);
                members.AddRange(inspectors);
                members.AddRange(repairPeople);
            }

            foreach (var property in await properties)
            {
                var group = await graphService.GetGroupByDisplayNameAsync((string)property["Title"]);
                if (group == null)
                    group = await CreateUnifiedGroupForPropertyAsync(graphService, property, members);
                property["sl_group"] = group.objectId;
                property.Update();
            }
            clientContext.ExecuteQuery();
        }
        public async Task AddGroupsAndUsersAsync(GraphService graphService)
        {
            List<string> newUsers = new List<string>();

            #region Create AD Group
            var groupsDict = new Dictionary<string, Graph.Group>();

            XmlNode groupItems = sampleData.SelectSingleNode("//List[@name='AD Groups']");

            foreach (XmlNode item in groupItems.ChildNodes)
            {
                string displayName = item.Attributes["DisplayName"].Value;
                string description = item.Attributes["Description"].Value;
                string mailNickname = item.Attributes["MailNickname"].Value;

                var group = await GraphServiceExtension.GetGroupByDisplayNameAsync(graphService, displayName);
                if (group == null)
                {
                    group = await GraphServiceExtension.AddGroupAsync(graphService, mailNickname, displayName, description);
                }
                groupsDict.Add(displayName, group as Graph.Group);
            }
            #endregion

            #region Create AD Users
            XmlNode userItems = sampleData.SelectSingleNode("//List[@name='AD Users']");
            foreach (XmlNode item in userItems)
            {
                string displayName = item.Attributes["DisplayName"].Value;
                string userPrincipalName = item.Attributes["PrincipalName"].Value;
                string password = item.Attributes["Password"].Value;
                string ownGroupDisplayName = item.Attributes["GroupsDisplayName"].Value;

                Graph.IUser user = await GraphServiceExtension.GetFirstUserAsync(graphService, i => i.displayName == displayName);
                if (user == null)
                {
                    user = await GraphServiceExtension.AddUserAsync(graphService, userPrincipalName, displayName, password);
                    await GraphServiceExtension.AssignLicenseAsyncViaHttpClientAsync(graphService, user as Graph.User);
                }

                if (groupsDict.ContainsKey(ownGroupDisplayName)
                    && (await GraphServiceExtension.GetGroupMembersAsync(graphService, ownGroupDisplayName))
                    .Where(i => i.userPrincipalName == user.userPrincipalName).Count() == 0)
                {
                    groupsDict[ownGroupDisplayName].members.Add(user as Graph.User);
                    await groupsDict[ownGroupDisplayName].SaveChangesAsync();
                }

                newUsers.Add(user.userPrincipalName);
            }
            #endregion

            AddUsersToSPGroup(newUsers);
        }
        public static async Task<GraphService> GetGraphClientAsync(string[] scope)
        {
            if (graphClient != null)
            {
                return graphClient;
            }

            var errorAuthenticating = false;

            try
            {
                AuthenticationContext = new AuthenticationContext(CommonAuthority, new TokenCache());

                var token = await GetAccessTokenAsync(AuthenticationContext, scope);

                if (string.IsNullOrEmpty(token))
                {
                    return null;
                }

                var tenantId = (LastTenantId ?? OutlookTenandId) + UriSchemeDelimiter;
                var serviceRoot = new Uri(ResourceBetaUrl + tenantId);

                graphClient = new GraphService(serviceRoot, async () =>
                    await GetAccessTokenAsync(AuthenticationContext, scope));
            }
            catch (AdalException ex) when (ex.ErrorCode == AdalError.AuthenticationCanceled)
            {
                // User tried closing sign-in window
                errorAuthenticating = true;
            }
            catch (AdalServiceException ex) when (ex.ErrorCode == "access_denied")
            {
                // The permission scope asked is denied for this user:
                // AADSTS65005: 
                //   Dynamic scope is invalid: scope Calendars.ReadWrite does not exist on application 00000003-0000-0000-c000-000000000000. 
                //   Request ID: ea763e39-1df1-437f-80f5-4578482e9ea1, Timestamp: 01/20/2016 11:00:05\r\n
                //   Trace ID: 4af73768-8231-490f-8840-f059b650b574\r\n
                //   Correlation ID: 40a55660-bf44-4b69-b5d0-ed2306914f52\r\n
                //   Timestamp: 2016-01-20 11:00:04Z

                // This same exception is used when logging-in with a valid O365 account,
                // and user cancels "asks for permission" dialog

                // TODO: Workarround to avoid the scope issue
                errorAuthenticating = false;
            }
            catch (Exception)
            {
                // Whatever else happens, re-sign-in
                errorAuthenticating = true;
            }

            if (errorAuthenticating)
            {
                graphClient = await GetGraphClientAsync(scope);
            }

            return graphClient;
        }
示例#38
0
        public async Task SignInCurrentUserAsync()
        {

            _graphClient = await AuthenticationHelper.GetGraphClientAsync();

            if (_graphClient != null)
            {
                _loggedInUserName = (string)_settings.Values["LoggedInUser"];

            }
        }
 public static void SignOut()
 {
     AuthenticationContext.TokenCache.Clear();
     graphClient = null;
     LoggedInUser = null;
     LoggedInUserEmail = null;
 }
        public async Task<Graph.Event> ScheduleRepairAsync(GraphService graphService, ScheduleRepairModel model)
        {
            var incident = await GetIncidentByIdAsync(model.IncidentId);
            var repairPeople = await GetRepairPeopleByEmailAddressAsync(model.RepairPeopleSelectedValue);

            string body = string.Format("<p>{0}</p><br/><br/><p>Incident ID: <span id='x_IncidentID'>{1}</span><br/><br/>Property ID: <span id='x_PropertyID'>{2}</span></p>",
                    incident.sl_dispatcherComments,
                    incident.Id,
                    incident.sl_propertyID.Id
                );
            var attendee = new Graph.Attendee
            {
                EmailAddress = new Graph.EmailAddress
                {
                    Address = repairPeople.sl_emailaddress,
                    Name = repairPeople.Title
                },
                Type = Graph.AttendeeType.Required
            };
            var newEvent = new Graph.Event
            {
                Subject = "Repair Event",
                Body = new Graph.ItemBody
                {
                    Content = body,
                    ContentType = Graph.BodyType.HTML
                },
                ShowAs = Graph.FreeBusyStatus.Busy,
                Start = model.TimeSlotsSelectedValue.ToUniversalTime(),
                End = (model.TimeSlotsSelectedValue.AddHours(1)).ToUniversalTime(),
                Location = new Graph.Location
                {
                    DisplayName = incident.sl_roomID.Title
                },
                Attendees = new Graph.Attendee[] { attendee }
            };
            await graphService.Me.Events.AddEventAsync(newEvent);

            return newEvent;
        }
        public async Task<Graph.Event> CreateGroupRepairEventAsync(GraphService graphService, ScheduleRepairModel model)
        {
            var incident = await GetIncidentByIdAsync(model.IncidentId);
            var property = incident.sl_propertyID;
            var unifiedGroupFetcher = graphService.groups.GetById(property.sl_group);
            string body = string.Format("<p>{0}</p><br/><br/><p>Incident ID: <span id='x_IncidentID'>{1}</span><br/><br/>Property ID: <span id='x_PropertyID'>{2}</span></p>",
                    incident.sl_dispatcherComments,
                    incident.Id,
                    property.Id
                );

            var newEvent = new Graph.Event
            {
                Subject = "Repair Event",
                Body = new Graph.ItemBody
                {
                    Content = body,
                    ContentType = Graph.BodyType.HTML
                },
                ShowAs = Graph.FreeBusyStatus.Busy,
                Start = model.TimeSlotsSelectedValue.ToUniversalTime(),
                End = (model.TimeSlotsSelectedValue.AddHours(1)).ToUniversalTime(),
                Location = new Graph.Location
                {
                    DisplayName = incident.sl_roomID.Title
                },
                Reminder = 60 * 24
            };
            await unifiedGroupFetcher.Events.AddEventAsync(newEvent);

            return newEvent;
        }
        public static GraphService GetGraphClient()
        {
            if (_graphClient != null)
            {
                return _graphClient;
            }

            string authority = null;
            if (string.IsNullOrEmpty(LastAuthority))
            {
                authority = OfficeSettings.Authority;
            }
            else
            {
                authority = LastAuthority;
            }

            if (_authenticationContext == null)
            {
                var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
                _authenticationContext = new AuthenticationContext(authority, new ADALTokenCache(signInUserId));
            }

            var client = new GraphService(new Uri(OfficeSettings.GraphBaseTenantAddress),
                                          async () => (await GetTokenAsync(_authenticationContext,
                                                                          OfficeSettings.GraphResourceId)).AccessToken);
            _graphClient = client;
            return _graphClient;
        }
        static async Task<GraphService> GetGraphClientAsync()
        {
            var errorAuthenticating = false;

            try
            {
                await SignInAsync();

                if (!string.IsNullOrEmpty(accessToken) && IsValidDomain(LoggedUserEmail)
                    && AppSettings.OutlookIntegration)
                {
                    var tenantId = (LastTenantId ?? OutlookTenandId) + UriSchemeDelimiter;
                    var serviceRoot = new Uri("https://graph.microsoft.com/beta/" + tenantId);
                    graphClient = new GraphService(serviceRoot, async () => 
						{
							await RetrieveAccessTokenAndUserInfoAsync();

							return accessToken;
						});
                }
            }
            catch (Exception)
            {
                errorAuthenticating = true;
            }

            if (errorAuthenticating)
                graphClient = await GetGraphClientAsync();

            return graphClient;
        }
        /// <summary>
        /// Signs the user out of the service.
        /// </summary>
        public static void SignOut()
        {
            _authenticationContext.TokenCache.Clear();

            //Clean up all existing clients
            _graphClient = null;
            //Clear stored values from last authentication.
            _settings.Values["TenantId"] = null;
            _settings.Values["LastAuthority"] = null;
            _settings.Values["LoggedInUser"] = null;
            _settings.Values["LoggedInUserEmail"] = null;

        }
        /// <summary>
        /// Checks that an OutlookServicesClient object is available. 
        /// </summary>
        /// <returns>The OutlookServicesClient object. </returns>
        public static async Task<GraphService> GetGraphClientAsync()
        {
            if (_graphClient != null)
            {
                return _graphClient;
            }
            else
            {
                try
                {
                    //First, look for the authority used during the last authentication.
                    //If that value is not populated, use CommonAuthority.
                    string authority = null;
                    if (String.IsNullOrEmpty(LastAuthority))
                    {
                        authority = CommonAuthority;
                    }
                    else
                    {
                        authority = LastAuthority;
                    }

                    // Create an AuthenticationContext using this authority.
                    _authenticationContext = new AuthenticationContext(authority);


                    // Set the value of _authenticationContext.UseCorporateNetwork to true so that you 
                    // can use this app inside a corporate intranet. If the value of UseCorporateNetwork 
                    // is true, you also need to add the Enterprise Authentication, Private Networks, and
                    // Shared User Certificates capabilities in the Package.appxmanifest file.

                    _authenticationContext.UseCorporateNetwork = true;


                    var token = await GetTokenHelperAsync(_authenticationContext, ResourceUrl);


                    // Check the token
                    if (String.IsNullOrEmpty(token))
                    {
                        // User cancelled sign-in
                        return null;
                    }
                    else
                    {
                        Uri serviceRoot = new Uri(ResourceBetaUrl + TenantId);
                        _graphClient = new Microsoft.Graph.GraphService(serviceRoot,
                        async () => await GetTokenHelperAsync(_authenticationContext, ResourceUrl));
                        return _graphClient;
                    }
                }
                // The following is a list of all exceptions you should consider handling in your app.
                // In the case of this sample, the exceptions are handled by returning null upstream. 

                catch (ArgumentException ae)
                {
                    // Argument exception
                    Debug.WriteLine("Exception: " + ae.Message);
                    _authenticationContext.TokenCache.Clear();
                    return null;
                }
                catch (Exception e)
                {
                    Debug.WriteLine("Exception: " + e.Message);
                    _authenticationContext.TokenCache.Clear();
                    return null;
                }
            }
        }
        public static GraphService GetGraphService()
        {
            try
            {
                if (graphService != null)
                    return graphService;

                graphService = new GraphService(new Uri(GraphEndpointId), GetTokenHelperAsync);

                return graphService;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                return null;
            }


        }
        public static async Task<GraphService> GetGraphClientAsync(string[] scope)
        {
            if (graphClient == null)
            {
                try
                {
                    AuthenticationContext = new AuthenticationContext(CommonAuthority, new TokenCache());

                    var token = await GetAccessTokenAsync(AuthenticationContext, scope);
                    if (string.IsNullOrEmpty(token))
                    {
                        // User cancelled sign-in
                        return null;
                    }
                    else
                    {
                        var tenantId = (LastTenantId ?? "outlook.com") + "/";
                        Uri serviceRoot = new Uri(ResourceBetaUrl + tenantId);
                        graphClient = new GraphService(serviceRoot, async () => await GetAccessTokenAsync(AuthenticationContext, scope));
                    }
                }
                catch (AdalException ex)
                {
                    Debug.WriteLine("Error from Adal: " + ex.ToString());
                    AuthenticationContext.TokenCache.Clear();
                    return null;
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("Exception thrown: " + ex.ToString());
                    AuthenticationContext.TokenCache.Clear();
                    return null;
                }
            }

            return graphClient;
        }
 /// <summary>
 /// Get Active Directory Client for User.
 /// </summary>
 /// <returns>ActiveDirectoryClient for User.</returns>
 public static GraphService GetActiveDirectoryClientAsUser()
 {
     
     Uri serviceRoot = new Uri(Constants.Url);
     GraphService graphClient = new GraphService(serviceRoot, 
         async () => await AcquireTokenAsyncForUser()); 
     return graphClient;
 }