Пример #1
0
        protected override void ConfigureJobServices(IServiceCollection services, IConfigurationRoot configurationRoot)
        {
            services.Configure <CertificateStoreConfiguration>(configurationRoot.GetSection(CertificateStoreConfigurationSectionName));
            SetupDefaultSubscriptionProcessorConfiguration(services, configurationRoot);

            services.AddTransient <IBrokeredMessageSerializer <CertificateValidationMessage>, CertificateValidationMessageSerializer>();
            services.AddTransient <IMessageHandler <CertificateValidationMessage>, CertificateValidationMessageHandler>();

            services.AddTransient <ICertificateStore>(p =>
            {
                var config = p.GetRequiredService <IOptionsSnapshot <CertificateStoreConfiguration> >().Value;
                var targetStorageAccount = CloudStorageAccount.Parse(config.DataStorageAccount);

                var storageFactory = new AzureStorageFactory(targetStorageAccount, config.ContainerName, LoggerFactory.CreateLogger <AzureStorage>());
                var storage        = storageFactory.Create();

                return(new CertificateStore(storage, LoggerFactory.CreateLogger <CertificateStore>()));
            });

            services.AddTransient <ICertificateVerifier, OnlineCertificateVerifier>();
            services.AddTransient <ICertificateValidationService, CertificateValidationService>();
            services.AddTransient <ITelemetryService, TelemetryService>();
            services.AddTransient <ISubscriptionProcessorTelemetryService, TelemetryService>();
            services.AddSingleton(new TelemetryClient());
        }
        public void AzureCompressedFactory(string storageBaseAddress,
                                           string storageAccountName,
                                           string storageKeyValue,
                                           string storageContainer,
                                           string storagePath,
                                           string storageType)
        {
            Dictionary <string, string> arguments = new Dictionary <string, string>()
            {
                { Arguments.CompressedStorageBaseAddress, storageBaseAddress },
                { Arguments.CompressedStorageAccountName, storageAccountName },
                { Arguments.CompressedStorageKeyValue, storageKeyValue },
                { Arguments.CompressedStorageContainer, storageContainer },
                { Arguments.CompressedStoragePath, storagePath },
                { Arguments.StorageType, storageType },
                { Arguments.UseCompressedStorage, "true" }
            };

            StorageFactory      factory      = CommandHelpers.CreateCompressedStorageFactory(arguments, true);
            AzureStorageFactory azureFactory = factory as AzureStorageFactory;

            // Assert
            Assert.True(azureFactory != null, "The CreateCompressedStorageFactory should return an AzureStorageFactory.");
            Assert.True(azureFactory.CompressContent, "The compressed storage factory should compress the content.");
        }
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var    iconBytes = Convert.FromBase64String(model.IconBase64);
                var    container = AzureStorageFactory.GetBlobContainer("werewolfkill", true);
                string blobName  = string.Format("icon/{0}.png", HashValue.md5(iconBytes));
                var    user      = new ApplicationUser(model.Username)
                {
                    //UserName = model.Username,
                    NickName  = string.IsNullOrEmpty(model.Nickname) ? model.Username : model.Nickname,
                    AvatarUrl = string.Format("{0}/{1}", container.EndpointUrl, blobName)
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    await container.UploadBlob(blobName, iconBytes);

                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                    return(RedirectToAction("Index", "Home"));
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Пример #4
0
        public override void Init(IDictionary <string, string> jobArgsDictionary)
        {
            _whatIf = JobConfigurationManager.TryGetBoolArgument(jobArgsDictionary, JobArgumentNames.WhatIf);

            var databaseConnectionString = JobConfigurationManager.GetArgument(jobArgsDictionary, JobArgumentNames.GalleryDatabase);

            _galleryDatabase = new SqlConnectionStringBuilder(databaseConnectionString);

            _galleryBrand      = JobConfigurationManager.GetArgument(jobArgsDictionary, MyJobArgumentNames.GalleryBrand);
            _galleryAccountUrl = JobConfigurationManager.GetArgument(jobArgsDictionary, MyJobArgumentNames.GalleryAccountUrl);

            _mailFrom = JobConfigurationManager.GetArgument(jobArgsDictionary, JobArgumentNames.MailFrom);

            var smtpConnectionString = JobConfigurationManager.GetArgument(jobArgsDictionary, JobArgumentNames.SmtpUri);
            var smtpUri = new SmtpUri(new Uri(smtpConnectionString));

            _smtpClient = CreateSmtpClient(smtpUri);

            _warnDaysBeforeExpiration = JobConfigurationManager.TryGetIntArgument(jobArgsDictionary, MyJobArgumentNames.WarnDaysBeforeExpiration)
                                        ?? _warnDaysBeforeExpiration;

            _allowEmailResendAfterDays = JobConfigurationManager.TryGetIntArgument(jobArgsDictionary, MyJobArgumentNames.AllowEmailResendAfterDays)
                                         ?? _allowEmailResendAfterDays;

            var storageConnectionString = JobConfigurationManager.GetArgument(jobArgsDictionary, JobArgumentNames.DataStorageAccount);
            var storageContainerName    = JobConfigurationManager.GetArgument(jobArgsDictionary, JobArgumentNames.ContainerName);

            var storageAccount = CloudStorageAccount.Parse(storageConnectionString);
            var storageFactory = new AzureStorageFactory(storageAccount, storageContainerName, LoggerFactory);

            _storage = storageFactory.Create();
        }
Пример #5
0
        public override void Init(IServiceContainer serviceContainer, IDictionary <string, string> jobArgsDictionary)
        {
            base.Init(serviceContainer, jobArgsDictionary);

            InitializationConfiguration = _serviceProvider.GetRequiredService <IOptionsSnapshot <InitializationConfiguration> >().Value;

            var serializer  = new ServiceBusMessageSerializer();
            var topicClient = new TopicClientWrapper(InitializationConfiguration.EmailPublisherConnectionString, InitializationConfiguration.EmailPublisherTopicName);
            var enqueuer    = new EmailMessageEnqueuer(topicClient, serializer, LoggerFactory.CreateLogger <EmailMessageEnqueuer>());

            EmailService = new AsynchronousEmailMessageService(
                enqueuer,
                LoggerFactory.CreateLogger <AsynchronousEmailMessageService>(),
                InitializationConfiguration);

            FromAddress = new MailAddress(InitializationConfiguration.MailFrom);

            var storageAccount = CloudStorageAccount.Parse(InitializationConfiguration.DataStorageAccount);
            var storageFactory = new AzureStorageFactory(
                storageAccount,
                InitializationConfiguration.ContainerName,
                LoggerFactory.CreateLogger <AzureStorage>());

            Storage = storageFactory.Create();
        }
Пример #6
0
        public async void WeDoGetDataFromBlobStorage()
        {
            var acc           = new Mock <ICloudStorageAccount>();
            var blobClient    = new Mock <CloudBlobClient>(new Uri("https://ww.google.com"), new StorageCredentials());
            var blobContainer = new Mock <CloudBlobContainer>(new Uri("https://www.google.com"));

            var blob      = new Mock <CloudBlob>(new Uri("https://waterfinder.blob.core.windows.net/data"));
            var riverList = new List <River>()
            {
                new River()
            };
            var listString = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(riverList));

            using (var val = new MemoryStream(listString))
            {
                blob.Setup(b => b.OpenReadAsync()).ReturnsAsync(val);
                blobContainer.Setup(bc => bc.GetBlobReference(It.IsAny <string>())).Returns(blob.Object);
                blobClient.Setup(b => b.GetContainerReference(It.IsAny <string>())).Returns(blobContainer.Object);

                acc.Setup(c => c.CreateCloudBlobClient()).Returns(blobClient.Object);

                var fac = new AzureStorageFactory(acc.Object)
                {
                    CollectionName = "PIZZA"
                };
                var stuff = await fac.GetAsync <List <River> >("TACOS");

                Assert.NotEmpty(stuff);
            }
        }
        public StorageRegistrationOwnership(IOwinContext context, CloudStorageAccount account, string ownershipContainer)
        {
            _context = context;

            StorageFactory storageFactory = new AzureStorageFactory(account, ownershipContainer);

            _registration = new StorageRegistration(storageFactory);
        }
