Example #1
0
        public void ConfigureServices(IServiceCollection services)
        {
            AzureBlobOptions      blobOptions           = Configuration.GetSection("AzureBlobOptions").Get <AzureBlobOptions>();
            AzureBlobFileProvider azureBlobFileProvider = new AzureBlobFileProvider(blobOptions);

            services.AddSingleton(azureBlobFileProvider);
        }
Example #2
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.Configure <CookiePolicyOptions>(options =>
            {
                //options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddSession(actions =>
            {
                actions.IdleTimeout     = TimeSpan.FromSeconds(10);
                actions.Cookie.HttpOnly = true;
            });
            services.AddMvc();
            services.AddHttpContextAccessor();

            services.AddDbContext <MusicStoreEntities>(options =>
                                                       options
                                                       .UseLazyLoadingProxies()
                                                       .UseSqlServer(Configuration.GetConnectionString("MusicStoreEntities")));

            services.AddAuthentication(AzureADB2CDefaults.AuthenticationScheme)
            .AddAzureADB2C(options => Configuration.Bind("AzureAdB2C", options)).AddCookie();

            var blobOptions = new AzureBlobOptions
            {
                ConnectionString  = Configuration.GetConnectionString("AzureStorageStaticFiles"),
                DocumentContainer = "wwwroot"
            };
            var azureBlobFileProvider = new AzureBlobFileProvider(blobOptions);

            services.AddSingleton(azureBlobFileProvider);
        }
Example #3
0
        static int Main(string[] args)
        {
            try
            {
                var environmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

                var config = new ConfigurationBuilder()
                             .AddJsonFile("appsettings.json", false)
                             .AddJsonFile($"appsettings.{environmentName}.json", optional: true, reloadOnChange: true)
                             .Build();

                var options = new AzureBlobOptions()
                {
                    ConnectionString = config["AzureBlobOptions:ConnectionString"]
                };

                var services = new ServiceCollection()
                               .AddLogging()
                               .AddOptions()
                               .AddStorageAzureIntegration <AzureBlobOptions>(config, Guid.Parse("ECEB4346-97AD-4919-9248-3EA1012FCA47").ToString())
                               .AddSingleton <Startup>()
                               .BuildServiceProvider();

                var application = services.GetRequiredService <Startup>();
                application.RunAsync().GetAwaiter().GetResult();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                return(1);
            }

            return(0);
        }
 public PostsController(
     ImageService saveImageService,
     ApplicationDbContext context,
     UserManager <AppUser> userManager,
     IOptions <AzureBlobOptions> azureOptions,
     IDistributedCache cache)
 {
     this.imageService = saveImageService;
     this.context      = context;
     this.userManager  = userManager;
     this.cache        = cache;
     this.azureOptions = azureOptions.Value;
 }
Example #5
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.Configure <CookiePolicyOptions>(options =>
            {
                //options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddSession(actions =>
            {
                actions.IdleTimeout     = TimeSpan.FromSeconds(10);
                actions.Cookie.HttpOnly = true;
            });
            services.AddMvc();
            services.AddHttpContextAccessor();

            services.AddDbContext <MusicStoreEntities>(options =>
                                                       options
                                                       .UseLazyLoadingProxies()
                                                       .UseSqlServer(Configuration.GetConnectionString("MusicStoreEntities")));

            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlServer(Configuration.GetConnectionString("ASPNETDB")));

            services.AddIdentity <ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();

            services.AddAuthentication().AddCookie();


            services.ConfigureApplicationCookie(options =>
            {
                options.LoginPath      = "/Account/Logon";
                options.ExpireTimeSpan = TimeSpan.FromHours(1);
            });

            var blobOptions = new AzureBlobOptions
            {
                ConnectionString  = Configuration.GetConnectionString("AzureStorageStaticFiles"),
                DocumentContainer = "wwwroot"
            };
            var azureBlobFileProvider = new AzureBlobFileProvider(blobOptions);

            services.AddSingleton(azureBlobFileProvider);
        }
