Пример #1
0
        public static IServiceProvider Initialize(
            IServiceCollection services,
            string connectionString,
            ICacheStore cacheStore,
            IEmailSender emailSender,
            IFileSaver fileSaver,
            EmailsSettings emailsSettings,
            AzureBlobStorageSettings azureBlobStorageSettings,
            ILogger logger,
            IExecutionContextAccessor executionContextAccessor,
            IUserAuthIdProvider userAuthIdProvider,
            bool runQuartz = true)
        {
            if (runQuartz)
            {
                StartQuartz(connectionString, emailsSettings, azureBlobStorageSettings, logger, executionContextAccessor, userAuthIdProvider);
            }

            services.AddSingleton(cacheStore);

            var serviceProvider = CreateAutofacServiceProvider(
                services,
                connectionString,
                emailSender,
                fileSaver,
                emailsSettings,
                azureBlobStorageSettings,
                logger,
                executionContextAccessor,
                userAuthIdProvider);

            return(serviceProvider);
        }
Пример #2
0
        public async Task DownloadAsync_ReturnsFileStreamResult()
        {
            const string expectedContentType = "test/content-type";

            using var expectedStream = new MemoryStream(Encoding.UTF8.GetBytes("Hello world!"));

            var azureBlobStorageSettings = new AzureBlobStorageSettings();

            azureBlobStorageSettings.DocumentDirectory = "non-solution";

            var downloadInfo = new Mock <IDocument>();

            downloadInfo.Setup(d => d.Content).Returns(expectedStream);
            downloadInfo.Setup(d => d.ContentType).Returns(expectedContentType);

            var mockStorage = new Mock <IDocumentRepository>();

            mockStorage.Setup(s => s.DownloadAsync(It.IsAny <string>()))
            .ReturnsAsync(downloadInfo.Object);

            var controller = new DocumentsController(mockStorage.Object, Mock.Of <ILogger <DocumentsController> >());

            var result = await controller.DownloadAsync("directory") as FileStreamResult;

            Assert.NotNull(result);
            result.FileStream.IsSameOrEqualTo(expectedStream);
            result.ContentType.Should().Be(expectedContentType);
        }
        public static void Uri_NullConnectionString_ReturnsNull(string connectionString)
        {
            var settings = new AzureBlobStorageSettings {
                ConnectionString = connectionString
            };

            settings.Uri.Should().BeNull();
        }