Пример #8
0
 public UserStore(string userTableName, string userClaimTableName, string userRoleTableName, string userLoginTableName, string lookupTableName)
 {
     m_userTable      = AzureStorageFactory.GetTable(userTableName, true);
     m_userClaimTable = AzureStorageFactory.GetTable(userClaimTableName, true);
     m_userRoleTable  = AzureStorageFactory.GetTable(userRoleTableName, true);
     m_userLoginTable = AzureStorageFactory.GetTable(userLoginTableName, true);
     m_lookupTable    = AzureStorageFactory.GetTable(lookupTableName, true);
 }
Пример #9
0
        public void Setup()
        {
            var factory = new AzureStorageFactory(CloudStorageAccount.DevelopmentStorageAccount);

            _repository   = new WebSiteRepository(factory);
            _webSiteTable = factory.GetTable <WebSiteRow>(typeof(WebSiteRow).Name);
            _bindingTable = factory.GetTable <BindingRow>(typeof(BindingRow).Name);
        }
Пример #10
0
            public void ValidatesArgs()
            {
                //Arrange
                var target = new AzureStorageFactory();

                //Act Assert
                Assert.That(() => target.GetAzureQueue <CloudQueueMessage>(null, "foo"), Throws.ArgumentNullException);
                Assert.That(() => target.GetAzureQueue <CloudQueueMessage>(mockAccount, string.Empty), Throws.ArgumentNullException);
            }
Пример #11
0
 public BaseAzureQueueBuilderTester()
 {
     AccountMock     = new Mock <ICloudStorageAccount>();
     QueueClientMock = new Mock <CloudQueueClient>(new Uri("https://www.google.com"), new StorageCredentials());
     CloudQueueMock  = new Mock <CloudQueue>(new Uri("https://www.google.com"));
     QueueClientMock.Setup(qc => qc.GetQueueReference(It.IsAny <string>())).Returns(CloudQueueMock.Object);
     AccountMock.Setup(c => c.CreateCloudQueueClient()).Returns(QueueClientMock.Object);
     Builder = new AzureStorageFactory(AccountMock.Object);
 }
        public static void EnsureDomainObjectsExist()
        {
            var factory = new AzureStorageFactory(CloudStorageAccount.FromConfigurationSetting("DataConnectionString"));

            factory.GetTable<Contact>(FBwithWA.Domain.AzureConstants.ContactTableName).Initialize();
            factory.GetQueue<ContactQueueMessage>(AzureConstants.ContactQueueName).Initialize();
            factory.GetTable<ZipStore>(FBwithWA.Domain.AzureConstants.ZipStoreTableName).Initialize();
            factory.GetTable<Store>(FBwithWA.Domain.AzureConstants.StoreTableName).Initialize();
        }
Пример #13
0
            public void ValidatesArgs()
            {
                //Arrange
                var target = new AzureStorageFactory();

                //Act Assert
                Assert.That(() => target.GetAccount(null), Throws.ArgumentNullException);
                Assert.That(() => target.GetAccount(null, "key", true), Throws.ArgumentNullException);
                Assert.That(() => target.GetAccount("foo", null, true), Throws.ArgumentNullException);
            }
Пример #14
0
            public void Sucesss()
            {
                //Arrange
                var target = new AzureStorageFactory();

                //Act
                var result = target.GetAzureQueue <CloudQueueMessage>(mockAccount, "foo");

                //Assert
                Assert.IsNotNull(result);
            }