Example #6
0
 private void SetupAzureBlobStore()
 {
     _services.AddSingleton <IFileSystemOperations>((provider) =>
     {
         string connectionString = GetConfigString(provider, _options.AzureStorageConnectionStringConfigPath);
         var storageAccount      = CloudStorageAccount.Parse(
             connectionString);
         CloudBlobClient cloudBlobClient       = storageAccount.CreateCloudBlobClient();
         CloudBlobContainer cloudBlobContainer =
             cloudBlobClient.GetContainerReference(_options.AzureBlobContainerName);
         var azureBlobOptions = new AzureBlobOptions
         {
             PathPrefix = _options.AzureBlobPathPrefix
         };
         return(new AzureBlobOperations(cloudBlobContainer, azureBlobOptions,
                                        CreateLogger <AzureBlobOperations>(provider)));
     });
 }
        public static async Task DeleteFileFromStorage(AzureBlobOptions _storageConfig, string fileName)
        {
            // Create storagecredentials object by reading the values from the configuration (appsettings.json)
            StorageCredentials storageCredentials = new StorageCredentials(_storageConfig.AccountName, _storageConfig.AccountKey);

            // Create cloudstorage account by passing the storagecredentials
            CloudStorageAccount storageAccount = new CloudStorageAccount(storageCredentials, true);

            // Create the blob client.
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

            // Get reference to the blob container by passing the name by reading the value from the configuration (appsettings.json)
            CloudBlobContainer container = blobClient.GetContainerReference(_storageConfig.ImageContainer);

            // Get the reference to the block blob from the container
            CloudBlockBlob blockBlob = container.GetBlockBlobReference(fileName);

            await blockBlob.DeleteAsync();
        }
        public static async Task <List <string> > GetThumbNailUrls(AzureBlobOptions _storageConfig)
        {
            List <string> thumbnailUrls = new List <string>();

            // Create storagecredentials object by reading the values from the configuration (appsettings.json)
            StorageCredentials storageCredentials = new StorageCredentials(_storageConfig.AccountName, _storageConfig.AccountKey);

            // Create cloudstorage account by passing the storagecredentials
            CloudStorageAccount storageAccount = new CloudStorageAccount(storageCredentials, true);

            // Create blob client
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

            // Get reference to the container
            CloudBlobContainer container = blobClient.GetContainerReference(_storageConfig.ThumbnailContainer);

            BlobContinuationToken continuationToken = null;

            BlobResultSegment resultSegment = null;

            //Call ListBlobsSegmentedAsync and enumerate the result segment returned, while the continuation token is non-null.
            //When the continuation token is null, the last page has been returned and execution can exit the loop.
            do
            {
                //This overload allows control of the page size. You can return all remaining results by passing null for the maxResults parameter,
                //or by calling a different overload.
                resultSegment = await container.ListBlobsSegmentedAsync("", true, BlobListingDetails.All, 10, continuationToken, null, null);

                foreach (var blobItem in resultSegment.Results)
                {
                    thumbnailUrls.Add(blobItem.StorageUri.PrimaryUri.ToString());
                }

                //Get the continuation token.
                continuationToken = resultSegment.ContinuationToken;
            }while (continuationToken != null);

            return(thumbnailUrls);
        }
Example #9
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.Configure <CookiePolicyOptions>(options =>
            {
                //options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddSession(actions =>
            {
                actions.IdleTimeout     = TimeSpan.FromMinutes(20);
                actions.Cookie.HttpOnly = true;
            });
            services.AddDistributedRedisCache(o =>
            {
                o.Configuration = Configuration.GetConnectionString("RedisCache");
            });
            services.AddMvc().AddJsonOptions(opt =>
            {
                opt.SerializerSettings.ReferenceLoopHandling      = ReferenceLoopHandling.Ignore;
                opt.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.Objects;
            });

            services.AddHttpContextAccessor();

            services.AddAuthentication(AzureADB2CDefaults.AuthenticationScheme)
            .AddAzureADB2C(options => Configuration.Bind("AzureAdB2C", options)).AddCookie();

            var blobOptions = new AzureBlobOptions
            {
                ConnectionString  = Configuration.GetConnectionString("AzureStorageStaticFiles"),
                DocumentContainer = "wwwroot"
            };
            var azureBlobFileProvider = new AzureBlobFileProvider(blobOptions);

            services.AddSingleton(azureBlobFileProvider);
        }
Example #10
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            #region Add CORS
            services.AddCors(options => options.AddPolicy("Cors", builder =>
            {
                builder
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader();
            }));
            #endregion

            #region Add Authentication
            var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Tokens:Key"]));
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(config =>
            {
                config.RequireHttpsMetadata      = false;
                config.SaveToken                 = true;
                config.TokenValidationParameters = new TokenValidationParameters()
                {
                    IssuerSigningKey         = signingKey,
                    ValidateAudience         = true,
                    ValidAudience            = this.Configuration["Tokens:Audience"],
                    ValidateIssuer           = true,
                    ValidIssuer              = this.Configuration["Tokens:Issuer"],
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true
                };
            });
            #endregion

            var blobOptionsTracks = new AzureBlobOptions
            {
                ConnectionString  = Configuration.GetConnectionString("BlobConnectionString"),
                DocumentContainer = "tracks"
            };


            var azureBlobFileProviderTracks = new AzureBlobFileProvider(blobOptionsTracks);


            // services.AddSingleton(azureBlobFileProviderTracks);

            var blobOptionsImages = new AzureBlobOptions
            {
                ConnectionString  = Configuration.GetConnectionString("BlobConnectionString"),
                DocumentContainer = "images"
            };


            var azureBlobFileProviderImages = new AzureBlobFileProvider(blobOptionsImages);
            //services.AddSingleton(azureBlobFileProviderImages);

            var composite = new CompositeFileProvider(azureBlobFileProviderTracks, azureBlobFileProviderImages);
            services.AddSingleton(composite);


            services.AddMvc()
            .AddJsonOptions(
                options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "My API", Version = "v1"
                });
            });
        }