Пример #4
0
        private static void StartQuartz(
            string connectionString,
            EmailsSettings emailsSettings,
            AzureBlobStorageSettings blobStorageSettings,
            ILogger logger,
            IExecutionContextAccessor executionContextAccessor,
            IUserAuthIdProvider userAuthIdProvider)
        {
            var schedulerFactory = new StdSchedulerFactory();
            var scheduler        = schedulerFactory.GetScheduler().GetAwaiter().GetResult();

            var container = new ContainerBuilder();

            container.RegisterModule(new LoggingModule(logger));
            container.RegisterModule(new QuartzModule());
            container.RegisterModule(new MediatorModule());
            container.RegisterModule(new DataAccessModule(connectionString));
            container.RegisterModule(new EmailModule(emailsSettings));
            container.RegisterModule(new ProcessingModule());
            container.RegisterModule(new AuthenticationModule(userAuthIdProvider));
            container.RegisterModule(new AzureBlobStorageModule(blobStorageSettings));

            container.RegisterInstance(executionContextAccessor);
            container.Register(c =>
            {
                var dbContextOptionsBuilder = new DbContextOptionsBuilder <TreesContext>();
                dbContextOptionsBuilder.UseSqlServer(connectionString);

                dbContextOptionsBuilder
                .ReplaceService <IValueConverterSelector, StronglyTypedIdValueConverterSelector>();

                return(new TreesContext(dbContextOptionsBuilder.Options));
            }).AsSelf().InstancePerLifetimeScope();

            scheduler.JobFactory = new JobFactory(container.Build());

            scheduler.Start().GetAwaiter().GetResult();

            var processOutboxJob = JobBuilder.Create <ProcessOutboxJob>().Build();
            var trigger          =
                TriggerBuilder
                .Create()
                .StartNow()
                .WithCronSchedule("0/15 * * ? * *")
                .Build();

            scheduler.ScheduleJob(processOutboxJob, trigger).GetAwaiter().GetResult();

            var processInternalCommandsJob = JobBuilder.Create <ProcessInternalCommandsJob>().Build();
            var triggerCommandsProcessing  =
                TriggerBuilder
                .Create()
                .StartNow()
                .WithCronSchedule("0/15 * * ? * *")
                .Build();

            scheduler.ScheduleJob(processInternalCommandsJob, triggerCommandsProcessing).GetAwaiter().GetResult();
        }
        private async Task <BlobFile> SaveToAzureStorageAsync(
            Jarvus.File.IWebAppFile File,
            AzureBlobStorageSettings storageSettings
            )
        {
            String StorageAccountName      = storageSettings.StorageAccountName;
            String FullImagesContainerName = storageSettings.ContainerName;

            string relativePath = File.RelativePath;

            if (relativePath.StartsWith("/"))
            {
                relativePath = relativePath.Substring(1, relativePath.Length - 1);
            }

            String BlobName = relativePath;

            _logger.LogDebug($"uploading to storage account name {StorageAccountName}; container named {FullImagesContainerName}; blob-name {BlobName}");

            CloudStorageAccount storageAccount = new CloudStorageAccount(
                new Microsoft.WindowsAzure.Storage.Auth.StorageCredentials(
                    StorageAccountName,
                    storageSettings.AccessKey
                    ),
                true
                );

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

            // Get a reference to a container named "my-new-container."
            CloudBlobContainer container = blobClient.GetContainerReference(
                FullImagesContainerName);

            // If "mycontainer" doesn't exist, create it.
            await container.CreateIfNotExistsAsync();

            // Get a reference to a blob named "myblob".
            CloudBlockBlob blockBlob = container.GetBlockBlobReference(BlobName);

            // Create or overwrite the "myblob" blob with the contents of a local file
            // named "myfile".
            using (var fileStream = System.IO.File.OpenRead(File.AbsoluteBase + "/" + File.RelativePath))
            {
                await blockBlob.UploadFromStreamAsync(fileStream);
            }

            _logger.LogDebug("upload finished");

            return(new BlobFile {
                AbsoluteBase = storageSettings.BaseUri,
                RelativePath = File.RelativePath,
                StorageAccountName = StorageAccountName,
                ContainerName = FullImagesContainerName
            });
        }
        public void Uri_HasConnectionString_ReturnsUri()
        {
            const string uri = "http://127.0.0.1:10000/devstoreaccount1";
            const string connectionString =
                "DefaultEndpointsProtocol=http;AccountName=UnitTest;AccountKey=;BlobEndpoint=" + uri;

            var settings = new AzureBlobStorageSettings {
                ConnectionString = connectionString
            };

            settings.Uri.Should().NotBeNull();
            settings.Uri.AbsoluteUri.Should().BeEquivalentTo(uri);
        }
Пример #7
0
        public ApplicationFixture()
        {
            const string connectionStringEnvironmentVariable =
                "ASPNETCORE_TreeOfAKind_IntegrationTests_ConnectionString";

            ConnectionString = Environment.GetEnvironmentVariable(connectionStringEnvironmentVariable);
            if (ConnectionString == null)
            {
                throw new ApplicationException(
                          $"Define connection string to integration tests database using environment variable: {connectionStringEnvironmentVariable}");
            }

            using var sqlConnection = new SqlConnection(ConnectionString);

            ClearDatabase(sqlConnection);

            EmailsSettings = new EmailsSettings {
                FromAddressEmail = "*****@*****.**"
            };

            AzureBlobStorageSettings = new AzureBlobStorageSettings
            {
                ConnectionString = "someConnectionString",
                Metadata         = new Dictionary <string, string>
                {
                    { "IntegrationTesting", "true" }
                }
            };

            EmailSender = Substitute.For <IEmailSender>();

            FileSaver = Substitute.For <IFileSaver>();

            UserAuthIdProvider = Substitute.For <IUserAuthIdProvider>();

            ExecutionContext = new ExecutionContextMock();

            ApplicationStartup.Initialize(
                new ServiceCollection(),
                ConnectionString,
                new CacheStore(),
                EmailSender,
                FileSaver,
                EmailsSettings,
                AzureBlobStorageSettings,
                Logger.None,
                ExecutionContext,
                UserAuthIdProvider,
                runQuartz: false);
        }
        public static void Uri_HasConnectionString_ReturnsUri()
        {
            // ReSharper disable once StringLiteralTypo
            const string uri = "http://127.0.0.1:10000/devstoreaccount1";

            const string connectionString =
                "DefaultEndpointsProtocol=http;AccountName=UnitTest;AccountKey=;BlobEndpoint=" + uri;

            var settings = new AzureBlobStorageSettings {
                ConnectionString = connectionString
            };

            Assert.NotNull(settings.Uri);
            settings.Uri.AbsoluteUri.Should().BeEquivalentTo(uri);
        }