Пример #15
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            AzureStorageFactory.Initialze(ConfigurationManager.ConnectionStrings["AzureStorage"].ConnectionString);
            // Configure the db context, user manager and signin manager to use a single instance per request
            //app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create);
            app.CreatePerOwinContext <ApplicationRoleManager>(ApplicationRoleManager.Create);

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            // Configure the sign in cookie
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Account/Login"),
                Provider           = new CookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Enables the application to remember the second login verification factor such as phone or email.
            // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            // This is similar to the RememberMe option when you log in.
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            // Uncomment the following lines to enable logging in with third party login providers
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(
            //   consumerKey: "",
            //   consumerSecret: "");

            //app.UseFacebookAuthentication(
            //   appId: "",
            //   appSecret: "");

            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});
        }
Пример #16
0
        public void Update_sites_removing_site()
        {
            var contosoWebSite = new WebSite
            {
                Name     = ContosoWebSiteName,
                Bindings = new List <Binding>
                {
                    new Binding
                    {
                        Protocol  = "http",
                        IpAddress = "127.0.0.1",
                        Port      = 8081,
                        HostName  = "contoso.com"
                    }
                }
            };

            var fabrikamWebSite = new WebSite
            {
                Name     = FabrikamWebSiteName,
                Bindings = new List <Binding>
                {
                    new Binding
                    {
                        Protocol              = "https",
                        IpAddress             = "127.0.0.1",
                        Port                  = 8443,
                        CertificateThumbprint = "12345"
                    }
                }
            };

            var factory    = new AzureStorageFactory(CloudStorageAccount.DevelopmentStorageAccount);
            var iisManager = new IISManager(LocalSitesPath, TempSitesPath, new SyncStatusRepository(factory), new ConsoleFactory(), LoggerLevel.Debug);
            var sites      = new List <WebSite> {
                contosoWebSite, fabrikamWebSite
            };

            iisManager.UpdateSites(sites, _excludedSites);

            Assert.AreEqual(2, RetrieveWebSites().Count() - _excludedSites.Count);

            sites.RemoveAt(0);
            iisManager.UpdateSites(sites, _excludedSites);

            // Asserts
            Assert.AreEqual(1, RetrieveWebSites().Count() - _excludedSites.Count);

            Site contoso  = RetrieveWebSite(ContosoWebSiteName);
            Site fabrikam = RetrieveWebSite(FabrikamWebSiteName);

            Assert.IsNull(contoso);
            Assert.IsNotNull(fabrikam);
        }
Пример #17
0
            public void SuccessWithConnectionString()
            {
                //Arrange
                var target = new AzureStorageFactory();

                //Act
                var result = target.GetAccount(TestHelpers.DevConnectionString);

                //Assert
                Assert.IsNotNull(result);
            }
Пример #18
0
            public void SuccessWithAccountName()
            {
                //Arrange
                var target = new AzureStorageFactory();

                //Act
                var result = target.GetAccount(TestHelpers.DevAccountName, TestHelpers.DevAccountKey, true);

                //Assert
                Assert.IsNotNull(result);
            }
Пример #19
0
        protected override void FixtureSetup()
        {
            base.FixtureSetup();

            // RoleEnvironment
            AzureRoleEnvironment.DeploymentId          = () => "DEPLOYMENTID";
            AzureRoleEnvironment.CurrentRoleInstanceId = () => "ROLEINSTANCEID";

            // File Resource Paths
            var basePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase.Replace("file:///", ""));

            _sitePath      = Path.Combine(basePath, "Sites");
            _tempPath      = Path.Combine(basePath, "Temp");
            _configPath    = Path.Combine(basePath, "Config");
            _resourcesPath = Path.Combine(basePath, "_resources");
            Directory.CreateDirectory(_sitePath);
            Directory.CreateDirectory(_tempPath);
            Directory.CreateDirectory(_configPath);

            // Website Repository
            var factory = new AzureStorageFactory(CloudStorageAccount.DevelopmentStorageAccount);

            _repo         = new WebSiteRepository(factory);
            _webSiteTable = factory.GetTable <WebSiteRow>(typeof(WebSiteRow).Name);
            _bindingTable = factory.GetTable <BindingRow>(typeof(BindingRow).Name);

            // Clean up IIS and table storage to prepare for test
            using (var serverManager = new ServerManager())
            {
                _excludedSites = new List <string>();
                using (var manager = new ServerManager())
                {
                    manager.Sites.Where(s => s.Name != AzureRoleEnvironment.RoleWebsiteName()).ToList().ForEach(s => _excludedSites.Add(s.Name));
                }
                CleanupWebsiteTest(serverManager);
            }

            // Sync Service
            _syncService = new SyncService(
                _repo,
                new SyncStatusRepository(factory),
                CloudStorageAccount.DevelopmentStorageAccount,
                _sitePath,
                _tempPath,
                new string[] { },
                _excludedSites,
                () => true,
                new IISManager(_sitePath, _tempPath, new SyncStatusRepository(factory), new ConsoleFactory(), LoggerLevel.Debug),
                new ConsoleFactory(),
                LoggerLevel.Debug
                );
        }
Пример #20
0
        static async Task Test1Async()
        {
            StorageCredentials  credentials = new StorageCredentials("", "");
            CloudStorageAccount account     = new CloudStorageAccount(credentials, true);
            StorageFactory      factory     = new AzureStorageFactory(account, "ver40", "catalog", new Uri("https://tempuri.org/test"));

            Console.WriteLine(factory);

            Storage storage = factory.Create();

            StorageContent content = new StringStorageContent("TEST");
            await storage.Save(new Uri(storage.BaseAddress, "doc1.txt"), content);
        }
