/// <inheritdoc/>
        public async Task InstallAppForUserAsync(string appId, string userId)
        {
            if (string.IsNullOrWhiteSpace(appId))
            {
                throw new ArgumentNullException(nameof(appId));
            }

            if (string.IsNullOrWhiteSpace(userId))
            {
                throw new ArgumentNullException(nameof(userId));
            }

            var userScopeTeamsAppInstallation = new UserScopeTeamsAppInstallation
            {
                AdditionalData = new Dictionary <string, object>()
                {
                    { "*****@*****.**", $"{GraphConstants.BetaBaseUrl}/appCatalogs/teamsApps/{appId}" },
                },
            };

            var retryPolicy = PollyPolicy.GetGraphRetryPolicy(GraphConstants.MaxRetry);
            await retryPolicy.ExecuteAsync(async() =>
                                           await this.graphServiceClient.Users[userId]
                                           .Teamwork
                                           .InstalledApps
                                           .Request()
                                           .WithMaxRetry(GraphConstants.MaxRetry)
                                           .AddAsync(userScopeTeamsAppInstallation));
        }
        public async Task AppinstallationforPersonal(string Userid, string MicrosoftTenantId, string MicrosoftAppId, string MicrosoftAppPassword, string MicrosoftTeamAppid)
        {
            string Access_Token = await GetToken(MicrosoftTenantId, MicrosoftAppId, MicrosoftAppPassword);

            GraphServiceClient graphClient = GetAuthenticatedClient(Access_Token);

            try
            {
                var userScopeTeamsAppInstallation = new UserScopeTeamsAppInstallation
                {
                    AdditionalData = new Dictionary <string, object>()
                    {
                        { "*****@*****.**", "https://graph.microsoft.com/v1.0/appCatalogs/teamsApps/" + MicrosoftTeamAppid }
                    }
                };
                await graphClient.Users[Userid].Teamwork.InstalledApps
                .Request()
                .AddAsync(userScopeTeamsAppInstallation);
            }
            catch (Microsoft.Graph.ServiceException ex)
            {
                // This is where app is already installed but we don't have conversation reference.
                if (ex.Error.Code == "Conflict")
                {
                    await TriggerConversationUpdate(Userid, MicrosoftTenantId, MicrosoftAppId, MicrosoftAppPassword, MicrosoftTeamAppid);
                }
                else
                {
                    throw ex;
                }
            }
        }
        /// <inheritdoc/>
        public async Task InstallAppForUserAsync(string appId, string userId)
        {
            if (string.IsNullOrWhiteSpace(appId))
            {
                throw new ArgumentNullException(nameof(appId));
            }

            if (string.IsNullOrWhiteSpace(userId))
            {
                throw new ArgumentNullException(nameof(userId));
            }

            var userScopeTeamsAppInstallation = new UserScopeTeamsAppInstallation
            {
                AdditionalData = new Dictionary <string, object>()
                {
                    { "*****@*****.**", $"{GraphConstants.BetaBaseUrl}/appCatalogs/teamsApps/{appId}" },
                },
            };

            // Skip Guest users.
            var user = await this.graphServiceClient.Users[userId].Request().GetAsync();

            if (!string.Equals(user.UserType, "Guest", StringComparison.OrdinalIgnoreCase) &&
                !user.UserPrincipalName.ToLower().Contains("#ext#"))
            {
                await this.graphServiceClient.Users[userId]
                .Teamwork
                .InstalledApps
                .Request()
                .WithMaxRetry(GraphConstants.MaxRetry)
                .AddAsync(userScopeTeamsAppInstallation);
            }
        }
        /// <summary>
        /// Install application in user Group chat
        /// </summary>
        /// <param name="GroupId">Id of group.</param>
        public async Task AppinstallationforGroupAsync(string GroupId)
        {
            string access_Token = await GetToken();

            GraphServiceClient graphClient = GetAuthenticatedClient(access_Token);

            try
            {
                var appInternalId = await GetApplicationInternalId(graphClient);

                var userScopeTeamsAppInstallation = new UserScopeTeamsAppInstallation
                {
                    AdditionalData = new Dictionary <string, object>()
                    {
                        { "*****@*****.**", $"https://graph.microsoft.com/v1.0/appCatalogs/teamsApps/{appInternalId}" }
                    }
                };

                await graphClient.Chats[GroupId].InstalledApps
                .Request()
                .AddAsync(userScopeTeamsAppInstallation);
            }
            catch (Microsoft.Graph.ServiceException ex)
            {
                throw ex;
            }
        }
Beispiel #5
0
        /// <summary>
        /// Update the navigation property installedApps in users
        /// <param name="body"></param>
        /// <param name="requestConfiguration">Configuration for the request such as headers, query parameters, and middleware options.</param>
        /// </summary>
        public RequestInformation CreatePatchRequestInformation(UserScopeTeamsAppInstallation body, Action <UserScopeTeamsAppInstallationItemRequestBuilderPatchRequestConfiguration> requestConfiguration = default)
        {
            _ = body ?? throw new ArgumentNullException(nameof(body));
            var requestInfo = new RequestInformation {
                HttpMethod     = Method.PATCH,
                UrlTemplate    = UrlTemplate,
                PathParameters = PathParameters,
            };

            requestInfo.SetContentFromParsable(RequestAdapter, "application/json", body);
            if (requestConfiguration != null)
            {
                var requestConfig = new UserScopeTeamsAppInstallationItemRequestBuilderPatchRequestConfiguration();
                requestConfiguration.Invoke(requestConfig);
                requestInfo.AddRequestOptions(requestConfig.Options);
                requestInfo.AddHeaders(requestConfig.Headers);
            }
            return(requestInfo);
        }
