public void Initialize(IExportContext context) { this.context = context; this.client = ((GraphConnectionContext)context.ConnectionContext).Client; this.betaClient = ((GraphConnectionContext)context.ConnectionContext).BetaClient; this.userFilter = ((GraphConnectionContext)context.ConnectionContext).UserFilter; this.token = context.Token; }
public static async Task GetGroups(Beta.GraphServiceClient client, ITargetBlock <Beta.Group> target, string filter, CancellationToken token, params string[] selectProperties) { string constructedFilter = "resourceProvisioningOptions/Any(x:x eq 'Team')"; if (!string.IsNullOrWhiteSpace(filter)) { constructedFilter += $" and {filter}"; } logger.Trace($"Enumerating groups with filter {constructedFilter}"); var request = client.Groups.Request().Select(string.Join(",", selectProperties)).Filter(constructedFilter); await GetGroups(request, target, token); }
public static async Task RemoveChannelMembers(Beta.GraphServiceClient client, string teamid, string channelid, IList <Beta.AadUserConversationMember> members, bool ignoreNotFound, CancellationToken token) { if (members.Count == 0) { return; } Dictionary <string, Func <BatchRequestStep> > requests = new Dictionary <string, Func <BatchRequestStep> >(); foreach (var member in members) { requests.Add(member.Id, () => GraphHelper.GenerateBatchRequestStep(HttpMethod.Delete, member.Id, client.Teams[teamid].Channels[channelid].Members[member.UserId].Request().RequestUrl)); } logger.Trace($"Removing {requests.Count} members in batch request for channel {teamid}:{channelid}"); await GraphHelper.SubmitAsBatches(client, requests, ignoreNotFound, false, token); }
// Get an Authenticated Microsoft Graph client using the token issued to the user. private Beta.GraphServiceClient GetAuthenticatedClient() { var graphClient = new Beta.GraphServiceClient( new DelegateAuthenticationProvider( requestMessage => { // Append the access token to the request. requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", _token); // Get event times in the current time zone. requestMessage.Headers.Add("Prefer", "outlook.timezone=\"" + TimeZoneInfo.Local.Id + "\""); return(Task.CompletedTask); })); return(graphClient); }
public static async Task UpdateChannelMembers(Beta.GraphServiceClient client, string teamid, string channelid, IList <Beta.AadUserConversationMember> members, CancellationToken token) { if (members.Count == 0) { return; } Dictionary <string, Func <BatchRequestStep> > requests = new Dictionary <string, Func <BatchRequestStep> >(); foreach (var member in members) { requests.Add(member.Id, () => GraphHelper.GenerateBatchRequestStepJsonContent(new HttpMethod("PATCH"), member.Id, client.Teams[teamid].Channels[channelid].Members[member.UserId].Request().RequestUrl, JsonConvert.SerializeObject(member))); } logger.Trace($"Adding {requests.Count} members in batch request for channel {teamid}:{channelid}"); await GraphHelper.SubmitAsBatches(client, requests, false, false, token); }
public static async Task <string> CreateTeam(Beta.GraphServiceClient client, Beta.Team team, CancellationToken token) { TeamsAsyncOperation result = await GraphHelperTeams.SubmitTeamCreateRequestAndWait(client, team, token); if (result.Status == TeamsAsyncOperationStatus.Succeeded) { return(result.TargetResourceId); } string serializedResponse = JsonConvert.SerializeObject(result); logger.Error($"Team creation failed\r\n{serializedResponse}"); throw new ServiceException(new Error() { Code = result.Error.Code, AdditionalData = result.Error.AdditionalData, Message = result.Error.Message }); }
public async Task InstallAppAndAddTabToCalendarEvent(Beta.GraphServiceClient graphServiceClient, string onlineMeetingJoinUrl) { try { var chatId = onlineMeetingJoinUrl.Split('/')[5]; var teamsAppInstallation = new Beta.TeamsAppInstallation { AdditionalData = new Dictionary <string, object>() { { "*****@*****.**", $"https://graph.microsoft.com/v1.0/appCatalogs/teamsApps/{_configuration["AppId"]}" } } }; await graphServiceClient.Chats[chatId].InstalledApps .Request() .AddAsync(teamsAppInstallation); var teamsTab = new Beta.TeamsTab { DisplayName = "Add Notes", Configuration = new Beta.TeamsTabConfiguration { EntityId = Guid.NewGuid().ToString("N").ToUpper(), ContentUrl = $"{_configuration["BaseUrl"]}/addnotes", WebsiteUrl = _configuration["BaseUrl"], RemoveUrl = $"{_configuration["BaseUrl"]}/uninstallTab" }, AdditionalData = new Dictionary <string, object>() { { "*****@*****.**", $"https://graph.microsoft.com/beta/appCatalogs/teamsApps/{_configuration["AppId"]}" } } }; await graphServiceClient.Chats[chatId].Tabs .Request() .AddAsync(teamsTab); } catch (Exception e) { _logger.LogError(e.Message + ' ' + e.StackTrace); } }
public static async Task AddChannelMembers(Beta.GraphServiceClient client, string teamid, string channelid, IList <Beta.AadUserConversationMember> members, bool ignoreMemberExists, CancellationToken token) { if (members.Count == 0) { return; } Dictionary <string, Func <BatchRequestStep> > requests = new Dictionary <string, Func <BatchRequestStep> >(); foreach (var member in members) { //await GraphHelper.ExecuteWithRetryAndRateLimit(async () => await client.Teams[teamid].Channels[channelid].Members.Request().AddAsync(member, token), token, 1); // logger.Trace(JsonConvert.SerializeObject(member)); requests.Add(member.UserId, () => GraphHelper.GenerateBatchRequestStepJsonContent(HttpMethod.Post, member.UserId, client.Teams[teamid].Channels[channelid].Members.Request().RequestUrl, JsonConvert.SerializeObject(member))); } logger.Trace($"Adding {requests.Count} members in batch request for channel {teamid}:{channelid}"); await GraphHelper.SubmitAsBatches(client, requests, false, ignoreMemberExists, token); }
private static async Task <TeamsAsyncOperation> AsyncRequestWait(Beta.GraphServiceClient client, CancellationToken token, string location) { TeamsAsyncOperation result; int waitCount = 1; do { await Task.Delay(TimeSpan.FromSeconds(3 * waitCount), token); var b = new TeamsAsyncOperationRequestBuilder($"{client.BaseUrl}{location}", client); // GetAsyncOperation API sometimes returns 'bad request'. Possibly a replication issue. So we create a custom IsRetryable handler for this call only result = await GraphHelper.ExecuteWithRetryAndRateLimit(async() => await b.Request().GetAsync(token), token, 1, GraphHelperTeams.IsGetAsyncOperationRetryable); GraphHelperTeams.logger.Trace($"Result of async operation is {result.Status}: Count : {waitCount}"); waitCount++; } while (result.Status == TeamsAsyncOperationStatus.InProgress || result.Status == TeamsAsyncOperationStatus.NotStarted); return(result); }
public static async Task <List <Beta.Channel> > GetChannels(Beta.GraphServiceClient client, string teamid, CancellationToken token) { List <Beta.Channel> channels = new List <Beta.Channel>(); var page = await GraphHelper.ExecuteWithRetryAndRateLimit(async() => await client.Teams[teamid].Channels.Request().GetAsync(token), token, 0); if (page?.Count > 0) { channels.AddRange(page.CurrentPage); while (page.NextPageRequest != null) { page = await GraphHelper.ExecuteWithRetryAndRateLimit(async() => await page.NextPageRequest.GetAsync(token), token, 0); channels.AddRange(page.CurrentPage); } } return(channels); }
public async void Login() { // Build a client application. IPublicClientApplication publicClientApplication = PublicClientApplicationBuilder .Create(_clientID) .WithAuthority(AzureCloudInstance.AzurePublic, AadAuthorityAudience.AzureAdMultipleOrgs) .WithRedirectUri("https://login.microsoftonline.com/common/oauth2/nativeclient") .Build(); //var authProvider = new UsernamePasswordProvider(publicClientApplication, graphScopes); var authProvider = new InteractiveAuthenticationProvider(publicClientApplication, graphScopes); // Create an authentication provider by passing in a client application and graph scopes. //DeviceCodeProvider authProvider = new DeviceCodeProvider(publicClientApplication, graphScopes); // Create a new instance of GraphServiceClient with the authentication provider. this._graphClient = new Beta.GraphServiceClient(authProvider); Beta.User profile = await this._graphClient.Me.Request().GetAsync(); this.txtUsername.Text = profile.UserPrincipalName; }
public async Task <List <CustomTeamMember> > GetMembers(string id) { Beta.GraphServiceClient graphServiceClient = new Beta.GraphServiceClient(new DelegateAuthenticationProvider((requestMessage) => { requestMessage .Headers .Authorization = new AuthenticationHeaderValue("Bearer", AuthProvider.GetAccessTokenFromCurrentUser()); return(Task.FromResult(0)); })); var members = await graphServiceClient .Teams[id].Members .Request() .GetAsync(); List <CustomTeamMember> result = new List <CustomTeamMember>(); foreach (Beta.AadUserConversationMember member in members.CurrentPage) { CustomTeamMember ctm = new CustomTeamMember() { DisplayName = member.DisplayName, Email = member.Email, }; List <string> roles = (List <string>)member.Roles; if (roles.Count > 0) { ctm.Roles = roles[0]; } else { ctm.Roles = ""; } result.Add(ctm); } return(result); }
private static async Task <string> AsyncRequestSubmit(Beta.GraphServiceClient client, HttpRequestMessage message, CancellationToken token) { using (var response = await client.HttpProvider.SendAsync(message, HttpCompletionOption.ResponseHeadersRead, token)) { if (response.StatusCode == HttpStatusCode.Accepted) { var location = response.Headers.Location; if (location == null) { throw new InvalidOperationException("The location header was null"); } logger.Trace($"Async request submissions was successful at {location}"); return(location.ToString()); } logger.Trace($"{response.StatusCode}"); throw new InvalidOperationException("The request was not successful"); } }
/// <summary> /// Initializes a new instance of the <see cref="EventGraphHelper"/> class. /// </summary> /// <param name="tokenAcquisitionHelper">Helper to get user access token for specified Graph scopes.</param> /// <param name="httpContextAccessor">HTTP context accessor for getting user claims.</param> /// <param name="userGraphHelper">The user graph helper dependency injection</param> public EventGraphHelper( ITokenAcquisitionHelper tokenAcquisitionHelper, IHttpContextAccessor httpContextAccessor, IUserGraphHelper userGraphHelper) { httpContextAccessor = httpContextAccessor ?? throw new ArgumentNullException(nameof(httpContextAccessor)); this.userGraphHelper = userGraphHelper; var oidClaimType = "http://schemas.microsoft.com/identity/claims/objectidentifier"; var userObjectId = httpContextAccessor.HttpContext.User.Claims? .FirstOrDefault(claim => oidClaimType.Equals(claim.Type, StringComparison.OrdinalIgnoreCase))?.Value; if (!string.IsNullOrEmpty(userObjectId)) { var jwtToken = AuthenticationHeaderValue.Parse(httpContextAccessor.HttpContext.Request.Headers["Authorization"].ToString()).Parameter; this.delegatedGraphClient = GraphServiceClientFactory .GetAuthenticatedGraphClient(async() => { return(await tokenAcquisitionHelper.GetUserAccessTokenAsync(userObjectId, jwtToken)); }); this.applicationBetaGraphClient = GraphServiceClientFactory .GetAuthenticatedBetaGraphClient(async() => { return(await tokenAcquisitionHelper.GetApplicationAccessTokenAsync()); }); this.applicationGraphClient = GraphServiceClientFactory .GetAuthenticatedGraphClient(async() => { return(await tokenAcquisitionHelper.GetApplicationAccessTokenAsync()); }); } }
private static async Task <TeamsAsyncOperation> SubmitTeamArchiveRequestAndWait(Beta.GraphServiceClient client, string teamid, bool?setSpoSiteReadOnly, CancellationToken token) { string location = await GraphHelper.ExecuteWithRetryAndRateLimit(async() => { var message = new HttpRequestMessage(); message.Method = HttpMethod.Post; message.RequestUri = new Uri(client.Teams[teamid].RequestUrl + "/archive"); if (setSpoSiteReadOnly.HasValue && setSpoSiteReadOnly.Value) { message.Content = new StringContent("{\"shouldSetSpoSiteReadOnlyForMembers\": true}", Encoding.UTF8, "application/json"); } else { message.Content = new StringContent("{\"shouldSetSpoSiteReadOnlyForMembers\": false}", Encoding.UTF8, "application/json");; } return(await AsyncRequestSubmit(client, message, token)); }, token, 1); return(await AsyncRequestWait(client, token, location)); }
public static async Task UnarchiveTeam(Beta.GraphServiceClient client, string teamid, CancellationToken token) { await GraphHelperTeams.SubmitTeamUnarchiveRequestAndWait(client, teamid, token); }
public static async Task ArchiveTeam(Beta.GraphServiceClient client, string teamid, bool setSpoReadOnly, CancellationToken token) { await GraphHelperTeams.SubmitTeamArchiveRequestAndWait(client, teamid, setSpoReadOnly, token); }
public static async Task DeleteChannel(Beta.GraphServiceClient client, string teamid, string channelid, CancellationToken token) { await GraphHelper.ExecuteWithRetryAndRateLimit(async() => await client.Teams[teamid].Channels[channelid].Request().DeleteAsync(token), token, 1); }
//public static async Task<Team> GetTeam(GraphServiceClient client, string teamid, CancellationToken token) //{ // return await GraphHelper.ExecuteWithRetryAndRateLimit(async () => await client.Teams[teamid].Request().GetAsync(token), token, 0); //} public static async Task <Beta.Team> GetTeam(Beta.GraphServiceClient client, string teamid, CancellationToken token) { return(await GraphHelper.ExecuteWithRetryAndRateLimit(async() => await client.Teams[teamid].Request().GetAsync(token), token, 0)); }
public static async Task <List <Beta.AadUserConversationMember> > GetChannelMembers(Beta.GraphServiceClient client, string groupId, string channelId, CancellationToken token) { List <Beta.AadUserConversationMember> members = new List <Beta.AadUserConversationMember>(); var page = await GraphHelper.ExecuteWithRetryAndRateLimit(async() => await client.Teams[groupId].Channels[channelId].Members.Request().GetAsync(token), token, 0); if (page?.Count > 0) { members.AddRange(page.CurrentPage.Where(t => t is Beta.AadUserConversationMember && (t.Roles == null || t.Roles.Any(u => !string.Equals(u, "guest", StringComparison.OrdinalIgnoreCase)))).Cast <Beta.AadUserConversationMember>()); while (page.NextPageRequest != null) { page = await GraphHelper.ExecuteWithRetryAndRateLimit(async() => await page.NextPageRequest.GetAsync(token), token, 0); members.AddRange(page.CurrentPage.Where(t => t is Beta.AadUserConversationMember && (t.Roles == null || t.Roles.Any(u => !string.Equals(u, "guest", StringComparison.OrdinalIgnoreCase)))).Cast <Beta.AadUserConversationMember>()); } } return(members); }
private async Task <string> CreateTeam(CSEntryChange csentry, Beta.GraphServiceClient client, string ownerId) { var team = new Beta.Team { MemberSettings = new Beta.TeamMemberSettings(), GuestSettings = new Beta.TeamGuestSettings(), MessagingSettings = new Beta.TeamMessagingSettings(), FunSettings = new Beta.TeamFunSettings(), ODataType = null }; team.MemberSettings.ODataType = null; team.GuestSettings.ODataType = null; team.MessagingSettings.ODataType = null; team.FunSettings.ODataType = null; team.AdditionalData = new Dictionary <string, object>(); team.DisplayName = csentry.GetValueAdd <string>("displayName"); team.Description = csentry.GetValueAdd <string>("description"); if (csentry.HasAttributeChange("visibility")) { string visibility = csentry.GetValueAdd <string>("visibility"); if (Enum.TryParse(visibility, out Beta.TeamVisibilityType result)) { team.Visibility = result; } else { throw new UnsupportedAttributeModificationException($"The value '{visibility}' provided for attribute 'visibility' was not supported. Allowed values are {string.Join(",", Enum.GetNames(typeof(Beta.TeamVisibilityType)))}"); } } string template = csentry.GetValueAdd <string>("template") ?? "https://graph.microsoft.com/beta/teamsTemplates('standard')"; if (!string.IsNullOrWhiteSpace(template)) { team.AdditionalData.Add("*****@*****.**", template); } team.AdditionalData.Add("*****@*****.**", new string[] { $"https://graph.microsoft.com/v1.0/users('{ownerId}')" }); team.MemberSettings.AllowCreateUpdateChannels = csentry.HasAttributeChange("memberSettings_allowCreateUpdateChannels") ? csentry.GetValueAdd <bool>("memberSettings_allowCreateUpdateChannels") : default(bool?); team.MemberSettings.AllowDeleteChannels = csentry.HasAttributeChange("memberSettings_allowDeleteChannels") ? csentry.GetValueAdd <bool>("memberSettings_allowDeleteChannels") : default(bool?); team.MemberSettings.AllowAddRemoveApps = csentry.HasAttributeChange("memberSettings_allowAddRemoveApps") ? csentry.GetValueAdd <bool>("memberSettings_allowAddRemoveApps") : default(bool?); team.MemberSettings.AllowCreateUpdateRemoveTabs = csentry.HasAttributeChange("memberSettings_allowCreateUpdateRemoveTabs") ? csentry.GetValueAdd <bool>("memberSettings_allowCreateUpdateRemoveTabs") : default(bool?); team.MemberSettings.AllowCreateUpdateRemoveConnectors = csentry.HasAttributeChange("memberSettings_allowCreateUpdateRemoveConnectors") ? csentry.GetValueAdd <bool>("memberSettings_allowCreateUpdateRemoveConnectors") : default(bool?); team.GuestSettings.AllowCreateUpdateChannels = csentry.HasAttributeChange("guestSettings_allowCreateUpdateChannels") ? csentry.GetValueAdd <bool>("guestSettings_allowCreateUpdateChannels") : default(bool?); team.GuestSettings.AllowDeleteChannels = csentry.HasAttributeChange("guestSettings_allowDeleteChannels") ? csentry.GetValueAdd <bool>("guestSettings_allowDeleteChannels") : default(bool?); team.MessagingSettings.AllowUserEditMessages = csentry.HasAttributeChange("messagingSettings_allowUserEditMessages") ? csentry.GetValueAdd <bool>("messagingSettings_allowUserEditMessages") : default(bool?); team.MessagingSettings.AllowUserDeleteMessages = csentry.HasAttributeChange("messagingSettings_allowUserDeleteMessages") ? csentry.GetValueAdd <bool>("messagingSettings_allowUserDeleteMessages") : default(bool?); team.MessagingSettings.AllowOwnerDeleteMessages = csentry.HasAttributeChange("messagingSettings_allowOwnerDeleteMessages") ? csentry.GetValueAdd <bool>("messagingSettings_allowOwnerDeleteMessages") : default(bool?); team.MessagingSettings.AllowTeamMentions = csentry.HasAttributeChange("messagingSettings_allowTeamMentions") ? csentry.GetValueAdd <bool>("messagingSettings_allowTeamMentions") : default(bool?); team.MessagingSettings.AllowChannelMentions = csentry.HasAttributeChange("messagingSettings_allowChannelMentions") ? csentry.GetValueAdd <bool>("messagingSettings_allowChannelMentions") : default(bool?); team.FunSettings.AllowGiphy = csentry.HasAttributeChange("funSettings_allowGiphy") ? csentry.GetValueAdd <bool>("funSettings_allowGiphy") : default(bool?); team.FunSettings.AllowStickersAndMemes = csentry.HasAttributeChange("funSettings_allowStickersAndMemes") ? csentry.GetValueAdd <bool>("funSettings_allowStickersAndMemes") : default(bool?); team.FunSettings.AllowCustomMemes = csentry.HasAttributeChange("funSettings_allowCustomMemes") ? csentry.GetValueAdd <bool>("funSettings_allowCustomMemes") : default(bool?); string gcr = csentry.GetValueAdd <string>("funSettings_giphyContentRating"); if (!string.IsNullOrWhiteSpace(gcr)) { if (!Enum.TryParse(gcr, false, out Beta.GiphyRatingType grt)) { throw new UnsupportedAttributeModificationException($"The value '{gcr}' provided for attribute 'funSettings_giphyContentRating' was not supported. Allowed values are {string.Join(",", Enum.GetNames(typeof(Beta.GiphyRatingType)))}"); } team.FunSettings.GiphyContentRating = grt; } logger.Info($"{csentry.DN}: Creating team using template {template ?? "standard"}"); logger.Trace($"{csentry.DN}: Team data: {JsonConvert.SerializeObject(team)}"); var tresult = await GraphHelperTeams.CreateTeam(client, team, this.token); logger.Info($"{csentry.DN}: Created team {tresult}"); await Task.Delay(TimeSpan.FromSeconds(MicrosoftTeamsMAConfigSection.Configuration.PostGroupCreateDelay), this.token); return(tresult); }
private static async Task <TeamsAsyncOperation> SubmitTeamUnarchiveRequestAndWait(Beta.GraphServiceClient client, string teamid, CancellationToken token) { string location = await GraphHelper.ExecuteWithRetryAndRateLimit(async() => { var message = new HttpRequestMessage(); message.Method = HttpMethod.Post; message.RequestUri = new Uri(client.Teams[teamid].RequestUrl + "/unarchive"); message.Content = new StringContent(string.Empty, Encoding.UTF8, "application/json"); return(await AsyncRequestSubmit(client, message, token)); }, token, 1); return(await AsyncRequestWait(client, token, location)); }
public static async Task UpdateTeam(Beta.GraphServiceClient client, string teamid, Beta.Team team, CancellationToken token) { await GraphHelper.ExecuteWithRetryAndRateLimit(async() => await client.Teams[teamid].Request().UpdateAsync(team, token), token, 1); }
/// <summary> /// Initialize the graph clients using an authProvider /// </summary> /// <param name="authProvider"></param> public GalleryAppsRepository(IAuthenticationProvider authProvider, ILogger logger) { _graphClient = new GraphServiceClient(authProvider); _graphBetaClient = new Beta.GraphServiceClient(authProvider); this.logger = logger; }
public static async Task <Beta.Channel> UpdateChannel(Beta.GraphServiceClient client, string teamid, string channelid, Beta.Channel channel, CancellationToken token) { return(await GraphHelper.ExecuteWithRetryAndRateLimit(async() => await client.Teams[teamid].Channels[channelid].Request().UpdateAsync(channel, token), token, 1)); }
public static async Task <Beta.Team> CreateTeamFromGroup(Beta.GraphServiceClient client, string groupid, Beta.Team team, CancellationToken token) { return(await GraphHelper.ExecuteWithRetryAndRateLimit(async() => await client.Groups[groupid].Team.Request().PutAsync(team, token), token, 1)); }
private static async Task <TeamsAsyncOperation> SubmitTeamCreateRequestAndWait(Beta.GraphServiceClient client, Beta.Team team, CancellationToken token) { string location = await GraphHelper.ExecuteWithRetryAndRateLimit(async() => { var message = client.Teams.Request().GetHttpRequestMessage(); message.Method = HttpMethod.Post; message.Content = new StringContent(JsonConvert.SerializeObject(team), Encoding.UTF8, "application/json"); return(await AsyncRequestSubmit(client, message, token)); }, token, 1); return(await AsyncRequestWait(client, token, location)); }
public AuthenticationContextClassReferencesOperations(Beta.GraphServiceClient graphServiceClient) { this._graphServiceClient = graphServiceClient; Beta.AuthenticationContextClassReference refn = new Beta.AuthenticationContextClassReference(); }