Пример #21
0
        public override void Init(IServiceContainer serviceContainer, IDictionary <string, string> jobArgsDictionary)
        {
            base.Init(serviceContainer, jobArgsDictionary);

            Configuration = _serviceProvider.GetRequiredService <IOptionsSnapshot <InitializationConfiguration> >().Value;

            SmtpClient = CreateSmtpClient(Configuration.SmtpUri);

            var storageAccount = CloudStorageAccount.Parse(Configuration.DataStorageAccount);
            var storageFactory = new AzureStorageFactory(storageAccount, Configuration.ContainerName, LoggerFactory);

            Storage = storageFactory.Create();
        }
Пример #22
0
        public async Task <ActionResult> ChangeIcon(ChangeIconViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            var    iconBytes = Convert.FromBase64String(model.IconBase64);
            var    container = AzureStorageFactory.GetBlobContainer("werewolfkill", true);
            string blobName  = string.Format("icon/{0}.png", HashValue.md5(iconBytes));
            await container.UploadBlob(blobName, iconBytes);

            ViewData["Message"] = "Success";
            return(PartialView());
        }
Пример #23
0
        public override bool Init(IDictionary <string, string> jobArgsDictionary)
        {
            try
            {
                var instrumentationKey = JobConfigurationManager.TryGetArgument(jobArgsDictionary, JobArgumentNames.InstrumentationKey);
                ApplicationInsights.Initialize(instrumentationKey);

                var loggerConfiguration = LoggingSetup.CreateDefaultLoggerConfiguration(ConsoleLogOnly);
                var loggerFactory       = LoggingSetup.CreateLoggerFactory(loggerConfiguration);
                _logger = loggerFactory.CreateLogger <Job>();

                _whatIf = JobConfigurationManager.TryGetBoolArgument(jobArgsDictionary, JobArgumentNames.WhatIf);

                var databaseConnectionString = JobConfigurationManager.GetArgument(jobArgsDictionary, JobArgumentNames.GalleryDatabase);
                _galleryDatabase = new SqlConnectionStringBuilder(databaseConnectionString);

                _galleryBrand      = JobConfigurationManager.GetArgument(jobArgsDictionary, MyJobArgumentNames.GalleryBrand);
                _galleryAccountUrl = JobConfigurationManager.GetArgument(jobArgsDictionary, MyJobArgumentNames.GalleryAccountUrl);

                _mailFrom = JobConfigurationManager.GetArgument(jobArgsDictionary, JobArgumentNames.MailFrom);

                var smtpConnectionString = JobConfigurationManager.GetArgument(jobArgsDictionary, JobArgumentNames.SmtpUri);
                var smtpUri = new SmtpUri(new Uri(smtpConnectionString));
                _smtpClient = CreateSmtpClient(smtpUri);

                _warnDaysBeforeExpiration = JobConfigurationManager.TryGetIntArgument(jobArgsDictionary, MyJobArgumentNames.WarnDaysBeforeExpiration)
                                            ?? _warnDaysBeforeExpiration;

                _allowEmailResendAfterDays = JobConfigurationManager.TryGetIntArgument(jobArgsDictionary, MyJobArgumentNames.AllowEmailResendAfterDays)
                                             ?? _allowEmailResendAfterDays;

                var storageConnectionString = JobConfigurationManager.GetArgument(jobArgsDictionary, JobArgumentNames.DataStorageAccount);
                var storageContainerName    = JobConfigurationManager.GetArgument(jobArgsDictionary, JobArgumentNames.ContainerName);

                var csa            = CloudStorageAccount.Parse(storageConnectionString);
                var storageFactory = new AzureStorageFactory(csa, storageContainerName, loggerFactory);
                _storage = storageFactory.Create();
            }
            catch (Exception exception)
            {
                _logger.LogCritical(LogEvents.JobInitFailed, exception, "Failed to initialize job!");

                return(false);
            }

            return(true);
        }
Пример #24
0
        public BaseAzureTableStorageTester()
        {
            Entity          = Mock.Of <RiverEntity>();
            ARiver          = Mock.Of <River>(r => r.Name == GetRandomRiverNameFroMock());
            AccountMock     = new Mock <ICloudStorageAccount>();
            TableClientMock = new Mock <CloudTableClient>(new Uri("https://www.google.com"), new StorageCredentials());
            TableMock       = new Mock <CloudTable>(new Uri("https://www.google.com"));

            TableClientMock.Setup(tc => tc.GetTableReference(It.IsAny <string>())).Returns(TableMock.Object);

            AccountMock.Setup(c => c.CreateCloudTableClient()).Returns(TableClientMock.Object);
            Fac = new AzureStorageFactory(AccountMock.Object)
            {
                PartitionKey   = "TACOS",
                CollectionName = "Pizza"
            };
        }
Пример #25
0
        public static async Task Test1Async()
        {
            CloudStorageAccount account = CloudStorageAccount.Parse("");

            AzureStorageFactory storageFactory = new AzureStorageFactory(account, "registration");

            string contentBaseAddress = "http://tempuri.org/content";

            CommitCollector collector = new RegistrationCatalogCollector(new Uri(source),
                                                                         storageFactory)
            {
                ContentBaseAddress = new Uri(contentBaseAddress)
            };
            await collector.Run();

            Console.WriteLine("http requests: {0}", collector.RequestCount);
        }