Beispiel #6
0
        public async Task <ActionResult> SendNotificationToOrganisation(BroadcastInfo taskInfo)
        {
            try
            {
                var currentTaskList           = new List <BroadcastInfo>();
                List <BroadcastInfo> taskList = new List <BroadcastInfo>();
                _taskList.TryGetValue("taskList", out currentTaskList);

                taskInfo.taskId = Guid.NewGuid();

                if (currentTaskList == null)
                {
                    taskList.Add(taskInfo);
                    _taskList.AddOrUpdate("taskList", taskList, (key, newValue) => taskList);
                    ViewBag.TaskList = taskList;
                }
                else
                {
                    currentTaskList.Add(taskInfo);
                    _taskList.AddOrUpdate("taskList", currentTaskList, (key, newValue) => currentTaskList);
                    ViewBag.TaskList = currentTaskList;
                }

                // Graph client for user.
                var graphClient = SimpleGraphClient.GetGraphClient(taskInfo.access_token);

                // Graph client for app.
                var graphClientApp = SimpleGraphClient.GetGraphClientforApp(_configuration["AzureAd:MicrosoftAppId"], _configuration["AzureAd:MicrosoftAppPassword"], _configuration["AzureAd:TenantId"]);
                var usersList      = await graphClient.Users
                                     .Request()
                                     .GetAsync();

                var installedAppsForCurrentUser = await graphClient.Users[taskInfo.userId].Teamwork.InstalledApps
                                                  .Request()
                                                  .Expand("teamsAppDefinition")
                                                  .GetAsync();

                // Get app id using app display name.
                var appId = installedAppsForCurrentUser.Where(id => id.TeamsAppDefinition.DisplayName == "Activity feed broadcast").Select(x => x.TeamsAppDefinition.TeamsAppId);

                Parallel.ForEach(usersList, async users =>
                {
                    var installedApp = await graphClient.Users[users.Id].Teamwork.InstalledApps
                                       .Request()
                                       .Expand("teamsApp")
                                       .GetAsync();

                    var response       = new HttpResponseMessage();
                    var installationId = installedApp.Where(id => id.TeamsApp.DisplayName == "Activity feed broadcast").Select(x => x.TeamsApp.Id);
                    var client         = new HttpClient();
                    var url            = "https://teams.microsoft.com/l/entity/" + appId.ToList()[0] + "/broadcast?context={\"subEntityId\":\"" + taskInfo.taskId + "\"}";
                    var postData       = new
                    {
                        topic = new TeamworkActivityTopic()
                        {
                            Source = TeamworkActivityTopicSource.Text,
                            Value  = $"{taskInfo.title}",
                            WebUrl = url
                        },
                        activityType = "approvalRequired",
                        previewText  = new ItemBody
                        {
                            Content = $"Message By:"
                        },
                        templateParameters = new List <Microsoft.Graph.KeyValuePair>()
                        {
                            new Microsoft.Graph.KeyValuePair
                            {
                                Name  = "approvalTaskId",
                                Value = taskInfo.title
                            }
                        }
                    };

                    var data = new StringContent(JsonConvert.SerializeObject(postData), Encoding.UTF8, "application/json");

                    if (installationId.ToList().Count == 0)
                    {
                        var userScopeTeamsAppInstallation = new UserScopeTeamsAppInstallation
                        {
                            AdditionalData = new Dictionary <string, object>()
                            {
                                { "*****@*****.**", "https://graph.microsoft.com/v1.0/appCatalogs/teamsApps/" + appId.ToList()[0] }
                            }
                        };

                        await graphClient.Users[users.Id].Teamwork.InstalledApps
                        .Request()
                        .AddAsync(userScopeTeamsAppInstallation);

                        client.DefaultRequestHeaders.Authorization =
                            new AuthenticationHeaderValue("Bearer", taskInfo.access_token);
                        await client.PostAsync($"https://graph.microsoft.com/v1.0/users/{users.Id}/teamwork/sendActivityNotification", data);
                    }
                    else
                    {
                        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", taskInfo.access_token);
                        response = await client.PostAsync($"https://graph.microsoft.com/v1.0/users/{users.Id}/teamwork/sendActivityNotification", data);
                    }

                    if (response.StatusCode == HttpStatusCode.TooManyRequests)
                    {
                        await Policy
                        .Handle <HttpRequestException>()
                        .OrResult <HttpResponseMessage>(response => response.StatusCode == HttpStatusCode.TooManyRequests ||
                                                        response.StatusCode == HttpStatusCode.ServiceUnavailable)
                        .WaitAndRetryAsync(3,
                                           sleepDurationProvider: (retryCount, response, context) =>
                        {
                            var delay = TimeSpan.FromSeconds(0);
                            // if an exception was thrown, this will be null
                            if (response.Result != null)
                            {
                                if (!response.Result.Headers.TryGetValues("Retry-After", out IEnumerable <string> values))
                                {
                                    return(delay);
                                }

                                if (int.TryParse(values.First(), out int delayInSeconds))
                                {
                                    delay = TimeSpan.FromSeconds(delayInSeconds);
                                }
                            }
                            else
                            {
                                var exponentialBackoff = Math.Pow(2, retryCount);
                                var delayInSeconds     = exponentialBackoff * 10000;
                                delay = TimeSpan.FromMilliseconds(delayInSeconds);
                            }

                            return(delay);
                        },
                                           onRetryAsync: async(response, timespan, retryCount, context) =>
                        {
                        }
                                           ).ExecuteAsync(async() =>
                        {
                            return(await client.PostAsync($"https://graph.microsoft.com/v1.0/users/{users.Id}/teamwork/sendActivityNotification", data));
                        }
                                                          );
                    }
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

            return(View("Index"));
        }