Пример #9
0
        public static async Task DownloadAsync_String_ReturnsBlobDownloadInfo()
        {
            var azureBlobStorageSettings = new AzureBlobStorageSettings {
                DocumentDirectory = "non-solution"
            };
            const string expectedContentType = "test/content";

            await using var expectedStream = new MemoryStream();
            var mockSdk = MockSdk.DownloadAsync().Returns(expectedStream, expectedContentType);
            var storage = new AzureBlobDocumentRepository(mockSdk.BlobContainerClient, azureBlobStorageSettings);

            var result = await storage.DownloadAsync("TheBlob");

            result.Content.Should().BeSameAs(expectedStream);
            result.ContentType.Should().Be(expectedContentType);
        }
Пример #10
0
        private static IServiceProvider CreateAutofacServiceProvider(
            IServiceCollection services,
            string connectionString,
            IEmailSender emailSender,
            IFileSaver fileSaver,
            EmailsSettings emailsSettings,
            AzureBlobStorageSettings azureBlobStorageSettings,
            ILogger logger,
            IExecutionContextAccessor executionContextAccessor,
            IUserAuthIdProvider userAuthIdProvider)
        {
            var container = new ContainerBuilder();

            container.Populate(services);

            container.RegisterModule(new LoggingModule(logger));
            container.RegisterModule(new DataAccessModule(connectionString));
            container.RegisterModule(new MediatorModule());
            container.RegisterModule(new DomainModule());
            container.RegisterModule(new GedcomXToDomainModule());
            container.RegisterModule(new AuthenticationModule(userAuthIdProvider));
            container.RegisterModule(new AzureBlobStorageModule(azureBlobStorageSettings, fileSaver));

            if (emailSender != null)
            {
                container.RegisterModule(new EmailModule(emailSender, emailsSettings));
            }
            else
            {
                container.RegisterModule(new EmailModule(emailsSettings));
            }

            container.RegisterModule(new ProcessingModule());

            container.RegisterInstance(executionContextAccessor);

            var buildContainer = container.Build();

            ServiceLocator.SetLocatorProvider(() => new AutofacServiceLocator(buildContainer));

            var serviceProvider = new AutofacServiceProvider(buildContainer);

            CompositionRoot.SetContainer(buildContainer);

            return(serviceProvider);
        }
        public void Create_NullRetryOptions_ReturnsContainerClient()
        {
            const string accountName      = "devstoreaccount1";
            const string containerName    = "Container";
            const string uri              = "http://127.0.0.1:10000/" + accountName;
            const string connectionString =
                "DefaultEndpointsProtocol=http;AccountName="
                + accountName + "UnitTest;AccountKey=;BlobEndpoint="
                + uri;

            var settings = new AzureBlobStorageSettings
            {
                ConnectionString = connectionString,
                ContainerName    = containerName,
            };

            var client = AzureBlobContainerClientFactory.Create(settings);

            client.Should().NotBeNull();
            client.AccountName.Should().Be(accountName);
            client.Name.Should().Be(containerName);
        }
Пример #12
0
 public ImagesController(IOptions <AzureBlobStorageSettings> azureBlobStorageSettings)
 {
     _azureBlobStorageSettings = azureBlobStorageSettings.Value;
     _storageAccount           = CloudStorageAccount.Parse(_azureBlobStorageSettings.ImageConnectionString);
 }
Пример #13
0
 public static bool IsAzureBlobStorageEnabled(this AzureBlobStorageSettings azureBlobStorageSettings) =>
 azureBlobStorageSettings.ConnectionString != null;