Пример #26
0
        protected override void ConfigureJobServices(IServiceCollection services, IConfigurationRoot configurationRoot)
        {
            services.Configure <CertificateStoreConfiguration>(configurationRoot.GetSection(CertificateStoreConfigurationSectionName));

            services.AddTransient <ISubscriptionProcessor <SignatureValidationMessage>, SubscriptionProcessor <SignatureValidationMessage> >();

            services.AddScoped <IEntitiesContext>(serviceProvider =>
                                                  new EntitiesContext(
                                                      serviceProvider.GetRequiredService <IOptionsSnapshot <GalleryDbConfiguration> >().Value.ConnectionString,
                                                      readOnly: false));
            services.Add(ServiceDescriptor.Transient(typeof(IEntityRepository <>), typeof(EntityRepository <>)));
            services.AddTransient <ICorePackageService, CorePackageService>();

            services.AddTransient <ITelemetryService, TelemetryService>();

            services.AddTransient <ICertificateStore>(p =>
            {
                var config = p.GetRequiredService <IOptionsSnapshot <CertificateStoreConfiguration> >().Value;
                var targetStorageAccount = CloudStorageAccount.Parse(config.DataStorageAccount);

                var storageFactory = new AzureStorageFactory(targetStorageAccount, config.ContainerName, LoggerFactory.CreateLogger <AzureStorage>());
                var storage        = storageFactory.Create();

                return(new CertificateStore(storage, LoggerFactory.CreateLogger <CertificateStore>()));
            });

            services.AddTransient <IProcessorPackageFileService, ProcessorPackageFileService>(p => new ProcessorPackageFileService(
                                                                                                  p.GetRequiredService <ICoreFileStorageService>(),
                                                                                                  typeof(PackageSigningValidator),
                                                                                                  p.GetRequiredService <ILogger <ProcessorPackageFileService> >()));

            services.AddTransient <IBrokeredMessageSerializer <SignatureValidationMessage>, SignatureValidationMessageSerializer>();
            services.AddTransient <IMessageHandler <SignatureValidationMessage>, SignatureValidationMessageHandler>();
            services.AddTransient <IPackageSigningStateService, PackageSigningStateService>();
            services.AddTransient <ISignaturePartsExtractor, SignaturePartsExtractor>();

            services.AddTransient <ISignatureValidator, SignatureValidator>(p => new SignatureValidator(
                                                                                p.GetRequiredService <IPackageSigningStateService>(),
                                                                                PackageSignatureVerifierFactory.CreateMinimal(),
                                                                                PackageSignatureVerifierFactory.CreateFull(),
                                                                                p.GetRequiredService <ISignaturePartsExtractor>(),
                                                                                p.GetRequiredService <IProcessorPackageFileService>(),
                                                                                p.GetRequiredService <ICorePackageService>(),
                                                                                p.GetRequiredService <ITelemetryService>(),
                                                                                p.GetRequiredService <ILogger <SignatureValidator> >()));
        }
Пример #27
0
        public async void ReturnsListKeyValuePair()
        {
            var mock = GetTableQuerySegments();

            TableMock.Setup(tt => tt.ExistsAsync()).ReturnsAsync(true);

            TableMock.Setup(tt => tt.ExecuteQuerySegmentedAsync(It.IsAny <TableQuery>(), It.IsAny <TableContinuationToken>()))
            .ReturnsAsync(mock);
            var fac = new AzureStorageFactory(AccountMock.Object)
            {
                CollectionName = "RiversUnitedStates"
            };
            var query = new TableQuery()
                        .Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, "search"));
            var stuff = await fac.GetAsync <List <KeyValuePair <string, string> > >(query);

            Assert.IsType <List <KeyValuePair <string, string> > > (stuff);
        }
 public void Setup()
 {
     var factory = new AzureStorageFactory(CloudStorageAccount.DevelopmentStorageAccount);
     _repository = new WebSiteRepository(factory);
     _webSiteTable = factory.GetTable<WebSiteRow>(typeof(WebSiteRow).Name);
     _bindingTable = factory.GetTable<BindingRow>(typeof(BindingRow).Name);
 }
Пример #29
0
        static void Main(string[] args)
        {
            Console.WriteLine("This is a simple program to copy the sample data to your Windows Azure storage account. This can take some time, depending on your network speed. Make sure you have changed the data connection string to point to your storage account.");

            // this could be easily re-written to use batching in the client storage api,
            // but I wanted to be consistent with how we access table storage through the sample.
            // And you will likely only run this once.

            AzureTable<Store> _Stores;
            AzureTable<ZipStore> _ZipCodes;
            AppSettingsReader myAppSettings = new AppSettingsReader();
            const int numberOfStores = 1000;
            const int numberOfZipCodes = 42192;

            var factory = new AzureStorageFactory(CloudStorageAccount.Parse((string)myAppSettings.GetValue("DataConnectionString", typeof(string))));

            _Stores = (AzureTable<Store>)factory.GetTable<Store>(FBwithWA.Domain.AzureConstants.StoreTableName);
            _Stores.Initialize();

            _ZipCodes = (AzureTable<ZipStore>)factory.GetTable<ZipStore>(FBwithWA.Domain.AzureConstants.ZipStoreTableName);
            _ZipCodes.Initialize();

            Console.WriteLine("Load stores..." + DateTime.Now.ToShortTimeString());
            using (CsvFileReader reader = new CsvFileReader(@"Store_List.csv"))
            {
                int count = 0;
                CsvRow row = new CsvRow();
                while (reader.ReadRow(row))
                {
                    //row headers: PartitionKey,RowKey,Name,City,State,Zip
                    Store aStore = new Store
                    {
                        PartitionKey = row[0],
                        RowKey = row[1],
                        Name = row[2],
                        City = row[3],
                        State = row[4],
                        Zip = row[5]
                    };
                    _Stores.AddOrUpdate(aStore);
                    Console.WriteLine(string.Format("Completed: {0} of {1} stores", count.ToString(), numberOfStores));
                    count++;
                }
            }
            Console.WriteLine("Load stores done. " + DateTime.Now.ToShortTimeString());

            // load zip array
            Console.WriteLine("Load zip code data..." + DateTime.Now.ToShortTimeString());

            using (CsvFileReader reader = new CsvFileReader(@"Zip_Map.csv"))
            {
                int count = 0;
                CsvRow row = new CsvRow();
                while (reader.ReadRow(row))
                {
                    ZipStore aZipCode = new ZipStore
                    {
                        // file format: PartitionKey,RowKey,zip,store1,store2,store3
                        PartitionKey = row[0],
                        RowKey = row[1],
                        store1 = row[3],
                        store2 = row[4],
                        store3 = row[5]
                    };
                    _ZipCodes.AddOrUpdate(aZipCode);
                    Console.WriteLine(string.Format("Completed: {0} of {1} zip codes", count.ToString(), numberOfZipCodes));
                    count++;
                }
            }
            Console.WriteLine("Load zip codes done. " + DateTime.Now.ToShortTimeString());
            Console.WriteLine("Prese enter to exit.");
            Console.ReadLine();
        }
