// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddSingleton <IAzureConfiguration, AzureConfiguration>(provider => { var azureConfiguration = new AzureConfiguration(); Configuration.Bind("AzureConfiguration", azureConfiguration); return(azureConfiguration); }); services.AddSingleton <PresentationAddedQueue>(provider => { var azure = provider.GetService <IAzureConfiguration>(); return(new PresentationAddedQueue(azure.AzureWebJobsStorage)); }); services.AddSingleton <PresentationScheduleAddedQueue>(provider => { var azure = provider.GetService <IAzureConfiguration>(); return(new PresentationScheduleAddedQueue(azure.AzureWebJobsStorage)); }); services.AddControllers() .AddNewtonsoftJson(o => { o.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; }); services.AddDbContext <PresentationContext>(options => options.UseSqlServer(Configuration.GetConnectionString("PresentationsSqlDb"))); //options.UseSqlite(Configuration.GetConnectionString("PresentationsDb"))); services.AddAutoMapper(typeof(PresentationRepositoryStorage)); services.AddTransient <IPresentationManager, PresentationManager>(); services.AddTransient <IPresentationRepository, PresentationRepository>(); services.AddTransient <IPresentationRepositoryStorage, PresentationRepositoryStorage>(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Version = "v1", Title = "My Event Presentations API", Description = "The API for My Event Presentations", TermsOfService = new Uri("https://www.myeventpresentations.com/terms"), Contact = new OpenApiContact { Name = "Joseph Guadagno", Email = "*****@*****.**", Url = new Uri("https://www.josephguadagno.net") }, License = new OpenApiLicense { Name = "Use under LICX", Url = new Uri("https://www.myeventpresentations.com/license"), } }); // Set the comments path for the Swagger JSON and UI. var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); }); }
public GraphServiceProvider(AzureConfiguration azureConfiguration) { _urlVersion = azureConfiguration.UrlVersion; _baseUrl = azureConfiguration.BaseUrl; _notificationUri = azureConfiguration.NotificationUri; _azureConfiguration = azureConfiguration; }
public VideoIndexerController(AzureConfiguration azureConfiguration, IHttpClientFactory httpClientFactory, IMemoryCache memoryCache) { this.AzureConfiguration = azureConfiguration; this.HttpClientFactory = httpClientFactory; this.MemoryCache = memoryCache; }
// Get an authenticated Microsoft Graph Service client. public static GraphServiceClient GetAuthenticatedClient(AzureConfiguration azureConfiguration, string jwtToken) { try { graphClient = new GraphServiceClient( new DelegateAuthenticationProvider( async(requestMessage) => { SampleAuthProvider sampleAuthProvider = new SampleAuthProvider(); var accessToken = await sampleAuthProvider.GetUserAccessTokenAsync(azureConfiguration, jwtToken); // Append the access token to the request. requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken); // This header has been added to identify our sample in the Microsoft Graph service. If extracting this code for your project please remove. requestMessage.Headers.Add("SampleID", "aspnet-connect-sample"); //}); })); return(graphClient); } catch { throw; } }
private static void AddConfigurationServices(IServiceCollection services) { services.AddSingleton(configuration); services.AddSingleton <TeamsConfiguration>(ctx => { var t = new TeamsConfiguration(); configuration.Bind("Teams", t); return(t); }); services.AddSingleton <BackupOptions>(ctx => { var t = new BackupOptions(); configuration.Bind("Backup", t); return(t); }); services.AddSingleton <MySqlOptions>(ctx => { var t = new MySqlOptions(); configuration.Bind("MySql", t); return(t); }); services.AddSingleton <RetentionOptions>(ctx => { var t = new RetentionOptions(); configuration.Bind("Retention", t); return(t); }); services.AddSingleton <SlackConfiguration>(ctx => { var t = new SlackConfiguration(); configuration.Bind("Slack", t); return(t); }); services.AddSingleton <AzureConfiguration>(ctx => { var t = new AzureConfiguration(); configuration.Bind("Azure", t); return(t); }); services.AddSingleton <S3Configuration>(ctx => { var t = new S3Configuration(); configuration.Bind("S3", t); return(t); }); services.AddSingleton <PhysicalConfiguration>(ctx => { var t = new PhysicalConfiguration(); configuration.Bind("Physical", t); return(t); }); }
public IndexedPersonsService(AzureConfiguration azureConfiguration, IHttpClientFactory httpClientFactory, IMemoryCache memoryCache) : base() { this.AzureConfiguration = azureConfiguration; this.HttpClientFactory = httpClientFactory; this.MemoryCache = memoryCache; }
public async Task SetConfig(AzureConfiguration ac) { AddOrUpdateAppSetting <string>("endpoint", ac.ApiAddress); AddOrUpdateAppSetting <string>("key", ac.KeyOcr); AddOrUpdateAppSetting <string>("language", ac.Language); AddOrUpdateAppSetting <string>("keyspeech", ac.KeySpeech); AddOrUpdateAppSetting <string>("endpointspeech", ac.AzureRegion); await Task.CompletedTask; }
public AzureConfiguration GetConfig() { AzureConfiguration ac = new AzureConfiguration(); ac.ApiAddress = AppSettingsManager.Settings["apiaddress"]; ac.KeyOcr = AppSettingsManager.Settings["key"]; ac.Language = AppSettingsManager.Settings["language"]; ac.KeySpeech = AppSettingsManager.Settings["keyspeech"]; ac.AzureRegion = AppSettingsManager.Settings["region"]; return(ac); }
public static CloudTable ConnectToTable(string table) { if (AzureConfiguration.Configuration == null) { AzureConfiguration.GetConfiguration(); } var connectionString = AzureConfiguration.Configuration[Constants.AzureStorageConnectionString]; var cloudStorageAccount = CloudStorageAccount.Parse(connectionString); var cloudTableClient = cloudStorageAccount.CreateCloudTableClient(); return(cloudTableClient.GetTableReference(table)); }
public static void Main(string[] args) { DataDirectory.ConfigureDataDirectory(); var config = new JobHostConfiguration(); config.DashboardConnectionString = config.StorageConnectionString = AzureConfiguration.GetStorageConnectionString(); config.Queues.BatchSize = 8; config.Queues.MaxDequeueCount = 10; config.Queues.MaxPollingInterval = TimeSpan.FromSeconds(10); var host = new JobHost(config); host.RunAndBlock(); }
/// <summary> /// Initializes a new instance of the <see cref="GraphService" /> class /// </summary> public GraphService(AzureConfiguration azureConfig, string jwtToken) { _graphClient = SDKHelper.GetAuthenticatedClient(azureConfig, jwtToken); AccessToken = SDKHelper.GetAccessToken(azureConfig, jwtToken); JWTToken = jwtToken; if (_graphClient != null) { GraphUrlVersion = azureConfig.UrlVersion; NotificationUri = azureConfig.NotificationUri; GraphUrl = azureConfig.BaseUrl + GraphUrlVersion; _graphClient.BaseUrl = GraphUrl; } }
private static async Task CreateStorageAccountAsync(string storageAccountName, HttpClient client, ConfigurationFile config) { string template = $"{{\"sku\": {{ \"name\": \"Standard_LRS\" }}, \"kind\": \"StorageV2\", \"location\": \"eastus\", \"properties\": {{ \"staticWebsite\": {{ \"enabled\": true}} }} }}"; HttpResponseMessage result = await client.PutAsync($"/subscriptions/{config.SubscriptionId}/resourcegroups/{config.ResourceGroup}/providers/Microsoft.Storage/storageAccounts/{storageAccountName}?api-version=2018-02-01", new StringContent(template, Encoding.UTF8, "application/json")); string requestContent = await result.RequestMessage.Content.ReadAsStringAsync(); HttpRequestMessage request = result.RequestMessage; string content = await result.Content.ReadAsStringAsync(); if (result.IsSuccessStatusCode) { await AzureConfiguration.SetDefaultStorageAccountAsync(storageAccountName); } }
private static async Task <Subscription> SelectSubcriptionAsync(HttpClient client) { HttpResponseMessage response = await client.GetAsync("https://management.azure.com/subscriptions?api-version=2014-04-01"); Subscriptions subscriptions = await response.Content.ReadAsAsync <Subscriptions>(); Console.Clear(); Console.WriteLine("Please choose the subscription into which the resources will be deployed."); List <Subscription> activeSubscription = subscriptions.value.Where(x => x.state == "Enabled").ToList(); Subscription selectedSubscription = CliPicker.SelectFromList(activeSubscription, x => $"{x.displayName} ({x.subscriptionId})"); await AzureConfiguration.SetDefaultSubscriptionAsync(selectedSubscription); return(selectedSubscription); }
private static async Task CreateResourceGroupAsync(string rgName, HttpClient client, ConfigurationFile config) { string defaultLocation = "eastus"; string template = $"{{\"location\": \"{defaultLocation}\"}}"; HttpResponseMessage result = await client.PutAsync($"/subscriptions/{config.SubscriptionId}/resourcegroups/{rgName}?api-version=2018-05-01", new StringContent(template, Encoding.UTF8, "application/json")); string requestContent = await result.RequestMessage.Content.ReadAsStringAsync(); HttpRequestMessage request = result.RequestMessage; string content = await result.Content.ReadAsStringAsync(); if (result.IsSuccessStatusCode) { await AzureConfiguration.SetDefaultResourceGroupAsync(rgName); } }
public static void Main(string[] args) { // This is just a sanity check to ensure we run as 64 bit when processing images. Console.WriteLine("Thumbnails WebJob running as {0} bit process.", Environment.Is64BitProcess ? "64" : "32"); Trace.TraceInformation("Thumbnails WebJob running as {0} bit process.", Environment.Is64BitProcess ? "64" : "32"); DataDirectory.ConfigureDataDirectory(); var config = new JobHostConfiguration(); config.DashboardConnectionString = config.StorageConnectionString = AzureConfiguration.GetStorageConnectionString(); config.Queues.BatchSize = 8; config.Queues.MaxDequeueCount = 3; config.Queues.MaxPollingInterval = TimeSpan.FromSeconds(2); var host = new JobHost(config); host.RunAndBlock(); }
public AzureConfiguration GetConfig() { var configuration = new ConfigurationBuilder().AddJsonFile("config.json").Build(); if (configuration != null) { AzureConfiguration ac = new AzureConfiguration(); ac.ApiAddress = configuration["apiaddress"]; ac.KeyOcr = configuration["key"]; ac.Language = configuration["language"]; ac.KeySpeech = configuration["keyspeech"]; ac.AzureRegion = configuration["region"]; return(ac); } else { throw new Exception("No configuration file or permission denied"); } }
// Gets an access token. First tries to get the token from the token cache. public async Task <string> GetUserAccessTokenAsync(AzureConfiguration azureConfiguration, string jwtToken) { try { ConfidentialClientApplication cca = new ConfidentialClientApplication( azureConfiguration.ClientId, azureConfiguration.RedirectUri, new ClientCredential(azureConfiguration.ClientSecret), null, null); AuthenticationResult result = await cca.AcquireTokenOnBehalfOfAsync(azureConfiguration.Scope.Split(" "), new UserAssertion(jwtToken)); return(result.AccessToken); } catch (Exception exception) { Trace.WriteLine(exception.Message); return(null); } }
public ConfigPage() { InitializeComponent(); //string speechKey = AppSettingsManager.Settings["keyspeech"]; //string endpoint = AppSettingsManager.Settings["endpointspeech"]; _irc = DependencyService.Get <IRecognizerConfiguration>(); if (_irc == null) { UserDialogs.Instance.Alert("Recognizer configuration is null", "Can't get Recognizer Configuration"); } else { if (Settings.NoSetupDefined) { _ac = _irc.GetConfig(); if (_ac != null) { txtKeyOcr.Text = _ac.KeyOcr; txtEndpointAzure.Text = _ac.ApiAddress; txtKeySpeech.Text = _ac.KeySpeech; txtLanguage.Text = _ac.Language; txtRegion.Text = _ac.AzureRegion; } else { UserDialogs.Instance.Alert("No data in config files", "Can't get detailed configuration"); } } else { txtEndpointAzure.Text = Settings.EndpointSetting; txtKeyOcr.Text = Settings.KeyOcrSetting; txtKeySpeech.Text = Settings.KeySpeechSetting; txtLanguage.Text = Settings.LanguageSetting; txtRegion.Text = Settings.RegionSetting; Settings.NoSetupDefined = false; } } }
public AirConService(IDeviceService deviceService, IOptions <AzureConfiguration> azureConfiguration) { _deviceService = deviceService; _azureConfiguration = azureConfiguration.Value; _airConMapper = new AirConMapper(); }
public Task SetConfig(AzureConfiguration ac) { throw new NotImplementedException("Not needed at the moment, using Xamarin plugin"); }
public AzureFunctionPublisher(ILogger <AzureFunctionPublisher> logger, IOptions <AzureConfiguration> azureConfig) { this.logger = logger; this.azureConfig = azureConfig.Value; this.azureConfig.AssertValidity(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { AzureConfiguration _azureConfiguration = new AzureConfiguration(); Configuration.Bind("AzureAd", _azureConfiguration); CacheTime _cacheTime = new CacheTime(); Configuration.Bind("CacheTime", _cacheTime); services.AddCors(options => { options.AddPolicy("AllowAllOrigins", builder => { builder.AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin(); }); }); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddAzureAdBearer(options => Configuration.Bind("AzureAd", options)); services.AddMvc(options => { /// add custom binder to beginning of collection options.ModelBinderProviders.Insert(0, new AlertFilterValueBinderProvider()); /// add cach profiles from appsettings.json options.AddCachingsProfiles(_cacheTime); }) .AddJsonOptions(opt => opt.SerializerSettings .ContractResolver = new CamelCasePropertyNamesContractResolver()) .SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddMemoryCache(); services.AddScoped <ITokenProvider, TokenProvider>(); services.AddScoped <IAlertService, AlertService>(); services.AddScoped <IActionService, ActionService>(); services.AddScoped <INotificationService, NotificationService>(); services.AddSingleton <IDemoExample>(instance => { return(new DemoExample(Convert.ToBoolean(Configuration["UseMockFilters"]))); }); services.AddScoped <IGraphServiceProvider>(instance => { return(new GraphServiceProvider(azureConfiguration: _azureConfiguration)); });; services.AddSingleton <IMemoryCacheHelper, MemoryCacheHelper>(); services.AddSignalR(); // In production, the Angular files will be served from this directory services.AddSpaStaticFiles(configuration => { configuration.RootPath = "wwwroot"; }); services.AddSwaggerGen(c => { c.SwaggerDoc("v3", new Info { Title = "MicrosoftGraph_Security_API_Sample", Version = "v3" }); c.AddSecurityDefinition("Bearer", new ApiKeyScheme() { Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"", Name = "Authorization", In = "header", Type = "apiKey" }); c.AddSecurityRequirement(new Dictionary <string, IEnumerable <string> > { { "Bearer", new string[] { } } }); }); }
/// <summary> /// Creates a new instance of <see cref="ConfigurationController"/> /// <paramref name="azureConfiguration"/> /// <paramref name="systemConfiguration"/> /// </summary> public ConfigurationController(AzureConfiguration azureConfiguration, SystemConfigurationModel systemConfiguration) { this.AzureConfiguration = azureConfiguration; this.SystemConfiguration = systemConfiguration; }
private static void ConfigureAzureMaps(IServiceCollection services, AzureConfiguration azureConfiguration) { services.AddSingleton(azureConfiguration.AzureMapsConfiguration); services.AddTransient <AzureMapsService>(); }
public AzureVideoIndexerHelper(AzureConfiguration azureConfiguration, HttpClient httpClient) { this.AzureConfiguration = azureConfiguration; this.HttpClient = httpClient; }
public PhotoService(AzureConfiguration configuration) { CloudStorageAccount storageAccount = CloudStorageAccount.Parse(configuration.ConnectionString); blobClient = storageAccount.CreateCloudBlobClient(); }
static async Task Main(string[] args) { if (args.Length == 0) { Console.WriteLine("Missing parameters"); return; } HttpClient client = null; if (File.Exists(".token")) { string rawToken = File.ReadAllText(".token"); Token token = JsonConvert.DeserializeObject <Token>(rawToken); client = new HttpClient(); client.BaseAddress = new Uri("https://management.azure.com"); client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token.access_token); client.DefaultRequestHeaders.UserAgent.Add(new System.Net.Http.Headers.ProductInfoHeaderValue("azstatic", "0.0.1")); } string action = args[0]; if (action == "login") { Console.WriteLine("We have opened a browser window for you to login. As soon as the authentication is completed, you can close your browser window."); OpenBrowser($"http://login.microsoftonline.com/common/oauth2/authorize?response_type=code&client_id={Common.ClientId}&redirect_uri={WebUtility.UrlEncode(Common.ReplyUrl)}&state=code&resource=https%3a%2f%2fmanagement.azure.com%2f&prompt=select_account"); // start kestrel and ... somehow... retrieve/save the authentication flow? 🤷♂️ CreateWebHostBuilder().Build().Run(); Console.WriteLine("Authentication completed."); } if (action == "init") { if (client == null) { Console.WriteLine("Please use the `azstatic login` before initializing resources."); return; } // select subscription ConfigurationFile config = AzureConfiguration.GetFromFile(); if (string.IsNullOrWhiteSpace(config.SubscriptionId)) { Subscription subscription = await SelectSubcriptionAsync(client); Console.Clear(); Console.WriteLine($"The selected subscription is: {subscription.displayName}"); } else { Console.WriteLine($"Existing subscription found: {config.SubscriptionId}"); } // select resource group config = AzureConfiguration.GetFromFile(); if (string.IsNullOrWhiteSpace(config.ResourceGroup)) { //todo: allow to specify RG name string rgName = $"azstatic-{RandomString(10)}-prod-rg"; await CreateResourceGroupAsync(rgName, client, config); Console.WriteLine($"Resource group {rgName} created."); } else { await CreateResourceGroupAsync(config.ResourceGroup, client, config); Console.WriteLine($"Existing resource group updated: {config.ResourceGroup}"); } // select storage account name config = AzureConfiguration.GetFromFile(); if (string.IsNullOrWhiteSpace(config.StorageAccount)) { string storageAccountName = $"azstatic{RandomString(10)}"; await CreateStorageAccountAsync(storageAccountName, client, config); Console.WriteLine($"Storage account {storageAccountName} created."); } else { await CreateStorageAccountAsync(config.StorageAccount, client, config); Console.WriteLine($"Existing storage account updated: {config.StorageAccount}"); } // retrieve storage key and use it to enable static website string storageKey = await GetAzureStorageKey(config, client); await SetAzureStorageServiceProperties(storageKey, config); // retrieve web endpoint string storageUrl = await GetAzureStorageUriAsync(config, client); config = AzureConfiguration.GetFromFile(); if (string.IsNullOrWhiteSpace(config.AzureCDNName)) { string cdnName = config.StorageAccount; await CreateAzureCDNProfile(cdnName, client, config); await CreateAzureCDNEndpoint(cdnName, storageUrl, client, config); Console.WriteLine($"Azure CDN endpoint {cdnName} created."); } else { await CreateAzureCDNProfile(config.AzureCDNName, client, config); await CreateAzureCDNEndpoint(config.AzureCDNName, storageUrl, client, config); Console.WriteLine($"Existing storage account updated: {config.StorageAccount}"); } Console.WriteLine("Website provisioned properly and accessible on: "); Console.WriteLine($"\t{storageUrl}"); } if (action == "deploy") { string pathOfStaticSite = "."; if (args.Length == 2) { if (Directory.Exists(args[1])) { pathOfStaticSite = args[1]; } } ConfigurationFile config = AzureConfiguration.GetFromFile(); // retrieve storage key to allow upload string storageKey = await GetAzureStorageKey(config, client); await UploadPathToAzureStorage(pathOfStaticSite, storageKey, config, client); } }
public AzureBlobStorageHandler(IOptions <AzureConfiguration> azureConfiguration) { this.azureConfiguration = azureConfiguration.Value; }
/// <summary> /// Configured application services /// </summary> /// <param name="services"></param> // 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) { GlobalPackageConfiguration.RapidApiKey = Configuration["PTIMicroservicesLibraryConfiguration:RapidApiKey"]; var azureAdB2CSection = Configuration.GetSection("AzureAdB2C"); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddMicrosoftIdentityWebApi(azureAdB2CSection); services.Configure <JwtBearerOptions>( JwtBearerDefaults.AuthenticationScheme, options => { options.TokenValidationParameters.NameClaimType = "name"; options.TokenValidationParameters.RoleClaimType = "Role"; options.Events.OnTokenValidated = async(context) => { BlazorRestaurantDbContext blazorRestaurantDbContext = CreateBlazorRestaurantDbContext(services); ClaimsIdentity claimsIdentity = context.Principal.Identity as ClaimsIdentity; var userObjectIdClaim = claimsIdentity.Claims.Single(p => p.Type == Shared.Global.Constants.Claims.ObjectIdentifier); var user = await blazorRestaurantDbContext.ApplicationUser .Include(p => p.ApplicationUserRole) .ThenInclude(p => p.ApplicationRole) .Where(p => p.AzureAdB2cobjectId.ToString() == userObjectIdClaim.Value) .SingleOrDefaultAsync(); if (user != null && user.ApplicationUserRole != null) { claimsIdentity.AddClaim(new Claim("Role", user.ApplicationUserRole.ApplicationRole.Name)); } }; options.SaveToken = true; }); services.AddTransient <ILogger <CustomHttpClientHandler>, CustomHttpClientHandlerLogger>(); services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); services.AddScoped <ICurrentUserProvider, CurrentUserProvider>(); services.AddScoped(serviceProvide => { BlazorRestaurantDbContext blazorRestaurantDbContext = CreateBlazorRestaurantDbContext(serviceProvide); return(blazorRestaurantDbContext); }); services.AddAutoMapper(configAction => { configAction.AddMaps(new[] { typeof(Startup).Assembly }); }); SystemConfigurationModel systemConfiguration = Configuration.GetSection("SystemConfiguration").Get <SystemConfigurationModel>(); services.AddSingleton(systemConfiguration); ConfigureDataStorage(services); ConfigurePTIMicroservicesLibraryDefaults(services); ConfigureAzureBlobStorage(services); AzureConfiguration azureConfiguration = Configuration.GetSection("AzureConfiguration").Get <AzureConfiguration>(); services.AddSingleton(azureConfiguration); ConfigureAzureMaps(services, azureConfiguration); services.AddControllersWithViews(); services.AddRazorPages(); services.AddSwaggerGen(c => { c.UseInlineDefinitionsForEnums(); var filePath = Path.Combine(System.AppContext.BaseDirectory, "BlazorRestaurant.Server.xml"); if (System.IO.File.Exists(filePath)) { c.IncludeXmlComments(filePath); } }); }
public SchedulerService(IOptions <AzureConfiguration> azureConfiguration) { _azureConfiguration = azureConfiguration.Value; }