public void Deserialize_BadJson() { // Arrange (propertySources array bad!) var environment = @" { 'name': 'testname', 'profiles': ['Production'], 'label': 'testlabel', 'version': 'testversion', 'propertySources': [ { 'name': 'source', 'source': { 'key1': 'value1', 'key2': 10 } } }"; ConfigServerConfigurationProvider provider = new ConfigServerConfigurationProvider(new ConfigServerClientSettings()); Stream stream = TestHelpers.StringToStream(environment); // Act and Assert ConfigEnvironment env = provider.Deserialize(stream); Assert.Null(env); }
public void Delete() { var item = new ConfigEnvironment(new EnvironmentIdentifier("Foo", "Bar")); item.ApplyEvent(new ReplayedEvent { DomainEvent = new EnvironmentCreated(new EnvironmentIdentifier("Foo", "Bar")), UtcTime = DateTime.UtcNow, Version = 1 }); item.ApplyEvent(new ReplayedEvent { DomainEvent = new EnvironmentKeysImported(new EnvironmentIdentifier("Foo", "Bar"), new[] { ConfigKeyAction.Set("Jar", "Jar", "Jar", "Jar") }), UtcTime = DateTime.UtcNow, Version = 1 }); item.Delete(); Assert.True(item.Deleted, "item.Deleted"); Assert.False(item.Created, "item.Created"); Assert.Empty(item.Keys); Assert.Empty(item.KeyPaths); }
public async void RemoteLoadAsync_ConfigServerReturnsLessThanBadRequest() { // Arrange IHostingEnvironment envir = new HostingEnvironment(); TestConfigServerStartup.Reset(); TestConfigServerStartup.ReturnStatus = new int[] { 204 }; var builder = new WebHostBuilder().UseStartup <TestConfigServerStartup>().UseEnvironment(envir.EnvironmentName); var server = new TestServer(builder); ConfigServerClientSettings settings = new ConfigServerClientSettings { Uri = "http://localhost:8888", Name = "myName" }; server.BaseAddress = new Uri(settings.Uri); ConfigServerConfigurationProvider provider = new ConfigServerConfigurationProvider(settings, server.CreateClient()); // Act and Assert ConfigEnvironment result = await provider.RemoteLoadAsync(settings.GetRawUris(), null); Assert.NotNull(TestConfigServerStartup.LastRequest); Assert.Equal("/" + settings.Name + "/" + settings.Environment, TestConfigServerStartup.LastRequest.Path.Value); Assert.Null(result); }
public virtual async Task RetrieveVersionConstrainedSnapshot() { var eventStore = new Mock <IEventStore>(); var nextEventId = 0L; eventStore.Setup(es => es.WriteEvents(It.IsAny <IList <DomainEvent> >())) .ReturnsAsync(() => nextEventId++); var item = new ConfigEnvironment(new EnvironmentIdentifier("Foo", "Bar")); item.Create(); await item.WriteRecordedEvents(eventStore.Object); var firstSnapshot = item.CreateSnapshot(); item.UpdateKeys(new[] { new ConfigEnvironmentKey("Foo", "1", "", "", 1) }); await item.WriteRecordedEvents(eventStore.Object); var secondSnapshot = item.CreateSnapshot(); item.UpdateKeys(new[] { new ConfigEnvironmentKey("Foo", "2", "", "", 2) }); await item.WriteRecordedEvents(eventStore.Object); var thirdSnapshot = item.CreateSnapshot(); await Store.SaveSnapshots(new[] { firstSnapshot, secondSnapshot, thirdSnapshot }); var result = await Store.GetSnapshot(nameof(ConfigEnvironment), item.Identifier.ToString(), 1); Assert.False(result.IsError, "result.IsError"); Assert.Equal(secondSnapshot, result.Data); }
public void Deserialize_BadJson() { // Arrange (propertySources array bad!) var environment = @" { ""name"": ""testname"", ""profiles"": [""Production""], ""label"": ""testlabel"", ""version"": ""testversion"", ""propertySources"": [ { ""name"": ""source"", ""source"": { ""key1"": ""value1"", ""key2"": 10 } } }"; ConfigServerConfigurationProvider provider = new ConfigServerConfigurationProvider(new ConfigServerClientSettings()); Stream stream = TestHelpers.StringToStream(environment); // Act and Assert ConfigEnvironment env = provider.Deserialize(stream); Assert.Null(env); }
public UserFacade(AppDbContext context, ConfigEnvironment config) { _userService = new UserService(context); _invitationKeyService = new InvitationKeyService(context); _emailService = new EmailService(EmailType.BlueGray); _reCaptchaService = new ReCaptchaService(); _config = config; }
public async Task <User> ComputePasswordHashAndAddUser(User user, ConfigEnvironment config) { user.Password = AuthUtilities.ComputeSha256Hash(user.Password, config.Salt); _context.Users.Add(user); await _context.SaveChangesAsync(); return(user); }
public void DeletingNullListFails() { var item = new ConfigEnvironment(new EnvironmentIdentifier("Foo", "Bar")); var result = item.DeleteKeys(null); Assert.True(result.IsError, "result.IsError"); }
public void Initialize() { var options = new DbContextOptionsBuilder <AppDbContext>().UseInMemoryDatabase(Guid.NewGuid().ToString()).Options; _context = new AppDbContext(options); _userService = new UserService(_context); _config = Utility.GetConfig(); }
public void CreateAssignsValues() { var item = new ConfigEnvironment(new EnvironmentIdentifier("Foo", "Bar")); item.Create(); Assert.True(item.Created); Assert.Empty(item.Keys); }
/// <exception cref="T:System.Reflection.TargetInvocationException">On the .NET Framework 4.6.1 and earlier versions only: The algorithm was used with Federal Information Processing Standards (FIPS) mode enabled, but is not FIPS compatible.</exception> /// <exception cref="T:System.FormatException">includes an unsupported specifier. Supported format specifiers are listed in the Remarks section.</exception> /// <exception cref="T:System.ArgumentOutOfRangeException">Enlarging the value of this instance would exceed <see cref="P:System.Text.StringBuilder.MaxCapacity" />.</exception> /// <exception cref="T:System.ArgumentNullException"></exception> /// <exception cref="T:System.ObjectDisposedException">The object has already been disposed.</exception> /// <exception cref="T:System.Text.EncoderFallbackException">A fallback occurred (for more information, see Character Encoding in .NET) /// -and- /// <see cref="P:System.Text.Encoding.EncoderFallback" /> is set to <see cref="T:System.Text.EncoderExceptionFallback" />.</exception> /// <exception cref="T:Microsoft.EntityFrameworkCore.DbUpdateException">An error is encountered while saving to the database.</exception> /// <exception cref="T:Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException">A concurrency violation is encountered while saving to the database. /// A concurrency violation occurs when an unexpected number of rows are affected during save. /// This is usually because the data in the database has been modified since it was loaded into memory.</exception> public async Task <User> ComputePasswordHashAndAddUser(User user, ConfigEnvironment config) { user.Password = AuthUtilities.ComputeSha256Hash(user.Password, config.Salt); await _context.Users.AddAsync(user); _logger.LogInformation($"Registered user with password: {user.Password.Substring(0, 5)}..."); await _context.SaveChangesAsync(); return(user); }
public void CreateValidSnapshot() { var item = new ConfigEnvironment(new EnvironmentIdentifier("FooBar", "Bar")); var snapshot = item.CreateSnapshot(); Assert.Equal(item.CurrentVersion, snapshot.Version); Assert.Equal(item.MetaVersion, snapshot.MetaVersion); Assert.False(string.IsNullOrWhiteSpace(snapshot.Identifier)); Assert.False(string.IsNullOrWhiteSpace(snapshot.JsonData)); Assert.False(string.IsNullOrWhiteSpace(snapshot.DataType)); }
public async void RemoteLoadAsync_ConfigServerReturnsGood() { // Arrange var environment = @" { 'name': 'testname', 'profiles': ['Production'], 'label': 'testlabel', 'version': 'testversion', 'propertySources': [ { 'name': 'source', 'source': { 'key1': 'value1', 'key2': 10 } } ] }"; IHostingEnvironment envir = new HostingEnvironment(); TestConfigServerStartup.Reset(); TestConfigServerStartup.Response = environment; var builder = new WebHostBuilder().UseStartup <TestConfigServerStartup>().UseEnvironment(envir.EnvironmentName); var server = new TestServer(builder); ConfigServerClientSettings settings = new ConfigServerClientSettings { Uri = "http://localhost:8888", Name = "myName" }; server.BaseAddress = new Uri(settings.Uri); ConfigServerConfigurationProvider provider = new ConfigServerConfigurationProvider(settings, server.CreateClient()); // Act and Assert ConfigEnvironment env = await provider.RemoteLoadAsync(settings.GetUris(), null); Assert.NotNull(TestConfigServerStartup.LastRequest); Assert.Equal("/" + settings.Name + "/" + settings.Environment, TestConfigServerStartup.LastRequest.Path.Value); Assert.NotNull(env); Assert.Equal("testname", env.Name); Assert.NotNull(env.Profiles); Assert.Single(env.Profiles); Assert.Equal("testlabel", env.Label); Assert.Equal("testversion", env.Version); Assert.NotNull(env.PropertySources); Assert.Single(env.PropertySources); Assert.Equal("source", env.PropertySources[0].Name); Assert.NotNull(env.PropertySources[0].Source); Assert.Equal(2, env.PropertySources[0].Source.Count); Assert.Equal("value1", env.PropertySources[0].Source["key1"]); Assert.Equal((long)10, env.PropertySources[0].Source["key2"]); }
public void CreateDefault() { var item = new ConfigEnvironment(new EnvironmentIdentifier("Foo", "Bar")); item.Create(true); Assert.True(item.Created); Assert.False(item.Deleted); Assert.True(item.IsDefault); Assert.Empty(item.Keys); Assert.Empty(item.KeyPaths); }
public virtual async Task StoreDomainObjectSnapshot() { var item = new ConfigEnvironment(new EnvironmentIdentifier("Foo", "Bar")); item.Create(); item.ImportKeys(new List <ConfigEnvironmentKey> { new ConfigEnvironmentKey("Jar", "Jar", "", "", 4711) }); var snapshot = item.CreateSnapshot(); var result = await Store.SaveSnapshots(new[] { snapshot }); Assert.False(result.IsError, "result.IsError"); }
public void DeleteKeysChangesValues() { var item = new ConfigEnvironment(new EnvironmentIdentifier("Foo", "Bar")); item.UpdateKeys(new List <ConfigEnvironmentKey> { new ConfigEnvironmentKey("Foo", "Bar", "", "", 0) }); Assert.NotEmpty(item.Keys); item.DeleteKeys(new List <string> { "Foo" }); Assert.Empty(item.Keys); }
public void DeletingInvalidKeysFails() { var item = new ConfigEnvironment(new EnvironmentIdentifier("Foo", "Bar")); item.UpdateKeys(new List <ConfigEnvironmentKey> { new ConfigEnvironmentKey("Foo", "Bar", "", "", 0) }); Assert.NotEmpty(item.Keys); var result = item.DeleteKeys(new List <string> { "Baz" }); Assert.True(result.IsError, "result.IsError"); }
public async Task Deserialize_GoodJsonAsync() { // Arrange var environment = new ConfigEnvironment { Name = "testname", Label = "testlabel", Profiles = new List <string> { "Production" }, Version = "testversion", State = "teststate", PropertySources = new List <PropertySource> { new PropertySource { Name = "source", Source = new Dictionary <string, object> { { "key1", "value1" }, { "key2", 10 } } } } }; var provider = new ConfigServerConfigurationProvider(); var content = JsonContent.Create(environment); // Act and Assert var env = await content.ReadFromJsonAsync <ConfigEnvironment>(provider.SerializerOptions); Assert.NotNull(env); Assert.Equal("testname", env.Name); Assert.NotNull(env.Profiles); Assert.Single(env.Profiles); Assert.Equal("testlabel", env.Label); Assert.Equal("testversion", env.Version); Assert.Equal("teststate", env.State); Assert.NotNull(env.PropertySources); Assert.Single(env.PropertySources); Assert.Equal("source", env.PropertySources[0].Name); Assert.NotNull(env.PropertySources[0].Source); Assert.Equal(2, env.PropertySources[0].Source.Count); Assert.Equal("value1", env.PropertySources[0].Source["key1"].ToString()); Assert.Equal(10L, long.Parse(env.PropertySources[0].Source["key2"].ToString())); }
public virtual async Task RetrieveDomainObjectSnapshot() { var item = new ConfigEnvironment(new EnvironmentIdentifier("Foo", "Bar")); item.Create(); item.ImportKeys(new List <ConfigEnvironmentKey> { new ConfigEnvironmentKey("Jar", "Jar", "", "", 4711) }); var snapshot = item.CreateSnapshot(); await Store.SaveSnapshots(new[] { snapshot }); var result = await Store.GetSnapshot <ConfigEnvironment>(new EnvironmentIdentifier("Foo", "Bar").ToString()); Assert.False(result.IsError, "result.IsError"); Assert.NotNull(result.Data); Assert.Equal(snapshot, result.Data); }
/// <exception cref="T:System.Reflection.TargetInvocationException">On the .NET Framework 4.6.1 and earlier versions only: The algorithm was used with Federal Information Processing Standards (FIPS) mode enabled, but is not FIPS compatible.</exception> /// <exception cref="T:System.FormatException">includes an unsupported specifier. Supported format specifiers are listed in the Remarks section.</exception> /// <exception cref="T:System.ArgumentOutOfRangeException">Enlarging the value of this instance would exceed <see cref="P:System.Text.StringBuilder.MaxCapacity" />.</exception> /// <exception cref="T:System.ArgumentNullException"></exception> /// <exception cref="T:System.ObjectDisposedException">The object has already been disposed.</exception> /// <exception cref="T:System.Text.EncoderFallbackException">A fallback occurred (for more information, see Character Encoding in .NET) /// -and- /// <see cref="P:System.Text.Encoding.EncoderFallback" /> is set to <see cref="T:System.Text.EncoderExceptionFallback" />.</exception> /// <exception cref="T:System.InvalidOperationException">(Asynchronous) The sequence contains more than one element that satisfies the condition in the predicate.</exception> /// <exception cref="T:WebApi.Services.AdminNotFoundException">Admin not found in database!</exception> public async Task <User> CheckCredentials(string login, string password, ConfigEnvironment config) { var generatedHash = AuthUtilities.ComputeSha256Hash(password, config.Salt); var user = await _context.Users.SingleOrDefaultAsync(c => c.Login.Trim() == login); if (user == null) { _logger.LogError($"Admin not found in database. Login: {login}"); throw new AdminNotFoundException("Admin not found in database!"); } var hashAssert = user.Password == generatedHash; if (!hashAssert) { _logger.LogError($"Wrong password for user {login}. " + $"Provided hash: {generatedHash.Substring(0, 5)}... " + $"Stored hash: {user.Password.Substring(0, 5)}..."); } return(hashAssert ? user : null); }
public void Deserialize_GoodJson() { // Arrange var environment = @" { 'name': 'testname', 'profiles': ['Production'], 'label': 'testlabel', 'version': 'testversion', 'propertySources': [ { 'name': 'source', 'source': { 'key1': 'value1', 'key2': 10 } } ] }"; IHostingEnvironment envir = new HostingEnvironment(); ConfigServerConfigurationProvider provider = new ConfigServerConfigurationProvider(new ConfigServerClientSettings(), envir); Stream stream = TestHelpers.StringToStream(environment); // Act and Assert ConfigEnvironment env = provider.Deserialize(stream); Assert.NotNull(env); Assert.Equal("testname", env.Name); Assert.NotNull(env.Profiles); Assert.Equal(1, env.Profiles.Count); Assert.Equal("testlabel", env.Label); Assert.Equal("testversion", env.Version); Assert.NotNull(env.PropertySources); Assert.Equal(1, env.PropertySources.Count); Assert.Equal("source", env.PropertySources[0].Name); Assert.NotNull(env.PropertySources[0].Source); Assert.Equal(2, env.PropertySources[0].Source.Count); Assert.Equal("value1", env.PropertySources[0].Source["key1"]); Assert.Equal((long)10, env.PropertySources[0].Source["key2"]); }
public void Deserialize_GoodJson() { // Arrange var environment = @" { ""name"": ""testname"", ""profiles"": [""Production""], ""label"": ""testlabel"", ""version"": ""testversion"", ""propertySources"": [ { ""name"": ""source"", ""source"": { ""key1"": ""value1"", ""key2"": 10 } } ] }"; ConfigServerConfigurationProvider provider = new ConfigServerConfigurationProvider(new ConfigServerClientSettings()); Stream stream = TestHelpers.StringToStream(environment); // Act and Assert ConfigEnvironment env = provider.Deserialize(stream); Assert.NotNull(env); Assert.Equal("testname", env.Name); Assert.NotNull(env.Profiles); Assert.Single(env.Profiles); Assert.Equal("testlabel", env.Label); Assert.Equal("testversion", env.Version); Assert.NotNull(env.PropertySources); Assert.Single(env.PropertySources); Assert.Equal("source", env.PropertySources[0].Name); Assert.NotNull(env.PropertySources[0].Source); Assert.Equal(2, env.PropertySources[0].Source.Count); Assert.Equal("value1", env.PropertySources[0].Source["key1"]); Assert.Equal(10L, env.PropertySources[0].Source["key2"]); }
public virtual async Task GetLatestSnapshotNumbers() { var esMock = new Mock <IEventStore>(MockBehavior.Strict); esMock.Setup(es => es.WriteEvents(It.IsAny <IList <DomainEvent> >())) .ReturnsAsync(1) .Verifiable("Events not written to EventStore"); var item = new ConfigEnvironment(new EnvironmentIdentifier("Foo", "Bar")); item.Create(); await item.WriteRecordedEvents(esMock.Object); var snapshot = item.CreateSnapshot(); await Store.SaveSnapshots(new[] { snapshot }); var result = await Store.GetLatestSnapshotNumbers(); Assert.False(result.IsError, "result.IsError"); Assert.Equal(1, result.Data); }
/// <summary> /// 加载Config /// </summary> /// <param name="environment">Config依赖配置</param> /// <param name="args">命令行参数,可以覆盖配置文件的信息</param> /// <returns>Config,环境名</returns> public static IConfiguration LoadConfig(ConfigEnvironment environment, string[] args) { var configBuilder = new ConfigurationBuilder(); string configPath = Environment.GetEnvironmentVariable(environment.EnvConfigPath); string configNamesStr = Environment.GetEnvironmentVariable(environment.EnvConfigNames); // update if (!string.IsNullOrEmpty(configNamesStr)) { var configNames = configNamesStr.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Distinct().ToList(); if (!string.IsNullOrEmpty(configPath)) { configPath = configPath.TrimEnd('/').TrimEnd('\\') + "/"; configBuilder.SetBasePath(configPath); } configNames?.ForEach(configName => { configBuilder.AddJsonFile(configName); }); } // old else { string envName = GetEnvOrConfig(environment.EnvName, string.Empty); string pathName = GetEnvOrConfig(environment.EnvConfigPath, environment.ConfigPath); envName = string.IsNullOrEmpty(envName) ? string.Empty : "." + envName; pathName = string.IsNullOrEmpty(pathName) ? string.Empty : pathName + "/"; string configName = $"{pathName}appsettings{envName}.json"; configBuilder.AddJsonFile(configName); } configBuilder.AddEnvironmentVariables().AddCommandLine(args); return(configBuilder.Build()); }
/// <summary> /// Initializes a new instance of the <see cref="ActiveDirectoryGALConnectorDocumenter"/> class. /// </summary> /// <param name="pilotXml">The pilot configuration XML.</param> /// <param name="productionXml">The production configuration XML.</param> /// <param name="connectorName">The name.</param> /// <param name="configEnvironment">The environment in which the config element exists.</param> public ActiveDirectoryGALConnectorDocumenter(XElement pilotXml, XElement productionXml, string connectorName, ConfigEnvironment configEnvironment) : base(pilotXml, productionXml, connectorName, configEnvironment) { Logger.Instance.WriteMethodEntry(); try { } finally { Logger.Instance.WriteMethodExit(); } }
public void CalculateCacheSize() { var item = new ConfigEnvironment(new EnvironmentIdentifier("Foo", "Bar")); Assert.NotInRange(item.CalculateCacheSize(), long.MinValue, 0); }
public void CreateSnapshot() { var item = new ConfigEnvironment(new EnvironmentIdentifier("Foo", "Bar")); Assert.NotNull(item.CreateSnapshot()); }
public UserController(DbContextOptions <AppDbContext> options, IOptions <ConfigEnvironment> config, ILogger <UserController> logger) { _config = config.Value; _context = new AppDbContext(options); _userService = new UserService(_context, logger); }
/// <summary> /// Initializes a new instance of the <see cref="PowerShellConnectorDocumenter"/> class. /// </summary> /// <param name="pilotXml">The pilot configuration XML.</param> /// <param name="productionXml">The production configuration XML.</param> /// <param name="connectorName">The name.</param> /// <param name="configEnvironment">The environment in which the config element exists.</param> public PowerShellConnectorDocumenter(XElement pilotXml, XElement productionXml, string connectorName, ConfigEnvironment configEnvironment) : base(pilotXml, productionXml, connectorName, configEnvironment) { Logger.Instance.WriteMethodEntry(); try { this.ReportFileName = Documenter.GetTempFilePath(this.ConnectorName + ".tmp.html"); this.ReportToCFileName = Documenter.GetTempFilePath(this.ConnectorName + ".TOC.tmp.html"); } finally { Logger.Instance.WriteMethodExit(); } }
/// <summary> /// Processes the connector configuration of specified connector. /// </summary> /// <param name="connector"> The connector config node</param> /// <param name="configEnvironment">The config environment.</param> private void ProcessConnectorConfiguration(XElement connector, ConfigEnvironment configEnvironment) { Logger.Instance.WriteMethodEntry(); try { var connectorName = (string)connector.Element("name"); var connectorCategory = (string)connector.Element("category"); ConnectorDocumenter connectorDocumenter; switch (connectorCategory.ToUpperInvariant()) { case "AD": connectorDocumenter = new ActiveDirectoryConnectorDocumenter(this.PilotXml, this.ProductionXml, connectorName, configEnvironment); break; case "EXTENSIBLE2": { var connectorSubType = (string)connector.Element("subtype"); switch (connectorSubType.ToUpperInvariant()) { case "WINDOWS AZURE ACTIVE DIRECTORY (MICROSOFT)": connectorDocumenter = new AzureActiveDirectoryConnectorDocumenter(this.PilotXml, this.ProductionXml, connectorName, configEnvironment); break; case "POWERSHELL (MICROSOFT)": connectorDocumenter = new PowerShellConnectorDocumenter(this.PilotXml, this.ProductionXml, connectorName, configEnvironment); break; case "GENERIC SQL (MICROSOFT)": connectorDocumenter = new GenericSqlConnectorDocumenter(this.PilotXml, this.ProductionXml, connectorName, configEnvironment); break; case "GENERIC LDAP (MICROSOFT)": connectorDocumenter = new GenericLdapConnectorDocumenter(this.PilotXml, this.ProductionXml, connectorName, configEnvironment); break; case "MICROSOFT WEB SERVICE ECMA2 CONNECTOR (MICROSOFT)": connectorDocumenter = new WebServicesConnectorDocumenter(this.PilotXml, this.ProductionXml, connectorName, configEnvironment); break; default: if (!string.IsNullOrEmpty(connectorSubType)) { Logger.Instance.WriteWarning("ECMA2 Connector of subtype '{0}' is currently not supported. The connector '{1}' with be treated as a generic ECMA2 connector.", connectorSubType, connectorName); } connectorDocumenter = new Extensible2ConnectorDocumenter(this.PilotXml, this.ProductionXml, connectorName, configEnvironment); break; } } break; default: Logger.Instance.WriteWarning("Connector of type '{0}' is currently not supported. The connector '{1}' with be treated as a generic ECMA2 connector. Documentation may not be complete.", connectorCategory, connectorName); connectorDocumenter = new Extensible2ConnectorDocumenter(this.PilotXml, this.ProductionXml, connectorName, configEnvironment); break; } var report = connectorDocumenter.GetReport(); this.ReportWriter.Write(report.Item1); this.ReportToCWriter.Write(report.Item2); } finally { Logger.Instance.WriteMethodExit(); } }