Пример #30
0
 public ContactRepository()
 {
     var factory = new AzureStorageFactory(CloudStorageAccount.FromConfigurationSetting("DataConnectionString"));
     _table = (AzureTable<Contact>) factory.GetTable<Contact>(FBwithWA.Domain.AzureConstants.ContactTableName);
 }
Пример #31
0
        public void Update_sites_removing_bindings()
        {
            var fabrikamWebSite = new WebSite
            {
                Name = FabrikamWebSiteName,
                Bindings = new List<Binding>
                {
                    new Binding
                    {
                        Protocol = "https",
                        IpAddress = "127.0.0.1",
                        Port = 8443,
                        CertificateThumbprint = "12345"
                    },
                    new Binding
                    {
                        Protocol = "http",
                        IpAddress = "127.0.0.1",
                        Port = 8082
                    }
                }
            };

            var factory = new AzureStorageFactory(CloudStorageAccount.DevelopmentStorageAccount);
            var iisManager = new IISManager(LocalSitesPath, TempSitesPath, new SyncStatusRepository(factory), new ConsoleFactory(), LoggerLevel.Debug);
            var sites = new List<WebSite> {fabrikamWebSite};

            iisManager.UpdateSites(sites, _excludedSites);

            var fabrikam = RetrieveWebSite(FabrikamWebSiteName);

            Assert.IsNotNull(fabrikam);
            Assert.AreEqual(fabrikamWebSite.Name, fabrikam.Name);
            Assert.AreEqual(2, fabrikam.Bindings.Count);

            var fabrikamBindings = fabrikamWebSite.Bindings.ToList();
            fabrikamBindings.RemoveAt(1);
            fabrikamWebSite.Bindings = fabrikamBindings;

            iisManager.UpdateSites(sites, _excludedSites);

            // Asserts
            Assert.AreEqual(sites.Count(), RetrieveWebSites().Count() - _excludedSites.Count);

            fabrikam = RetrieveWebSite(FabrikamWebSiteName);

            Assert.IsNotNull(fabrikam);
            Assert.AreEqual(fabrikamWebSite.Name, fabrikam.Name);
            Assert.AreEqual(1, fabrikam.Bindings.Count);

            Assert.IsTrue(string.IsNullOrEmpty(fabrikam.Bindings.First().Host));
            Assert.AreEqual(fabrikamWebSite.Bindings.First().Protocol, fabrikam.Bindings.First().Protocol);
            Assert.AreEqual(fabrikamWebSite.Bindings.First().IpAddress, fabrikam.Bindings.First().EndPoint.Address.ToString());
            Assert.AreEqual(fabrikamWebSite.Bindings.First().Port, fabrikam.Bindings.First().EndPoint.Port);
            // todo: Figure out why these don't work!
            //Assert.AreEqual(StoreName.My.ToString().ToUpperInvariant(), fabrikam.Bindings.First().CertificateStoreName.ToUpperInvariant());
            //Assert.IsNotNull(fabrikam.Bindings.First().CertificateHash);
        }
Пример #32
0
        public void Update_sites_removing_site()
        {
            var contosoWebSite = new WebSite
            {
                Name = ContosoWebSiteName,
                Bindings = new List<Binding>
                {
                    new Binding
                    {
                        Protocol = "http",
                        IpAddress = "127.0.0.1",
                        Port = 8081,
                        HostName = "contoso.com"
                    }
                }
            };

            var fabrikamWebSite = new WebSite
            {
                Name = FabrikamWebSiteName,
                Bindings = new List<Binding>
                {
                    new Binding
                    {
                        Protocol = "https",
                        IpAddress = "127.0.0.1",
                        Port = 8443,
                        CertificateThumbprint = "12345"
                    }
                }
            };

            var factory = new AzureStorageFactory(CloudStorageAccount.DevelopmentStorageAccount);
            var iisManager = new IISManager(LocalSitesPath, TempSitesPath, new SyncStatusRepository(factory), new ConsoleFactory(), LoggerLevel.Debug);
            var sites = new List<WebSite> {contosoWebSite, fabrikamWebSite};

            iisManager.UpdateSites(sites, _excludedSites);

            Assert.AreEqual(2, RetrieveWebSites().Count() - _excludedSites.Count);

            sites.RemoveAt(0);
            iisManager.UpdateSites(sites, _excludedSites);

            // Asserts
            Assert.AreEqual(1, RetrieveWebSites().Count() - _excludedSites.Count);

            Site contoso = RetrieveWebSite(ContosoWebSiteName);
            Site fabrikam = RetrieveWebSite(FabrikamWebSiteName);

            Assert.IsNull(contoso);
            Assert.IsNotNull(fabrikam);
        }
