public void Handling_namevaluesettings_forced_encryption_should_work() { /* Arrange */ var crypto = A.Fake<ICryptoProvider>(); A.CallTo(() => crypto.Encrypt(A<string>.Ignored)).ReturnsLazily(h => Convert.ToBase64String(Encoding.UTF8.GetBytes(h.Arguments[0].ToString()))); A.CallTo(() => crypto.Decrypt(A<string>.Ignored)).ReturnsLazily(h => Encoding.UTF8.GetString(Convert.FromBase64String(h.Arguments[0].ToString()))); A.CallTo(() => crypto.IsEncrypted(A<string>.Ignored)).Returns(true); var nv = new NameValueSettings(); nv.SetSetting("Plain", "PlainText"); nv.SetEncryptedSetting("Encrypted", "EncryptedText"); var handler = new NameValueExtendedSectionHandler(); /* Act */ var node = handler.WriteSection("TestSection", nv, crypto, true); var result = handler.ReadSection(node, crypto, true) as NameValueSettings; var val1 = result.Get("Plain", null); var val2 = result.Get("Encrypted", null); var allEncrypted = result.IsEncrypted("Plain") && result.IsEncrypted("Encrypted"); /* Assert */ val1.Should().Be("PlainText"); val2.Should().Be("EncryptedText"); allEncrypted.Should().BeTrue(); }
public ReportRegistry() : base() { var setting = AppSettings.Current.GetString("Report1:Settings"); NameValueSettings settings = new NameValueSettings(setting); // Schedule an IJob to run at an interval Schedule <Report1Job>().ToRunNow().AndEvery(settings.Get("repeat", 10)).Minutes(); }
public static void Initialise(Stream configurationFile) { if (AppSettings != null) { throw new TypeInitializationException(nameof(ConfigurationManager), new InvalidOperationException("Initialise must be called once in program")); } AppSettings = new NameValueSettings(new ConfigurationManager(configurationFile).LoadSection <Configuration>().Settings); }
public void Getting_defaults_for_non_existant_values_should_work() { /* Arrange */ var nv = new NameValueSettings(); /* Act */ var s1 = nv.Get("NoSuch1", "Def1"); var s2 = nv.Get<string>("NoSuch2", "Def2"); var s3 = nv.Get<bool>("NoSuch3", true); /* Assert */ s1.Should().Be("Def1"); s2.Should().Be("Def2"); s3.Should().BeTrue(); }
public void Getting_an_invalid_type_should_throw() { /* Arrange */ var nv = new NameValueSettings(); /* Act */ nv.SetSetting(TestSetting.StringValue, "somestring"); Action a1 = () => nv.Get<int>(TestSetting.StringValue, 0); Action a2 = () => nv.Get<object>(TestSetting.StringValue, null); /* Assert */ a1.ShouldThrow<ConfigException>(); a2.ShouldThrow<ConfigException>(); }
public void Get_and_set_and_remove_description_Should_work() { /* Arrange */ var nv = new NameValueSettings(); string expectedDescription = "this is a description"; /* Act */ nv.SetDescription(TestSetting.GuidValue, expectedDescription); nv.SetDescription(TestSetting.TimeSpanValue, expectedDescription); nv.RemoveDescription(TestSetting.TimeSpanValue); nv.RemoveDescription((Enum)null); nv.RemoveDescription((string)null); string desc1 = nv.GetDescription(TestSetting.GuidValue); string desc2 = nv.GetDescription(TestSetting.IntegerValue); string desc3 = nv.GetDescription(TestSetting.TimeSpanValue); /* Assert */ desc1.Should().Be(expectedDescription); desc2.Should().BeEmpty(); desc3.Should().BeEmpty(); }
public void Normal_write_read_namevaluesettings_handling_should_work() { /* Arrange */ var crypter = A.Fake<ICryptoProvider>(); A.CallTo(() => crypter.Encrypt(A<string>.Ignored)).ReturnsLazily(h => h.Arguments[0].ToString()); A.CallTo(() => crypter.Decrypt("PlainText")).Throws(new Exception()); A.CallTo(() => crypter.Decrypt("EncryptedText")).Returns("EncryptedText"); A.CallTo(() => crypter.IsEncrypted("PlainText")).Returns(false); A.CallTo(() => crypter.IsEncrypted("EncryptedText")).Returns(true); var nv = new NameValueSettings(); nv.SetSetting("Plain", "PlainText"); nv.SetEncryptedSetting("Encrypted", "EncryptedText"); nv.SetDescription("Encrypted", "This is some encrypted text"); var handler = new NameValueExtendedSectionHandler(); /* Act */ var node = handler.WriteSection("TestSection", nv, crypter, false); var result = handler.ReadSection(node, crypter, false) as NameValueSettings; var val1 = result.Get("Plain", null); var val2 = result.Get("Encrypted", null); var desc = result.GetDescription("Encrypted"); var isEnc1 = result.IsEncrypted("Plain"); var isEnc2 = result.IsEncrypted("Encrypted"); /* Assert */ val1.Should().Be("PlainText"); val2.Should().Be("EncryptedText"); desc.Should().Be("This is some encrypted text"); isEnc1.Should().BeFalse(); isEnc2.Should().BeTrue(); }
public void Reading_a_section_with_one_encryption_and_writing_it_with_another_must_work() { /* Arrange */ var cryptoOne = A.Fake<ICryptoProvider>(); A.CallTo(() => cryptoOne.Encrypt(A<string>.Ignored)).ReturnsLazily(h => Convert.ToBase64String(Encoding.UTF8.GetBytes(h.Arguments[0].ToString()))); A.CallTo(() => cryptoOne.Decrypt(A<string>.Ignored)).ReturnsLazily(h => Encoding.UTF8.GetString(Convert.FromBase64String(h.Arguments[0].ToString()))); A.CallTo(() => cryptoOne.IsEncrypted(A<string>.Ignored)).Returns(true); var cryptoTwo = A.Fake<ICryptoProvider>(); A.CallTo(() => cryptoTwo.Encrypt(A<string>.Ignored)).ReturnsLazily(h => new string(h.Arguments[0].ToString().Reverse().ToArray())); A.CallTo(() => cryptoTwo.Decrypt(A<string>.Ignored)).ReturnsLazily(h => new string(h.Arguments[0].ToString().Reverse().ToArray())); A.CallTo(() => cryptoTwo.IsEncrypted(A<string>.Ignored)).Returns(true); var source = new NameValueSettings(); source.SetEncryptedSetting("Setting1", "SomeText"); var handler1 = new NameValueExtendedSectionHandler(); var handler2 = new NameValueExtendedSectionHandler(); /* Act */ var node = handler1.WriteSection("TestSection", source, cryptoOne, false); var midResult = handler1.ReadSection(node, cryptoOne, false) as NameValueSettings; node = handler2.WriteSection("TestSection", midResult, cryptoTwo, false); var result = handler2.ReadSection(node, cryptoTwo, false) as NameValueSettings; var val = result.Get("Setting1", null); /* Assert */ A.CallTo(() => cryptoOne.Encrypt(A<string>.Ignored)).MustHaveHappened(Repeated.Exactly.Once); A.CallTo(() => cryptoOne.Decrypt(A<string>.Ignored)).MustHaveHappened(Repeated.Exactly.Once); A.CallTo(() => cryptoTwo.Encrypt(A<string>.Ignored)).MustHaveHappened(Repeated.Exactly.Once); A.CallTo(() => cryptoTwo.Decrypt(A<string>.Ignored)).MustHaveHappened(Repeated.Exactly.Once); val.Should().Be("SomeText"); }
/// <summary> /// Creates a <see cref="NameValueSettings"/> from an xml element of a config file. /// <para> /// NOTE: The settings collection is case sensitive. /// </para> /// </summary> /// <param name="section">The XElement that contains the configuration information from the configuration file. Provides direct access to the XML contents of the configuration section</param> /// <param name="cryptoProvider">An <see cref="ICryptoProvider"/> instance that can be used to decrypt settings.</param> /// <param name="decryptAll">If <see langword="true" /> all settings will be decrypted. This is ignored since the <see cref="NameValueSettings"/> handles this by itself.</param> /// <returns>A <see cref="NameValueSettings"/> instance containing the configuration data, or empty if section is null or in fact empty.</returns> public object ReadSection(XElement section, ICryptoProvider cryptoProvider, bool decryptAll) { Ensure.ArgumentNotNull(section, "section"); _errors = null; //Create a case sensitive collection var data = new NameValueSettings(); if (section != null) { var settings = from node in section.Elements(ConfigElement.KeyValueSettingNode) let key = node.Attribute(ConfigElement.SettingKeyAttribute) let val = node.Attribute(ConfigElement.SettingValueAttribute) where key != null && val != null select new { Key = key.Value, Value = val.Value, Comment = node.PreviousNode as XComment }; foreach (var node in settings) { string val = node.Value; bool encrypted = false; if (cryptoProvider != null && cryptoProvider.IsEncrypted(val)) { try { val = cryptoProvider.Decrypt(val); encrypted = true; } catch { if (_errors == null) { _errors = new List<ConfigError>(); } _errors.Add( new ConfigError( ConfigErrorCode.InvalidConfigValue, string.Format("Reading value of setting {0} failed, value appears to be encrypted, but decryption failed.", node.Key))); continue; } } data.SetSetting(node.Key, val, encrypted); if (node.Comment != null) { data.SetDescription(node.Key, node.Comment.Value); } } } return data; }
public void Normal_write_read_handling_with_null_encrypter_should_work() { /* Arrange */ var nv = new NameValueSettings(); nv.SetSetting("Plain", "PlainText"); nv.SetEncryptedSetting("Encrypted", "EncryptedText"); var handler = new NameValueExtendedSectionHandler(); /* Act */ var node = handler.WriteSection("TestSection", nv, null, false); var result = handler.ReadSection(node, null, false) as NameValueSettings; var val1 = result.Get("Plain", null); var val2 = result.Get("Encrypted", null); var isEnc1 = result.IsEncrypted("Plain"); var isEnc2 = result.IsEncrypted("Encrypted"); /* Assert */ val1.Should().Be("PlainText"); val2.Should().Be("EncryptedText"); isEnc1.Should().BeFalse(); isEnc2.Should().BeFalse(); }
public void Props_should_return_expected_values() { /* Arrange */ var nv = new NameValueSettings(); /* Act */ nv.SetSetting(TestSetting.StringValue, "somestring"); nv.SetSetting(TestSetting.BooleanValue, false); /* Assert */ nv.Count.Should().Be(2); nv.RawSettings.Count.Should().Be(2); nv.SettingNames.Count.Should().Be(2); }
public void Setting_and_getting_name_value_settings_should_work() { /* Arrange */ var doc = TestConfigFactory.CreateConfig(); var p = A.Fake<IConfigProvider>(); A.CallTo(() => p.LoadConfig()).Returns(new[] { doc }); var settingsOne = new NameValueCollection(); settingsOne.Add("A", "ValueA"); var settingsTwo = new NameValueSettings(); settingsTwo.SetSetting("B", "ValueB"); /* Act */ var mgr = ConfigManager.Create(p); mgr.SetSettings(TestSection.SectionOne, settingsOne); mgr.SetSettings(TestSection.SectionTwo, settingsTwo); var readSectionOne = mgr.GetSettings<NameValueSettings>(TestSection.SectionOne); var readSectionTwo = mgr.GetSettings<NameValueSettings>(TestSection.SectionTwo); mgr.Reload(); var readSectionOneAfterReload = mgr.GetSettings<NameValueSettings>(TestSection.SectionOne); var readSectionTwoAfterReload = mgr.GetSettings<NameValueSettings>(TestSection.SectionTwo); int sectionCount = mgr.Sections.Count(); /* Assert */ A.CallTo(() => p.SaveConfig(doc)).MustNotHaveHappened(); readSectionOne.Should().NotBeNull(); readSectionOne.Get("A", null).Should().Be("ValueA"); readSectionTwo.Should().NotBeNull(); readSectionTwo.Should().NotBeSameAs(settingsTwo); readSectionTwo.Get("B", null).Should().Be("ValueB"); readSectionOneAfterReload.Should().NotBeNull(); readSectionOneAfterReload.Get("A", null).Should().Be("ValueA"); readSectionTwoAfterReload.Should().NotBeNull(); readSectionTwoAfterReload.Get("B", null).Should().Be("ValueB"); sectionCount.Should().Be(2); }
public void Execute() { Console.WriteLine("Execute"); try { var setting = AppSettings.Current.GetString("Report1:Settings"); NameValueSettings settings = new NameValueSettings(setting); var email = settings.Get("email"); if (string.IsNullOrEmpty(email)) { Console.WriteLine("Email was not configured"); } else { EmailTemplate template = null; using (var db = new DataContext()) { var journals = db.DBModel.Journals .Include(x => x.JournalDrivers) .Where(x => x.Status == JournalStatus.Started).ToArray(); bool isChanged = false; var engine = new FileHelperEngine <JournalRow>(); var rows = new List <JournalRow>(); rows.Add(new JournalRow { Shipmentcode = "Shipment Code", TruckNo = "Truck No", DriverName = "Driver", Start = "Start", Destination = "Destination", TotalDistance = "Total Distance", TotalDuration = "Total Duration", CurrentLocation = "Current Location", EstimatedDistanceToDestination = "Estimated Distance To Destination", Note = "Note", }); foreach (var journal in journals) { var journalRows = ToJournalRows(db, journal, ref isChanged); if (journalRows.Length > 0) { rows.AddRange(journalRows); } } //MemoryStream ms = new MemoryStream(); string fileContent = engine.WriteString(rows); string fileName = $"JournalStatus{DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss")}.csv"; // Email if (template == null) { template = GetEmailTemplate(); } (new SmtpEmailService()).SendMail( email, template, new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase) { }, new List <Tuple <string, Stream> >() { new Tuple <string, Stream>(fileName, new MemoryStream(Encoding.Unicode.GetBytes(fileContent))), }); if (isChanged) { db.SaveChanges(); } //ms.Dispose(); } } } catch (Exception ex) { Console.WriteLine("Error:", ex.GetFullMessage()); } finally { Console.WriteLine("Sleep to next run"); } }
private static XElement WriteSettings(string sectionXmlName, NameValueSettings sectionSource, ICryptoProvider cryptoProvider, bool encryptAll) { //Write the settings var section = new XElement(sectionXmlName); var rawSource = sectionSource.RawSettings; foreach (string key in rawSource.AllKeys) { //Add the description if appropriate string description = sectionSource.GetDescription(key); if (description.Length > 0) { section.Add(new XComment(description)); } //Encrypt if appropriate string val = rawSource[key]; if (cryptoProvider != null && (encryptAll || sectionSource.IsEncrypted(key))) { val = cryptoProvider.Encrypt(val); } section.Add(new XElement( ConfigElement.KeyValueSettingNode, new XAttribute(ConfigElement.SettingKeyAttribute, key), new XAttribute(ConfigElement.SettingValueAttribute, val))); } return section; }
public void Reading_a_value_that_where_decryption_fails_must_fail_gracefully() { /* Arrange */ var crypto = A.Fake<ICryptoProvider>(); A.CallTo(() => crypto.Encrypt(A<string>.Ignored)).ReturnsLazily(h => Convert.ToBase64String(Encoding.UTF8.GetBytes(h.Arguments[0].ToString()))); A.CallTo(() => crypto.Decrypt(A<string>.Ignored)).Throws(new Exception()); A.CallTo(() => crypto.IsEncrypted(A<string>.Ignored)).Returns(true); var nv = new NameValueSettings(); nv.SetEncryptedSetting("Encrypted", "EncryptedText"); var handler = new NameValueExtendedSectionHandler(); /* Act */ var node = handler.WriteSection("TestSection", nv, crypto, true); var result = handler.ReadSection(node, crypto, true) as NameValueSettings; /* Assert */ handler.Errors.Should().ContainSingle(e => e.Code == ConfigErrorCode.InvalidConfigValue); }
public void Removing_a_setting_should_work() { /* Arrange */ var nv = new NameValueSettings(); /* Act */ nv.SetSetting(TestSetting.StringValue, "SomeVal"); nv.SetSetting(TestSetting.BooleanValue, true); nv.RemoveSetting(TestSetting.StringValue); nv.RemoveSetting((Enum)null); nv.RemoveSetting((string)null); var s1 = nv.Get(TestSetting.StringValue, "Def1"); var s2 = nv.Get<bool>(TestSetting.BooleanValue, false); /* Assert */ s1.Should().Be("Def1"); s2.Should().BeTrue(); }
public void Setting_empty_values_should_work() { /* Arrange */ var nv = new NameValueSettings(); /* Act */ nv.SetSetting(TestSetting.StringValue, "SomeVal"); nv.SetSetting(TestSetting.BooleanValue, true); nv.SetSetting(TestSetting.StringValue, null); nv.SetSetting(TestSetting.BooleanValue, string.Empty); var s1 = nv.Get(TestSetting.StringValue, "Def1"); var s2 = nv.Get<bool>(TestSetting.BooleanValue, false); /* Assert */ s1.Should().Be("Def1"); s2.Should().BeFalse(); }
public void Get_and_set_should_work_regardless_of_culture() { /* Arrange */ var nv = new NameValueSettings(); var expectedDate = DateTime.UtcNow; var expectedTime = new TimeSpan(5, 4, 3, 2, 1); var expectedGuid = Guid.NewGuid(); /* Act */ using (new CultureContext()) { nv.SetSetting("StringValue", "SomeString"); nv.SetEncryptedSetting("StringValueTwo", "SomeOtherString"); nv.SetSetting(TestSetting.IntegerValue, 10); nv.SetSetting(TestSetting.BooleanValue, true); nv.SetSetting(TestSetting.DateTimeValue, expectedDate); nv.SetSetting(TestSetting.EnumValue, TestSetting.EnumValue); nv.SetSetting(TestSetting.TimeSpanValue, expectedTime); nv.SetEncryptedSetting(TestSetting.GuidValue, expectedGuid); } bool encryptedDate = nv.IsEncrypted(TestSetting.DateTimeValue); bool encryptedGuid = nv.IsEncrypted(TestSetting.GuidValue); bool valueExists = nv.HasSetting(TestSetting.BooleanValue); bool valueNoExists = nv.HasSetting("SomeOtherVal"); string stringVal = nv.Get("StringValue", null); string stringVal2 = nv.Get<string>("StringValueTwo", null); int intVal = nv.Get<int>(TestSetting.IntegerValue, 0); bool boolVal = nv.Get<bool>(TestSetting.BooleanValue, false); DateTime dateVal = nv.Get<DateTime>(TestSetting.DateTimeValue, DateTime.MaxValue); TestSetting enumVal = nv.Get<TestSetting>(TestSetting.EnumValue, TestSetting.BooleanValue); TimeSpan timeVal = nv.Get<TimeSpan>(TestSetting.TimeSpanValue, TimeSpan.Zero); Guid guidVal = nv.Get<Guid>(TestSetting.GuidValue, Guid.Empty); /* Assert */ stringVal.Should().Be("SomeString"); stringVal2.Should().Be("SomeOtherString"); intVal.Should().Be(10); boolVal.Should().Be(true); dateVal.Should().Be(expectedDate); enumVal.Should().Be(TestSetting.EnumValue); timeVal.Should().Be(expectedTime); guidVal.Should().Be(expectedGuid); encryptedDate.Should().BeFalse(); encryptedGuid.Should().BeTrue(); valueExists.Should().BeTrue(); valueNoExists.Should().BeFalse(); }
/// <summary> /// Writes configuration settings from a <see cref="NameValueSettings"/> or <see cref="System.Collections.Specialized.NameValueCollection"/> instance. /// </summary> /// <param name="sectionXmlName">The xml name of the section to be written.</param> /// <param name="sectionSource">A <see cref="NameValueSettings"/> or <see cref="System.Collections.Specialized.NameValueCollection"/> instance.</param> /// <param name="cryptoProvider">An <see cref="ICryptoProvider"/> instance that can be used to encrypt settings. This is only used if <c>encryptAll</c> is true.</param> /// <param name="encryptAll">If <see langword="true" /> all settings will be encrypted (if not already encrypted). Only applies if sectionSource is a <see cref="NameValueSettings"/>.</param> /// <returns>The xml element for the section.</returns> /// <exception cref="ArgumentNullException">If sectionName is null or empty, or sectionSource is null</exception> /// <exception cref="ConfigException">If sectionSource is not of type <see cref="NameValueSettings"/> or <see cref="System.Collections.Specialized.NameValueCollection"/></exception> public XElement WriteSection(string sectionXmlName, object sectionSource, ICryptoProvider cryptoProvider, bool encryptAll) { Ensure.ArgumentNotNullOrEmpty(sectionXmlName, "sectionName"); Ensure.ArgumentNotNull(sectionSource, "sectionSource"); _errors = null; var nvs = sectionSource as NameValueSettings; if (nvs != null) { return WriteSettings(sectionXmlName, nvs, cryptoProvider, encryptAll); } var nvc = sectionSource as NameValueCollection; if (nvc != null) { nvs = new NameValueSettings(nvc); return WriteSettings(sectionXmlName, nvs, cryptoProvider, encryptAll); } _errors = new[] { new ConfigError(ConfigErrorCode.InvalidConfigType, "This handler can only process instances of type DeepConfig.NameValueSettings or System.Collections.Specialized.NameValueCollection or a derivative thereof.") }; return null; }