public async Task <IAzure> GetAzureContextFromManagedIdentityAsync() { IAzure azure; ISubscription subscription; var azureServiceTokenProvider = new AzureServiceTokenProvider(); var accessToken = await azureServiceTokenProvider.GetAccessTokenAsync("https://management.azure.com/").ConfigureAwait(false); var restTokenCredentials = new Microsoft.Rest.TokenCredentials(accessToken); var azCred = new AzureCredentials(restTokenCredentials, null, this.configuration.AadTenantId, AzureEnvironment.AzureGlobalCloud); var rest = RestClient.Configure().WithEnvironment(AzureEnvironment.AzureGlobalCloud).WithCredentials(azCred).Build(); try { this.logger.LogDebug($"Authenticating with Azure"); azure = Azure.Authenticate(rest, this.configuration.AadTenantId).WithSubscription(this.configuration.AzureSubscriptionId); subscription = azure.GetCurrentSubscription(); } catch (Exception ex) { this.logger.LogError($"Failed to authenticate with Auzre: {ex.Message}"); throw; } this.logger.Log(LogLevel.Debug, $"Successfully authenticated with Azure subscription {subscription.DisplayName}"); return(azure); }
public static async Task UploadModule(AuthenticationResult auth, AutomationModule module, AutomationManagementClient automationManagementClient, string resourceGroupName, AutomationAccount account, string storageResourceGroup, string storageSubID, string storageAccount) { // Update the module from powershell gallery if it exists, otherwise upload to storage if (!(await UploadFromGalleryIfExists(module.Name, module.localVersion, automationManagementClient, resourceGroupName, account))) { // Create storage client and set subscription to work against var token = new Microsoft.Rest.TokenCredentials(auth.AccessToken); var storageManagementClient = new Microsoft.Azure.Management.Storage.StorageManagementClient(new Uri(Properties.Settings.Default.appIdURI), token); storageManagementClient.SubscriptionId = storageSubID; // Get storage key and set up connection to storage account var storageKeys = storageManagementClient.StorageAccounts.ListKeys(storageResourceGroup, storageAccount); var storageKey = storageKeys.Keys.FirstOrDefault().Value; var storageConnection = "DefaultEndpointsProtocol=https;AccountName=" + storageAccount + ";AccountKey=" + storageKey; CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(storageConnection); // Zip and upload module to storage account var zipModule = ZipModuleFolder(module.localModulePath, module.Name); var blobClient = cloudStorageAccount.CreateCloudBlobClient(); await UploadModuleToStorageAccount(blobClient, Constants.moduleContainer, zipModule, module.Name.ToLower()); // Get sas token and upload to automation account var SaSURI = await GetSASToken(blobClient, Constants.moduleContainer, module.Name.ToLower()); await UploadModuleToAutomationAccount(module.Name, automationManagementClient, resourceGroupName, account, SaSURI); } }
/// <summary> /// Adds <see cref="IAzure"/> for use in management operations. /// </summary> /// <param name="services">IServiceCollection object.</param> public static void AddAzureFluentManagement(this IServiceCollection services) { services.AddSingleton(sp => { // If we find tenant and subscription in environment variables, configure accordingly if (!string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable(@"AZURE_TENANT_ID")) && !string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable(@"AZURE_SUBSCRIPTION_ID"))) { var tokenCred = sp.GetService <TokenCredential>(); var armToken = tokenCred.GetToken(new TokenRequestContext(scopes: new[] { "https://management.azure.com/.default" }, parentRequestId: null), default).Token; var armCreds = new Microsoft.Rest.TokenCredentials(armToken); var graphToken = tokenCred.GetToken(new TokenRequestContext(scopes: new[] { "https://graph.windows.net/.default" }, parentRequestId: null), default).Token; var graphCreds = new Microsoft.Rest.TokenCredentials(graphToken); var credentials = new AzureCredentials(armCreds, graphCreds, Environment.GetEnvironmentVariable(@"AZURE_TENANT_ID"), AzureEnvironment.AzureGlobalCloud); return(Microsoft.Azure.Management.Fluent.Azure .Authenticate(credentials) .WithSubscription(Environment.GetEnvironmentVariable(@"AZURE_SUBSCRIPTION_ID"))); } else { var credentials = SdkContext.AzureCredentialsFactory .FromSystemAssignedManagedServiceIdentity(MSIResourceType.AppService, AzureEnvironment.AzureGlobalCloud); return(Microsoft.Azure.Management.Fluent.Azure .Authenticate(credentials) .WithDefaultSubscription()); } }); }
public static ColetaApiClient CriaCliente() { var cookie = HttpContext.Current.Request.Cookies.Get(NomeCookie); var token = cookie?.Value ?? "None"; var credenciais = new Microsoft.Rest.TokenCredentials(token, "Bearer"); return(new ColetaApiClient(new Uri(ConfigurationManager.AppSettings["ApiUrl"]), credenciais)); }
public async Task <List <SupportTicketDetails> > GetMsSupportTickets(List <string> subIds) { try { #if DEBUG _logger.LogInformation($"{nameof(GetMsSupportTickets)} started."); Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); #endif if (subIds.IsNullOrEmptyCollection()) { subIds = new(); subIds.Add(_testSubId); } var apiToken = await base.ApiIdentity.GetAccessTokenForUserAsync(Scope); var cr = new Microsoft.Rest.TokenCredentials(apiToken); var msClient = new MicrosoftSupportClient(cr, HttpClientBase, true); Dictionary <string, SupportTicketDetails> dic = new(); foreach (var sub in subIds) { msClient.SubscriptionId = sub; var supTicks = await msClient.SupportTickets.ListAsync(); if (supTicks.HasAnyInCollection()) { foreach (var item in supTicks) { if (!dic.ContainsKey(item.SupportTicketId)) { if (!dic.TryAdd(item.SupportTicketId, item)) { ;//waring failed to add } } else { ;//already in list } } } } #if DEBUG stopWatch.Stop(); _logger.LogInformation($"{nameof(GetMsSupportTickets)} took {stopWatch.Elapsed}"); #endif return(dic.Values.ToList()); } catch (Exception ex) { throw; } }
private async void OKbutton_Click(object sender, RoutedEventArgs e) { try { if (!String.IsNullOrEmpty(subscriptionComboBox.Text) && !String.IsNullOrEmpty(resourceGroupcomboBox.Text) && !String.IsNullOrEmpty(storageAccountcomboBox.Text)) { if (storageAccountcomboBox.SelectedItem == null) { var subObject = (AutomationISEClient.SubscriptionObject)subscriptionComboBox.SelectedItem; var azureARMAuthResult = AuthenticateHelper.RefreshTokenByAuthority(subObject.Authority, Properties.Settings.Default.appIdURI); var authToken = azureARMAuthResult.AccessToken; var token = new Microsoft.Rest.TokenCredentials(authToken); var storageManagementClient = new Microsoft.Azure.Management.Storage.StorageManagementClient(new Uri(Properties.Settings.Default.appIdURI), token); storageManagementClient.SubscriptionId = subObject.SubscriptionId; var result = await storageManagementClient.StorageAccounts.CheckNameAvailabilityAsync(storageAccountcomboBox.Text); if (!(result.NameAvailable.Value)) { var messageBoxResult = System.Windows.Forms.MessageBox.Show( "Storage account name is not available in this subscription. Please choose another name", "Name not available", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning); } else { createNewStorageAccount = true; storageSubID = ((AutomationISEClient.SubscriptionObject)subscriptionComboBox.SelectedItem).SubscriptionId; storageResourceGroupName = resourceGroupcomboBox.Text; storageAccountName = storageAccountcomboBox.Text; region = regionComboBox.Text; this.DialogResult = true; this.Close(); } } else { storageSubID = ((AutomationISEClient.SubscriptionObject)subscriptionComboBox.SelectedItem).SubscriptionId; storageResourceGroupName = resourceGroupcomboBox.SelectedItem.ToString(); storageAccountName = storageAccountcomboBox.Text; this.DialogResult = true; this.Close(); } } } catch (Exception Ex) { throw Ex; } }
/// <summary> /// Creates instance of Power BI client Power BI workspace's used define on @data /// </summary> /// <param name="data"></param> static PowerBIClient CreatePowerBIClient(PowerBIWorkspaceConfig data) { // Create a user password cradentials. var credential = new UserPasswordCredential(data.PowerBIUserName, data.PowerBIPassword); // Authenticate using created credentials var authenticationContext = new AuthenticationContext(Constants.AUTHORITY_URL); var authenticationResult = authenticationContext.AcquireTokenAsync(Constants.RESOURCE_URL, Constants.CLIENT_ID, credential).Result; if (authenticationResult == null) { Console.WriteLine("Error during authentication"); } var tokenCredentials = new Microsoft.Rest.TokenCredentials(authenticationResult.AccessToken, "Bearer"); return(new PowerBIClient(new Uri(Constants.API_URL), tokenCredentials)); }
public async Task <List <CommunicationDetails> > GetMsSupportTicketsCommunication(string submitedSubscription, string supportTicketId, string trackingId) { if (string.IsNullOrWhiteSpace(submitedSubscription)) { throw new ArgumentException($"'{nameof(submitedSubscription)}' cannot be null or whitespace.", nameof(submitedSubscription)); } if (string.IsNullOrWhiteSpace(supportTicketId)) { throw new ArgumentException($"'{nameof(supportTicketId)}' cannot be null or whitespace.", nameof(supportTicketId)); } try { var apiToken = await AuthCsroService.GetAccessTokenForUserAsync(Scope); var cr = new Microsoft.Rest.TokenCredentials(apiToken); var msClient = new MicrosoftSupportClient(cr, HttpClientBase, true); try { msClient.SubscriptionId = submitedSubscription; var coms = await msClient.Communications.ListAsync(supportTicketId); if (coms.HasAnyInCollection()) { return(coms.ToList()); } } catch (Exception ex) { //if case is submited from prog api, it will only work via trackingId var coms = await msClient.Communications.ListAsync(trackingId); if (coms.HasAnyInCollection()) { return(coms.ToList()); } } } catch (Exception ex) { throw; } return(null); }
public async Task <CommunicationDetails> AddMessageToCommunication(string submitedSubscription, string supportTicketId, string subject, string body) { if (string.IsNullOrWhiteSpace(submitedSubscription)) { throw new ArgumentException($"'{nameof(submitedSubscription)}' cannot be null or whitespace.", nameof(submitedSubscription)); } if (string.IsNullOrWhiteSpace(supportTicketId)) { throw new ArgumentException($"'{nameof(supportTicketId)}' cannot be null or whitespace.", nameof(supportTicketId)); } if (string.IsNullOrWhiteSpace(subject)) { throw new ArgumentException($"'{nameof(subject)}' cannot be null or whitespace.", nameof(subject)); } if (string.IsNullOrWhiteSpace(body)) { throw new ArgumentException($"'{nameof(body)}' cannot be null or whitespace.", nameof(body)); } try { var apiToken = await AuthCsroService.GetAccessTokenForUserAsync(Scope); var cr = new Microsoft.Rest.TokenCredentials(apiToken); var msClient = new MicrosoftSupportClient(cr, HttpClientBase, true); msClient.SubscriptionId = submitedSubscription; var email = await AuthCsroService.GetCurrentUserEmail(); string name = null; name = StringHelper.RandomStringDate(20); var crNew = await msClient.Communications.CreateAsync(supportTicketId, name, new CommunicationDetails { Body = body, Sender = email, Subject = subject, }); return(crNew); } catch (Exception ex) { throw; } }
internal static Tuple <string, AzureCredentials, IConfigurationRoot> InitializeApiObjects(Microsoft.Azure.WebJobs.ExecutionContext context) { var tokenProvider = new AzureServiceTokenProvider(); var accessToken = tokenProvider.GetAccessTokenAsync("https://management.azure.com/").Result; client.DefaultRequestHeaders.Add("Accept", "application/json"); client.DefaultRequestHeaders.Add("Authorization", $"Bearer {accessToken}"); var credentials = new Microsoft.Rest.TokenCredentials(accessToken, "Bearer"); var azureCreds = new AzureCredentials(credentials, credentials, credentials.TenantId, AzureEnvironment.AzureGlobalCloud); var config = new ConfigurationBuilder() .SetBasePath(context.FunctionAppDirectory) .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() .Build(); return(new Tuple <string, AzureCredentials, IConfigurationRoot>(accessToken, azureCreds, config)); }
public static async Task <Boolean> CreateStorageAccount(String authority, AutomationManagementClient automationManagementClient, string resourceGroupName, AutomationAccount account, string storageResourceGroup, string storageSubID, string storageAccount, string storageRGLocation) { try { // Get the token for the tenant on this subscription. var cloudtoken = AuthenticateHelper.RefreshTokenByAuthority(authority, Properties.Settings.Default.appIdURI); var subscriptionCreds = new TokenCloudCredentials(storageSubID, cloudtoken.AccessToken); var resourceManagementClient = new ResourceManagementClient(subscriptionCreds, new Uri(Properties.Settings.Default.appIdURI)); // Check if the resource group exists, otherwise create it. var rgExists = resourceManagementClient.ResourceGroups.CheckExistence(storageResourceGroup); if (!(rgExists.Exists)) { var resourceGroup = new ResourceGroup { Location = storageRGLocation }; await resourceManagementClient.ResourceGroups.CreateOrUpdateAsync(storageResourceGroup, resourceGroup); } // Create storage client and set subscription to work against var token = new Microsoft.Rest.TokenCredentials(cloudtoken.AccessToken); var storageManagementClient = new Microsoft.Azure.Management.Storage.StorageManagementClient(new Uri(Properties.Settings.Default.appIdURI), token); storageManagementClient.SubscriptionId = storageSubID; // Use Standard local replication as the sku since it is not critical to keep these modules replicated var storageParams = new StorageAccountCreateParameters() { Location = storageRGLocation, Kind = Kind.Storage, Sku = new Microsoft.Azure.Management.Storage.Models.Sku(SkuName.StandardLRS) }; // Create storage account CancellationToken cancelToken = new CancellationToken(); await storageManagementClient.StorageAccounts.CreateAsync(storageResourceGroup, storageAccount, storageParams, cancelToken); } catch (Exception Ex) { throw Ex; } return(true); }
private async void subscriptionComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { var subObject = (AutomationISEClient.SubscriptionObject)subscriptionComboBox.SelectedItem; var azureARMAuthResult = AuthenticateHelper.RefreshTokenByAuthority(subObject.Authority, Properties.Settings.Default.appIdURI); authority = subObject.Authority; var authToken = azureARMAuthResult.AccessToken; var token = new Microsoft.Rest.TokenCredentials(authToken); var storageManagementClient = new Microsoft.Azure.Management.Storage.StorageManagementClient(new Uri(Properties.Settings.Default.appIdURI), token); storageManagementClient.SubscriptionId = subObject.SubscriptionId; resourceGroupcomboBox.Items.Clear(); try { storageAccounts = storageManagementClient.StorageAccounts.List(); foreach (var storageAccount in storageAccounts) { var startPosition = storageAccount.Id.IndexOf("/resourceGroups/"); var endPosition = storageAccount.Id.IndexOf("/", startPosition + 16); var resourceGroup = storageAccount.Id.Substring(startPosition + 16, endPosition - startPosition - 16); if (resourceGroupcomboBox.Items.IndexOf(resourceGroup) == -1) { resourceGroupcomboBox.Items.Add(resourceGroup); } } var cloudtoken = AuthenticateHelper.RefreshTokenByAuthority(authority, Properties.Settings.Default.appIdURI); var subscriptionCreds = new TokenCloudCredentials(((AutomationISEClient.SubscriptionObject)subscriptionComboBox.SelectedItem).SubscriptionId, cloudtoken.AccessToken); var resourceManagementClient = new Microsoft.Azure.Subscriptions.SubscriptionClient(subscriptionCreds, new Uri(Properties.Settings.Default.appIdURI)); CancellationToken cancelToken = new CancellationToken(); var subscriptionRegions = await resourceManagementClient.Subscriptions.ListLocationsAsync(((AutomationISEClient.SubscriptionObject)subscriptionComboBox.SelectedItem).SubscriptionId, cancelToken); regionComboBox.ItemsSource = subscriptionRegions.Locations; regionComboBox.DisplayMemberPath = "Name"; } catch (Exception Ex) { throw Ex; } }
private static string InitializeToken() { var token = GetToken(); var creds = new Microsoft.Rest.TokenCredentials(token); s_netclient = new NetworkManagementClient(creds) { SubscriptionId = Config.Current.subscription_id }; s_computeClient = new ComputeManagementClient(creds) { SubscriptionId = Config.Current.subscription_id }; return token; }
public async Task <RefundSupportTicket> CreateSupportTicket(ServiceIssue serviceIssue) { RefundSupportTicket result = new(); try { #if DEBUG _logger.LogInformation($"{nameof(CreateSupportTicket)} started."); Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); #endif var apiToken = await base.ApiIdentity.GetAccessTokenForUserAsync(Scope); var cr = new Microsoft.Rest.TokenCredentials(apiToken); var msClient = new MicrosoftSupportClient(cr, HttpClientBase, true); //test msClient.SubscriptionId = _testSubId; // can be only on sub var defTicket = await msClient.SupportTickets.GetAsync(_testSupportTicketId); //var coms = await msClient.Communications.ListAsync(SupportTicketId); var subIds = serviceIssue.ImpactedSubscriptions.GetSubcriptionIdsFromTextExt(); if (subIds.IsNullOrEmptyCollection()) { return(null); //error } foreach (var subId in subIds) { try { result = new(); result.RequiredAction = null; result.SubmitedSubscription = subId; result.ServiceIssueId = serviceIssue.Id; result.TrackingId = serviceIssue.TrackingId; var userEmail = await ApiIdentity.GetCurrentUserEmail(); if (userEmail.HasValueExt() && userEmail != defTicket.ContactDetails.PrimaryEmailAddress) { defTicket.ContactDetails.AdditionalEmailAddresses = new List <string> { userEmail } } ; StringBuilder sb = new StringBuilder(DESCRIPTION_CONTS); sb.Replace("Tue, 21 Sep 2021, 12:00 am GMT+2", serviceIssue.ImpactStartTime.ToString("R")); sb.Replace("ImpactMitigationTime", serviceIssue.ImpactMitigationTime.ToString("R")); sb.Replace("LastUpdateTime", serviceIssue.LastUpdateTime.ToString("R")); sb.Replace("TitlePlaceholder", serviceIssue.Title); sb.Replace("1VWB-V9G", serviceIssue.TrackingId); sb.Replace("ImpactedRegions", serviceIssue.ImpactedRegions); sb.Replace("ImpactedServices", serviceIssue.ImpactedServices); sb.Replace("Status", serviceIssue.Status); #region ImpactedSubscriptions, pupulate with entire list, with ids only or split and store to RequiredAction StringBuilder sbSubs = new(); var subPairs = serviceIssue.ImpactedSubscriptions.Split(",").ToList(); if (subPairs.Count > 1) { sbSubs.AppendLine(); //if more then 1, place subs into new line } subPairs.Where(a => a.Length > 1).ToList().ForEach(a => sbSubs.AppendLine(a.TrimStart().TrimEnd())); var desLenght = sb.Length + sbSubs.Length; const int max = 5000; if (desLenght < max) //limit for des is 5000 char { sb.Replace(nameof(serviceIssue.ImpactedSubscriptions), sbSubs.ToString()); } else { //try with ids only, ignore sub names sbSubs.Clear(); subIds.ForEach(a => sbSubs.AppendLine(a)); desLenght = sb.Length + sbSubs.Length; if (desLenght < max) //limit for des { sb.Replace(nameof(serviceIssue.ImpactedSubscriptions), sbSubs.ToString()); } else { //real problem. Save into db filed RequiredAction sbSubs.Clear(); StringBuilder sbRequiredAction = new("[Action]Additional subscriptions not included in tickets to be reported, because of 5000 limit for description in api:"); subPairs = serviceIssue.ImpactedSubscriptions.Split(",").ToList(); foreach (var item in subPairs) { if (item.Length > 1) { desLenght = sb.Length + sbSubs.Length + 400; //some offset if (desLenght < max) //limit for des is 5000 char { sbSubs.AppendLine(item.TrimStart().TrimEnd()); } else { sbRequiredAction.AppendLine(item.TrimStart().TrimEnd()); } } } sb.Replace(nameof(serviceIssue.ImpactedSubscriptions), sbSubs.ToString()); result.RequiredAction = sbRequiredAction.ToString(); } } #endregion var desc = sb.ToString(); SupportTicketDetails supportTicketDetails = new SupportTicketDetails(desc, defTicket.ProblemClassificationId, "minimal" , defTicket.ContactDetails, $"Refund for {nameof(serviceIssue.TrackingId)}#{serviceIssue.TrackingId}", defTicket.ServiceId); supportTicketDetails.ProblemStartTime = serviceIssue.ImpactStartTime; supportTicketDetails.Validate(); msClient.SubscriptionId = subId; //return result; //only for test, to feed db with existing ticket var supTicksCreated = await msClient.SupportTickets.CreateAsync(serviceIssue.TrackingId, supportTicketDetails); if (supTicksCreated != null) { result.SupportTicketId = supTicksCreated.SupportTicketId; result.Description = supTicksCreated.Description; result.Title = supTicksCreated.Title; //result.CreatedBy = userEmail; ////overide created time with ticket time //refund.CreatedAt = supTicksCreated.CreatedDate; result.ServiceIssue = serviceIssue; break; } } catch (Exception ex) { //_logger.LogWarning($"{nameof(CreateSupportTicket)} failed for {serviceIssue.TrackingId} and sub {subId} with: {ex}"); throw; } } #if DEBUG stopWatch.Stop(); _logger.LogInformation($"{nameof(CreateSupportTicket)} took {stopWatch.Elapsed}"); #endif return(result.SupportTicketId.HasValueExt() ? result : null); } catch (Exception ex) { throw; } }
public async Task <RefundSupportTicket> CreateSupportTicket(ServiceIssue serviceIssue, string subId, List <string> trackingIds) { RefundSupportTicket result = new(); try { #if DEBUG _logger.LogInformation($"{nameof(CreateSupportTicket)} started."); Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); #endif var apiToken = await base.ApiIdentity.GetAccessTokenForUserAsync(Scope); var cr = new Microsoft.Rest.TokenCredentials(apiToken); var msClient = new MicrosoftSupportClient(cr, HttpClientBase, true); //test msClient.SubscriptionId = _testSubId; // can be only on sub var defTicket = await msClient.SupportTickets.GetAsync(_testSupportTicketId); var subIds = serviceIssue.ImpactedSubscriptions.GetSubcriptionIdsFromTextExt(); if (subIds.IsNullOrEmptyCollection()) { return(null); //error } StringBuilder sbTrIds = new(); trackingIds.ForEach(s => sbTrIds.Append($"{s}, ")); try { result = new(); result.RequiredAction = serviceIssue.TrackingId; result.SubmitedSubscription = subId; result.ServiceIssueId = serviceIssue.Id; result.TrackingId = serviceIssue.TrackingId; var userEmail = await ApiIdentity.GetCurrentUserEmail(); if (userEmail.HasValueExt() && userEmail != defTicket.ContactDetails.PrimaryEmailAddress) { defTicket.ContactDetails.AdditionalEmailAddresses = new List <string> { userEmail } } ; StringBuilder sb = new StringBuilder(DESCRIPTION_SINGLE_CONTS); sb.Replace("1VWB-V9G", sbTrIds.ToString()); var desc = sb.ToString(); SupportTicketDetails supportTicketDetails = new SupportTicketDetails(desc, defTicket.ProblemClassificationId, "minimal" , defTicket.ContactDetails, $"Refund for {nameof(serviceIssue.TrackingId)}#{serviceIssue.TrackingId}", defTicket.ServiceId); supportTicketDetails.ProblemStartTime = serviceIssue.ImpactStartTime; supportTicketDetails.Validate(); msClient.SubscriptionId = subId; //return result; //only for test, to feed db with existing ticket /*var supTicksCreated = await msClient.SupportTickets.CreateAsync(serviceIssue.TrackingId, supportTicketDetails)*/; var supTicksCreated = await msClient.SupportTickets.CreateAsync(serviceIssue.TrackingId, supportTicketDetails); if (supTicksCreated != null) { result.SupportTicketId = supTicksCreated.SupportTicketId; result.Description = supTicksCreated.Description; result.Title = supTicksCreated.Title; result.ServiceIssue = serviceIssue; } } catch (Exception ex) { //_logger.LogWarning($"{nameof(CreateSupportTicket)} failed for {serviceIssue.TrackingId} and sub {subId} with: {ex}"); throw; } #if DEBUG stopWatch.Stop(); _logger.LogInformation($"{nameof(CreateSupportTicket)} took {stopWatch.Elapsed}"); #endif return(result.SupportTicketId.HasValueExt() ? result : null); } catch (Exception ex) { throw; } }
public async Task <List <SupportTicketDetails> > GetMsSupportTicketsParallel(List <string> subIds, string primaryEmail = null) { try { #if DEBUG _logger.LogInformation($"{nameof(GetMsSupportTickets)} started."); Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); #endif if (subIds.IsNullOrEmptyCollection()) { subIds = new(); subIds.Add(_testSubId); } var apiToken = await AuthCsroService.GetAccessTokenForUserAsync(Scope); var cr = new Microsoft.Rest.TokenCredentials(apiToken); var msClient = new MicrosoftSupportClient(cr, HttpClientBase, true); Dictionary <string, MicrosoftSupportClient> dicClients = new(); foreach (var id in subIds) { if (!dicClients.ContainsKey(id)) { var cl = new MicrosoftSupportClient(cr, HttpClientBase, true) { SubscriptionId = id }; dicClients.Add(id, cl); } } ConcurrentDictionary <string, SupportTicketDetails> conDic = new(); Parallel.ForEach(subIds, (sub) => { try { //msClient.SubscriptionId = sub; //var t = msClient.SupportTickets.ListAsync(); var t = dicClients[sub].SupportTickets.ListAsync(); t.Wait(); var supTicks = t.Result; if (supTicks.HasAnyInCollection()) { foreach (var item in supTicks) { if (primaryEmail.HasValueExt() && item?.ContactDetails?.PrimaryEmailAddress != primaryEmail) { continue; } if (!conDic.ContainsKey(item.SupportTicketId)) { conDic.AddOrUpdate(item.SupportTicketId, item, (key, old) => item); } } } } catch (Exception ex) { _logger.LogErrorCsro(ex, $"{nameof(GetMsSupportTicketsParallel)} for sub {sub}"); } }); //subIds.AsParallel().ForAll(async sub => //{ // msClient.SubscriptionId = sub; // var supTicks = await msClient.SupportTickets.ListAsync(); // if (supTicks.HasAnyInCollection()) // { // foreach (var item in supTicks) // { // if (!conDic.ContainsKey(item.SupportTicketId)) // conDic.AddOrUpdate(item.SupportTicketId, item, (key, old) => item); // else // ;//already in list // } // } //}); #if DEBUG stopWatch.Stop(); _logger.LogInformation($"{nameof(GetMsSupportTickets)} took {stopWatch.Elapsed}"); #endif return(conDic.Values.ToList()); } catch (Exception ex) { throw; } }
public async Task <ActionResult> Delete(string id) { // ====================================================================== // Delete document from Cosmos DB // ====================================================================== var videoRepo = VideoRepositoryFactory.Create(); var video = await videoRepo.Get(id); await videoRepo.Delete(id); // ====================================================================== // Delete files from Blob Storage // ====================================================================== // Load Connection String to Azure Storage Account var videoConnString = ConfigurationManager.ConnectionStrings["videostorage"].ConnectionString; if (string.IsNullOrWhiteSpace(videoConnString)) { throw new Exception("The 'videostorage' Connection String is NOT set"); } // Get reference to the Blob Container to upload to var storageAccount = CloudStorageAccount.Parse(videoConnString); var blobClient = storageAccount.CreateCloudBlobClient(); // Get reference to 'video' container var videoContainer = blobClient.GetContainerReference("video"); await videoContainer.CreateIfNotExistsAsync(); // Delete Video file from Blob Storage var videoBlob = videoContainer.GetBlockBlobReference(id); await videoBlob.DeleteAsync(); // ====================================================================== // Delete video from Video Indexer service // ====================================================================== var videoIndexerLocation = "trial"; var videoIndexerTokenCredentials = new Microsoft.Rest.TokenCredentials( ConfigurationManager.AppSettings["VideoIndexerAPI_Key"] ); var videoIndexerAuthClient = new VideoIndexer.Authorization.AuthorizationClient(videoIndexerTokenCredentials); // Get Video Indexer Account Id var accountsResponse = await videoIndexerAuthClient.GetAccountsWithHttpMessagesAsync(videoIndexerLocation); dynamic accounts = Newtonsoft.Json.Linq.JArray.Parse(await accountsResponse.Response.Content.ReadAsStringAsync()); var videoIndexerAccountId = accounts[0].id as string; // Get Video Indexer Access Token var accountAccessTokenResponse = await videoIndexerAuthClient.GetAccountAccessTokenWithHttpMessagesAsync(videoIndexerLocation, videoIndexerAccountId, true); var accountAccessToken = Newtonsoft.Json.JsonConvert.DeserializeObject <string>(await accountAccessTokenResponse.Response.Content.ReadAsStringAsync()); // Delete Video from Video Indexer Account var videoIndexerClient = new VideoIndexer.Operations.OperationsClient(videoIndexerTokenCredentials); var response = await videoIndexerClient.DeleteVideoWithHttpMessagesAsync(videoIndexerLocation, videoIndexerAccountId, video.VideoId, accountAccessToken); return(RedirectToAction("Index")); }