Пример #33
0
        public void Update_sites_adding_bindings()
        {
            var contosoWebSite = new WebSite
            {
                Name = ContosoWebSiteName,
                Bindings = new List<Binding>
                {
                    new Binding
                    {
                        Protocol = "http",
                        IpAddress = "10.0.0.1",
                        Port = 8081,
                        HostName = "contoso.com"
                    }
                }
            };

            var factory = new AzureStorageFactory(CloudStorageAccount.DevelopmentStorageAccount);
            var iisManager = new IISManager(LocalSitesPath, TempSitesPath, new SyncStatusRepository(factory), new ConsoleFactory(), LoggerLevel.Debug);
            var sites = new List<WebSite> {contosoWebSite};

            iisManager.UpdateSites(sites, _excludedSites);

            var contoso = RetrieveWebSite(ContosoWebSiteName);

            Assert.IsNotNull(contoso);
            Assert.AreEqual(contosoWebSite.Name, contoso.Name);
            Assert.AreEqual(contosoWebSite.Bindings.Count(), contoso.Bindings.Count);

            // Add a new binding (https)
            var contosoBindings = contosoWebSite.Bindings.ToList();
            contosoBindings.Add(new Binding
                {
                    Protocol = "https",
                    IpAddress = "10.0.0.1",
                    Port = 8443,
                    CertificateThumbprint = "12345"
                }
            );
            contosoWebSite.Bindings = contosoBindings;

            iisManager.UpdateSites(sites, _excludedSites);

            // Asserts
            Assert.AreEqual(sites.Count, RetrieveWebSites().Count() - _excludedSites.Count);

            contoso = RetrieveWebSite(ContosoWebSiteName);

            Assert.IsNotNull(contoso);
            Assert.AreEqual(contosoWebSite.Name, contoso.Name);
            Assert.AreEqual(2, contoso.Bindings.Count);

            Assert.AreEqual(contosoWebSite.Bindings.First().HostName, contoso.Bindings.First().Host);
            Assert.AreEqual(contosoWebSite.Bindings.First().Protocol, contoso.Bindings.First().Protocol);
            Assert.AreEqual(contosoWebSite.Bindings.First().IpAddress, contoso.Bindings.First().EndPoint.Address.ToString());
            Assert.AreEqual(contosoWebSite.Bindings.First().Port, contoso.Bindings.First().EndPoint.Port);
            Assert.IsNull(contoso.Bindings.First().CertificateHash);

            Assert.IsTrue(string.IsNullOrEmpty(contoso.Bindings.Last().Host));
            Assert.AreEqual(contosoWebSite.Bindings.Last().Protocol, contoso.Bindings.Last().Protocol);
            Assert.AreEqual(contosoWebSite.Bindings.Last().IpAddress, contoso.Bindings.Last().EndPoint.Address.ToString());
            Assert.AreEqual(contosoWebSite.Bindings.Last().Port, contoso.Bindings.Last().EndPoint.Port);
            // todo: Figure out why these don't work!
            //Assert.AreEqual(StoreName.My.ToString().ToUpperInvariant(), contoso.Bindings.Last().CertificateStoreName.ToUpperInvariant());
            //Assert.IsNotNull(contoso.Bindings.Last().CertificateHash);
        }
Пример #34
0
 public ContactQueue()
 {
     var factory = new AzureStorageFactory();
     _queue = (AzureQueue<ContactQueueMessage>)factory.GetQueue<ContactQueueMessage>(AzureConstants.ContactQueueName);
 }
Пример #35
0
        protected override void FixtureSetup()
        {
            base.FixtureSetup();

            // RoleEnvironment
            AzureRoleEnvironment.DeploymentId = () => "DEPLOYMENTID";
            AzureRoleEnvironment.CurrentRoleInstanceId = () => "ROLEINSTANCEID";

            // File Resource Paths
            var basePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase.Replace("file:///", ""));
            _sitePath = Path.Combine(basePath, "Sites");
            _tempPath = Path.Combine(basePath, "Temp");
            _configPath = Path.Combine(basePath, "Config");
            _resourcesPath = Path.Combine(basePath, "_resources");
            Directory.CreateDirectory(_sitePath);
            Directory.CreateDirectory(_tempPath);
            Directory.CreateDirectory(_configPath);

            // Website Repository
            var factory = new AzureStorageFactory(CloudStorageAccount.DevelopmentStorageAccount);
            _repo = new WebSiteRepository(factory);
            _webSiteTable = factory.GetTable<WebSiteRow>(typeof(WebSiteRow).Name);
            _bindingTable = factory.GetTable<BindingRow>(typeof(BindingRow).Name);

            // Clean up IIS and table storage to prepare for test
            using (var serverManager = new ServerManager())
            {
                _excludedSites = new List<string>();
                using (var manager = new ServerManager())
                {
                    manager.Sites.Where(s => s.Name != AzureRoleEnvironment.RoleWebsiteName()).ToList().ForEach(s => _excludedSites.Add(s.Name));
                }
                CleanupWebsiteTest(serverManager);
            }

            // Sync Service
            _syncService = new SyncService(
                _repo,
                new SyncStatusRepository(factory),
                CloudStorageAccount.DevelopmentStorageAccount,
                _sitePath,
                _tempPath,
                new string[] { },
                _excludedSites,
                () => true,
                new IISManager(_sitePath, _tempPath, new SyncStatusRepository(factory), new ConsoleFactory(), LoggerLevel.Debug),
                new ConsoleFactory(),
                LoggerLevel.Debug
            );
        }
Пример #36
0
 public RoleStore(string roleTableName)
 {
     m_roleTable = AzureStorageFactory.GetTable(roleTableName, true);
 }
Пример #37
0
        static void Main(string[] args)
        {
            var config = new ConfigurationBuilder()
                         .SetBasePath(Environment.CurrentDirectory)
                         .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                         .AddEnvironmentVariables()
                         .Build()
                         .Get <RiverRepositoryConfig>();



            var account      = new CloudStorageAccountBuilder(config.StorageConnection);
            var azureFactory = new AzureStorageFactory(account);

            azureFactory.CollectionName = config.RiverTable;
            var client = new HttpClient();
            var repo   = new RiverRepository(azureFactory, client);

            repo.Register(config);

            var rivers = new List <River>();

            using (var file = new FileStream(config.RiverFile, FileMode.Open))
                using (var reader = new StreamReader(file))
                {
                    var json = reader.ReadToEnd();
                    rivers = JsonConvert.DeserializeObject <List <River> >(json);
                }
            LoadTableStore(repo, rivers);


            // rivers.ForEach(r =>
            // {
            //     r.Id = r.BuildRiverIdHash();
            // });
            // var stuff = JsonConvert.SerializeObject(rivers);
            // using(StreamWriter file = File.CreateText("../../../riverswithid.json"))
            // {
            //     JsonSerializer serializer = new JsonSerializer();
            //     serializer.Serialize(file, stuff);
            // }

            // var states = rivers.Select((r, code) => r.StateCode).Distinct();
            // foreach(var state in states)
            // {
            //     var stateRivers  = rivers.Where(x => x.StateCode.Equals(state)).Distinct();
            //     using(var hasher = MD5.Create())
            //     {
            //         stateRivers.ToList().ForEach(r =>
            //         {
            //             var bytes = hasher.ComputeHash(Encoding.UTF8.GetBytes($"{r.StateCode}{r.RiverId}"));
            //             var builder = new StringBuilder();
            //             for(var x =0; x < bytes.Length; x++)
            //             {
            //                 builder.Append(bytes[x].ToString("x2"));
            //             }
            //             r.Id = builder.ToString();
            //         });
            //     }
            //     // BuildAzureSearchIndex(stateRivers, client, config.AzureSearchAdminKey, config.AzureSearchAdminUrl).GetAwaiter().GetResult();
            // }
        }
Пример #38
0
        public void Update_sites_with_initial_bindings()
        {
            var contosoWebSite = new WebSite
            {
                Name     = ContosoWebSiteName,
                Bindings = new List <Binding>
                {
                    new Binding
                    {
                        Protocol  = "http",
                        IpAddress = "*",
                        Port      = 8081,
                        HostName  = "contoso.com"
                    }
                }
            };

            var fabrikamWebSite = new WebSite
            {
                Name     = FabrikamWebSiteName,
                Bindings = new List <Binding>
                {
                    new Binding
                    {
                        Protocol              = "https",
                        IpAddress             = "*",
                        Port                  = 8443,
                        CertificateThumbprint = "12354"
                    },
                    new Binding
                    {
                        Protocol  = "http",
                        IpAddress = "127.0.0.1",
                        Port      = 8082
                    }
                }
            };

            var factory    = new AzureStorageFactory(CloudStorageAccount.DevelopmentStorageAccount);
            var iisManager = new IISManager(LocalSitesPath, TempSitesPath, new SyncStatusRepository(factory), new ConsoleFactory(), LoggerLevel.Debug);
            var sites      = new List <WebSite> {
                contosoWebSite, fabrikamWebSite
            };

            iisManager.UpdateSites(sites, _excludedSites);

            // Asserts
            Assert.AreEqual(sites.Count, RetrieveWebSites().Count() - _excludedSites.Count);

            var contoso = RetrieveWebSite(ContosoWebSiteName);

            Assert.IsNotNull(contoso);
            Assert.AreEqual(contosoWebSite.Name, contoso.Name);
            Assert.AreEqual(contosoWebSite.Bindings.Count(), contoso.Bindings.Count);

            Assert.AreEqual(contosoWebSite.Bindings.First().HostName, contoso.Bindings.First().Host);
            Assert.AreEqual(contosoWebSite.Bindings.First().Protocol, contoso.Bindings.First().Protocol);
            Assert.AreEqual("0.0.0.0", contoso.Bindings.First().EndPoint.Address.ToString());
            Assert.AreEqual(contosoWebSite.Bindings.First().Port, contoso.Bindings.First().EndPoint.Port);
            Assert.IsNull(contoso.Bindings.First().CertificateHash);

            var fabrikam = RetrieveWebSite(FabrikamWebSiteName);

            Assert.IsNotNull(fabrikam);
            Assert.AreEqual(fabrikamWebSite.Name, fabrikam.Name);
            Assert.AreEqual(fabrikamWebSite.Bindings.Count(), fabrikam.Bindings.Count);

            Assert.IsTrue(string.IsNullOrEmpty(fabrikam.Bindings.First().Host));
            Assert.AreEqual(fabrikamWebSite.Bindings.First().Protocol, fabrikam.Bindings.First().Protocol);
            Assert.AreEqual(string.Empty, fabrikam.Bindings.First().Host);
            Assert.AreEqual("0.0.0.0", fabrikam.Bindings.First().EndPoint.Address.ToString());
            Assert.AreEqual(fabrikamWebSite.Bindings.First().Port, fabrikam.Bindings.First().EndPoint.Port);
            // todo: Figure out why these don't work!
            //Assert.AreEqual(StoreName.My.ToString().ToUpperInvariant(), fabrikam.Bindings.First().CertificateStoreName.ToUpperInvariant());
            //Assert.IsNotNull(fabrikam.Bindings.First().CertificateHash);

            Assert.IsTrue(string.IsNullOrEmpty(fabrikam.Bindings.Last().Host));
            Assert.AreEqual(fabrikamWebSite.Bindings.Last().Protocol, fabrikam.Bindings.Last().Protocol);
            Assert.AreEqual(fabrikamWebSite.Bindings.Last().IpAddress, fabrikam.Bindings.Last().EndPoint.Address.ToString());
            Assert.AreEqual(fabrikamWebSite.Bindings.Last().Port, fabrikam.Bindings.Last().EndPoint.Port);
            Assert.IsNull(fabrikam.Bindings.Last().CertificateHash);
        }
Пример #39
0
 public StoreRepository()
 {
     var factory = new AzureStorageFactory();
     _zipStore = (AzureTable<ZipStore>)factory.GetTable<ZipStore>(FBwithWA.Domain.AzureConstants.ZipStoreTableName);
     _store = (AzureTable<Store>)factory.GetTable<Store>(FBwithWA.Domain.AzureConstants.StoreTableName);
 }
Пример #40
0
        public void Instantiate()
        {
            var fac = new AzureStorageFactory(AccountMock.Object);

            Assert.NotNull(fac);
        }