Exemplo n.º 1
0
        public void Configuring_the_mapping_with_both_fluent_api_and_default_value_attribute()
        {
            AutoConfig.WhenMapping <IDefaultValueConfiguration>(mapper => mapper.Map(x => x.Foo).OptionalWithDefault("default_from_fluent_api"));
            var config = AutoConfig.Map <IDefaultValueConfiguration>(configFilePath: ConfigFilePath);

            config.Foo.Should().Be("default_from_fluent_api");
        }
Exemplo n.º 2
0
        public static Container ApplicationContainer()
        {
            var container = new Container();

            container.Options.DefaultScopedLifestyle = new WebApiRequestLifestyle();

            container.RegisterSingleton <IApplicationConfig>(() =>
            {
                return(AutoConfig.Map <IApplicationConfig>("applicationConfig"));
            });

            container.RegisterSingleton <ICurrencyLayerEndpoints>(() =>
            {
                return(AutoConfig.Map <ICurrencyLayerEndpoints>("currencyLayerEndpoints"));
            });

            container.RegisterSingleton <ICurrencyLayerConfig>(() =>
            {
                return(AutoConfig.Map <ICurrencyLayerConfig>("currencyLayerConfig"));
            });

            //Data Service
            container.Register <ICurrencyLayerApiProvider, CurrencyLayerApiProvider>(Lifestyle.Singleton);

            //Processors
            container.Register <IHistoricalRateProcessor, HistoricalRateProcessor>(Lifestyle.Scoped);

            //Controllers
            container.Register <CurrencyRateController>(Lifestyle.Scoped);

            container.Verify();
            return(container);
        }
Exemplo n.º 3
0
        static void Main(string[] args)
        {
            /*
                This is the standard console application and the starting point of the project
             */
            try
            {
                // This cool util, serializes the app.config configuration section to a class or interface
                var result = AutoConfig.Map<LoggingConfiguration>();

                // Initialise the service using the Topshelf and configure logging
                // InvoiceWindowsService is the service that is inheriting from the base and doing cool stuff 
                new ServiceConfigurationHelper(new InvoiceWindowsService(), 
                    new ServiceDependencies
                    {
                         LoggingConfiguration = new LoggingConfiguration()
                         {
                             LogFile = result.LogFile,
                             LogFolder = result.LogFolder
                         }
                    }
                    ).Configure();
            }
            catch (System.Exception ex)
            {
                System.Console.WriteLine(ex.Message);
                throw;
            }
        }
Exemplo n.º 4
0
        static void Main(string[] args)
        {
            /*
             *  This is the standard console application and the starting point of the project
             */
            try
            {
                // This cool util, serializes the app.config configuration section to a class or interface
                var result = AutoConfig.Map <LogginInfo>();
                var logger = new LoggingConfiguration(result).ConfigureLogger();

                // Initialise the service using the Topshelf and configure logging
                // InvoiceWindowsService is the service that is inheriting from the base and doing cool stuff
                new ServiceConfigurationHelper(new SqlTrackingWindowsService(logger),
                                               new ServiceDependencies
                {
                    Logger      = logger,
                    ServiceInfo = new ServiceInfo()
                    {
                        Description        = "Sql Tracking Service",
                        ServiceDisplayName = "Sql Tracking Service",
                        ServiceName        = "SqlTrackingService"
                    }
                }
                                               ).Configure();
            }
            catch (System.Exception ex)
            {
                System.Console.WriteLine(ex.Message);
                throw;
            }
        }
Exemplo n.º 5
0
        public void Mapping_arrays()
        {
            var config = AutoConfig.Map <IArrayConfiguration>();

            config.Should().NotBeNull();
            config.Eggs.Should().HaveCount(3);
            config.Eggs.Should().ContainInOrder("fried", "scrambled", "poached");
        }
Exemplo n.º 6
0
        public void Mapping_from_attributes()
        {
            var config = AutoConfig.Map <EndPointConfiguration>(configFilePath: ConfigFilePath);

            config.Should().NotBeNull();
            config.Url.Should().Be("http://foo");
            config.Port.Should().Be(80);
        }
        public void AppConfig_Return_AllObjects()
        {
            // Usa o autoConfig para ler uma seção do web.config com todas as tabelas e permissões
            var tablesDiagnostics = AutoConfig.Map <ITablesDiagnostics>();

            // Quantidade de registros no app.config
            Assert.True(tablesDiagnostics.TablePermissions.Count == 3);
        }
Exemplo n.º 8
0
        public void Mapping_readOnlyDictionaries()
        {
            var config = AutoConfig.Map <IReadOnlyDictionaryConfiguration>(configFilePath: ConfigFilePath);

            config.Should().NotBeNull();
            config.FrenchWords.Should().HaveCount(3);
            config.FrenchWords.Keys.Should().ContainInOrder("cat", "dog", "monkey");
            config.FrenchWords.Values.Should().ContainInOrder("chat", "chien", "singe");
        }
Exemplo n.º 9
0
        public void Mapping_nested_collections()
        {
            var config = AutoConfig.Map <INestedCollectionsConfiguration>();

            config.Should().NotBeNull();
            config.Numbers.Should().HaveCount(2);
            config.Numbers.First().Should().ContainInOrder(1, 3, 5);
            config.Numbers.Last().Should().ContainInOrder(2, 4);
        }
Exemplo n.º 10
0
        public void Mapping_from_the_default_file_path()
        {
            var foo = AutoConfig.Map <IFoo>();
            var bar = AutoConfig.Map <IFoo>("bar");

            foo.Should().NotBeNull();
            foo.Name.Should().Be("foo");

            bar.Should().NotBeNull();
            bar.Name.Should().Be("bar");
        }
Exemplo n.º 11
0
        public void Mapping_collections()
        {
            var config = AutoConfig.Map <ICollectionsConfiguration>();

            config.Should().NotBeNull();
            config.Primes.Should().HaveCount(4);
            config.Primes.Should().ContainInOrder(2L, 3L, 5L, 7L);
            config.Colors.Should().HaveCount(2);
            config.Colors.Should().ContainInOrder(ConsoleColor.Red, ConsoleColor.Green);
            config.Unicorns.Should().BeEmpty();
        }
Exemplo n.º 12
0
        public void Mapping_complex_readOnlyDictionaries()
        {
            var config = AutoConfig.Map <IComplexReadOnlyDictionaryConfiguration>(configFilePath: ConfigFilePath);

            config.Should().NotBeNull();
            config.Endpoints.Should().HaveCount(2);
            config.Endpoints["Primary"].Should().HaveCount(2);
            config.Endpoints["Primary"].First().Name.Should().Be("Foo");
            config.Endpoints["Primary"].First().Port.Should().Be(1);
            config.Endpoints["Secondary"].Should().HaveCount(1);
        }
Exemplo n.º 13
0
        public void Mapping_from_a_specific_file_path()
        {
            var foo = AutoConfig.Map <IFoo>(configFilePath: "SpecifyingTheConfigFilePath.xml");
            var bar = AutoConfig.Map <IFoo>("bar", "SpecifyingTheConfigFilePath.xml");

            foo.Should().NotBeNull();
            foo.Name.Should().Be("foo");

            bar.Should().NotBeNull();
            bar.Name.Should().Be("bar");
        }
Exemplo n.º 14
0
        public void Mapping_from_a_combination_of_properties_and_attributes()
        {
            var config = AutoConfig.Map <IPizzaConfiguration>(configFilePath: ConfigFilePath);

            config.Should().NotBeNull();
            config.Name.Should().Be("Vege Deluxe");
            config.Base.Should().Be("Stuffed Crust");
            config.Size.Should().Be(PizzaSize.XLarge);
            config.Price.Should().Be(9.99M);
            config.Toppings.Should().HaveCount(3);
            config.Toppings.Should().ContainInOrder("Aubergine", "Spinach", "Artichoke");
        }
Exemplo n.º 15
0
 static Connection GetConnection()
 {
     try
     {
         return(AutoConfig.Map <Common.Settings>().Connection);
     }
     catch (Exception e)
     {
         Log.ErrorException("failed to read configuration", e);
         throw new ApplicationException("can't read configuration", e);
     }
 }
Exemplo n.º 16
0
        public void Mapping_keyed_collections()
        {
            var config = AutoConfig.Map <IThemeConfig>(configFilePath: ConfigFilePath);

            config.Should().NotBeNull();
            config.Themes.Should().NotBeNull();
            config.Themes.Should().HaveCount(3);
            config.Themes["Blue"].Should().Match <ITheme>(theme => theme.Name == "Blue");
            config.Themes["Red"].Should().Match <ITheme>(theme => theme.Name == "Red");
            config.Themes["Black"].Should().Match <ITheme>(theme => theme.Name == "Black");
            config.Default.Should().Be("Red");
        }
        public async void HealthCheck_Return_WithError()
        {
            // Usa o autoConfig para ler uma seção do web.config com todas as tabelas e permissões
            var tablesDiagnostics = AutoConfig.Map <ITablesDiagnostics>();

            // Repositório para validar a saúde
            var heathCheckRepository = new HeathCheckRepository("DrHouse.Wrapper", "BdName");

            var healthCheck = new HealthCheck(heathCheckRepository);
            var result      = await healthCheck.HealthCheckAsync(tablesDiagnostics);

            Assert.False(result.First().IsSuccess);
        }
Exemplo n.º 18
0
        public void Mapping_to_an_interface()
        {
            var config = AutoConfig.Map <ISimpleConfiguration>();

            config.Should().BeAssignableTo <ISimpleConfiguration>();
            config.Should().NotBeNull();
            config.MyString.Should().Be("hello");
            config.MyInt.Should().Be(42);
            config.MyDate.Should().Be(new DateTime(1969, 07, 21));
            config.MyBool.Should().BeTrue();
            config.MyNullable.Should().Be(23);
            config.MyEmptyNullable.Should().NotHaveValue();
            config.MyTimeSpan.Should().Be(TimeSpan.FromMinutes(5));
        }
Exemplo n.º 19
0
        DataLoader GetLoader()
        {
            var config = AutoConfig.Map <Settings>();

            if (config.Connection == null)
            {
                throw new NullReferenceException("no Connection element");
            }
            var remote     = new DataServiceRemote(config.Connection);
            var dataLoader = new DataLoader(remote);

            dataLoader.Users.LoadAsync().ContinueWith(CheckTaskStatus);
            return(dataLoader);
        }
Exemplo n.º 20
0
        public void Mapping_to_a_concrete_class()
        {
            var config = AutoConfig.Map <SimpleConfiguration>(configFilePath: ConfigFilePath);

            config.Should().BeOfType <SimpleConfiguration>();
            config.Should().NotBeNull();
            config.MyString.Should().Be("hello");
            config.MyInt.Should().Be(42);
            config.MyDate.Should().Be(new DateTime(1969, 07, 21));
            config.MyBool.Should().BeTrue();
            config.MyNullable.Should().Be(23);
            config.MyEmptyNullable.Should().NotHaveValue();
            config.MyTimeSpan.Should().Be(TimeSpan.FromMinutes(5));
        }
        public object Map(XElement element, Type type)
        {
            if (!CanMap(type))
            {
                throw new InvalidOperationException(
                          string.Format("Type '{0}' cannot be mapped by {1} because it is not a KeyValuePair<,>.", type, GetType()));
            }

            var typeArgs = type.GetGenericArguments();
            var keyValuePairBuilderType     = typeof(KeyValuePairBuilder <,>).MakeGenericType(typeArgs);
            var keyValuePairBuilderInstance = AutoConfig.Map(keyValuePairBuilderType, element);
            var keyValuePair = keyValuePairBuilderType.GetMethod("Build").Invoke(keyValuePairBuilderInstance, null);

            return(keyValuePair);
        }
        public void Using_a_custom_mapper()
        {
            AutoConfig.WhenMapping <ICustomMapperExample>(
                mapper =>
            {
                mapper.Map(x => x.Foo).Using <CommaSeparatedListMapper>();
                mapper.Map(x => x.Bar).Using <CommaSeparatedListMapper>();
                mapper.Map(x => x.Baz).Using <CommaSeparatedListMapper>();
            });

            var config = AutoConfig.Map <ICustomMapperExample>();

            config.Foo.Should().Equal(1, 2, 3, 4, 5);
            config.Bar.Should().Equal("one", "two", "three");
            config.Baz.Should().Equal(DayOfWeek.Monday, DayOfWeek.Tuesday);
        }
Exemplo n.º 23
0
        public void Mapping_from_specified_sections()
        {
            var foo      = AutoConfig.Map <IFooBarBaz>("foo");
            var bar      = AutoConfig.Map <IFooBarBaz>("bar");
            var baz      = AutoConfig.Map <IFooBarBaz>("baz");
            var bazUpper = AutoConfig.Map <IFooBarBaz>("BAZ");

            foo.Should().NotBeNull();
            foo.Name.Should().Be("foo");

            bar.Should().NotBeNull();
            bar.Name.Should().Be("bar");

            baz.Should().NotBeNull();
            baz.Name.Should().Be("baz");

            bazUpper.Should().NotBeNull();
            bazUpper.Name.Should().Be("BAZ");
        }
        public void Configuring_the_mapping()
        {
            AutoConfig.WhenMapping <ICustomConfiguration>(
                mapper =>
            {
                mapper.UseMatchingCase();
                mapper.Map(x => x.Foo).From("foofoo");
                mapper.Map(x => x.Bar).Optional();
                mapper.Map(x => x.Baz).OptionalWithDefault("baz");
                mapper.Map(x => x.Qux).Using <CustomMapper>();
            });

            var config = AutoConfig.Map <ICustomConfiguration>();

            config.Foo.Should().Be("fooooo");
            config.Bar.Should().BeNull();
            config.Baz.Should().Be("baz");
            config.Qux.Should().Be("From custom mapper");
        }
Exemplo n.º 25
0
        public void Mapping_using_section_name_conventions()
        {
            var foo = AutoConfig.Map <IFooConfiguration>();
            var bar = AutoConfig.Map <IBarConfig>();
            var baz = AutoConfig.Map <IBazConfig>();
            var qux = AutoConfig.Map <IQuxConfiguration>();

            foo.Should().NotBeNull();
            foo.Name.Should().Be("foo");

            bar.Should().NotBeNull();
            bar.Name.Should().Be("bar");

            baz.Should().NotBeNull();
            baz.Name.Should().Be("baz");

            qux.Should().NotBeNull();
            qux.Name.Should().Be("qux");
        }
Exemplo n.º 26
0
        private async Task PollOnChangedTrackingTables(CancellationToken cancellationToken)
        {
            var settings            = AutoConfig.Map <ChangeTrackingAppSettings>();
            int degreeOfParallelism = settings.DegreeOfParallelism;
            var producerConsumer    = new ProducerConsumerQueue <UspTableVersionChangeTrackingReturnModel>(WcfService.TableChanged, degreeOfParallelism, logger, cancellationToken);

            while (!cancellationToken.IsCancellationRequested)
            {
                Console.WriteLine($"Polling {DateTime.Now}...");

                var versionChanges = DatabaseHelper.GetData();

                foreach (var change in versionChanges)
                {
                    Console.WriteLine($"Change: {change.Id} -> {change.Name} - {change.SysChangeOperation} - {change.SysChangeVersion}");
                    producerConsumer.Produce(change);
                }

                await Task.Delay(settings.PollingFrequencyMilliSeconds);
            }
        }
        public void Mapping_nested_complex_types()
        {
            var config = AutoConfig.Map <IComplexConfiguration>();

            config.Should().NotBeNull();
            config.Foo.Should().Be("foo");
            config.Bar.Should().Be("bar");
            config.Baz.Should().Be("baz");

            config.SomeService.Should().NotBeNull();
            config.SomeService.Name.Should().Be("MyService");
            config.SomeService.RequestTimeout.Should().Be(20);
            config.SomeService.Enabled.Should().BeFalse();

            config.SomeOtherService.Should().NotBeNull();
            config.SomeOtherService.Name.Should().Be("MyOtherService");
            config.SomeOtherService.RequestTimeout.Should().Be(1000);
            config.SomeOtherService.Enabled.Should().BeTrue();

            config.SomeOtherService.Hosts.Should().NotBeNull();
            config.SomeOtherService.Hosts.Should().HaveCount(3);
            config.SomeOtherService.Hosts.Select(host => host.Name).Should().BeEquivalentTo("HOST-01", "HOST-02", "HOST-03");
            config.SomeOtherService.Hosts.Select(host => host.Port).All(port => port == 1700).Should().BeTrue();
        }
Exemplo n.º 28
0
 public virtual object Map(XElement element, Type type)
 {
     return(AutoConfig.Map(type, element));
 }
Exemplo n.º 29
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Engine"/> class.
        /// and processes the startup routine
        /// </summary>
        public Engine(
            bool StartEngine = true,
            bool StartTimer  = true
            )
        {
            // load configuration file
            portNumber = int.Parse(ConfigurationManager.AppSettings["PortNumber"]);
            logLevel   = (LogLevels)int.Parse(ConfigurationManager.AppSettings["LogLevel"]);
            logSource  = ConfigurationManager.AppSettings["LogSource"];
            logto      = ConfigurationManager.AppSettings["LogName"];

            listenOn = IPAddress.Any;
            IPAddress.TryParse(ConfigurationManager.AppSettings["IPAddressToListen"], out listenOn);
            protoTCP = ((ConfigurationManager.AppSettings["Protocol"]).ToLower().Contains("tcp"));
            protoUDP = ((ConfigurationManager.AppSettings["Protocol"]).ToLower().Contains("udp"));

            connectionString = ConfigurationManager.ConnectionStrings["SysLogConnString"].ConnectionString;

            PluginDirectory = ConfigurationManager.AppSettings["PluginDirectory"];
            if (PluginDirectory == "")
            {
                PluginDirectory = Environment.CurrentDirectory + "\\plugins";
            }
            else if (!PluginDirectory.Contains(":"))
            {
                PluginDirectory = Environment.CurrentDirectory + PluginDirectory;
            }


            LogToConsole("Initalizing Virvent Syslog Service");
            LogToConsole("Plugin Directory: " + PluginDirectory);
            // Do a check for the configured startup process

            // load plugin configurations
            LogToConsole("Loading plugin configurations");
            var pluginsConfig = AutoConfig.Map <IPluginConfiguration>();

            // load plugins - pass the config file
            LogToConsole("Loading plugins");
            Plugins          = new List <Plugin>();
            PluginDictionary = new Dictionary <string, IPlugin>();
            ICollection <IPlugin> plugins = PluginManager.LoadPlugins(PluginDirectory);

            if (plugins.Count > 0)
            {
                LogToConsole("Found " + plugins.Count + " plugins.");
            }


            LogToConsole("Binding configurations to plugins.");


            // assemble the plugin with it's configuration
            foreach (var config in pluginsConfig.PluginSettings)
            {
                // find the assembly
                foreach (var i in plugins)
                {
                    if (i.Name == config.Name)
                    {
                        try {
                            var thisPlugin = new Plugin()
                            {
                                Name                  = config.Name,
                                Hours                 = config.Hours,
                                Minutes               = config.Minutes,
                                Seconds               = config.Seconds,
                                TimeUntilEvent        = (config.Hours * 60 * 60) + (config.Minutes * 60) + (config.Seconds),
                                SecondsSinceLastEvent = 0,
                                PluginAssembly        = i,
                                Settings              = new List <PluginSetting>()
                            };

                            foreach (var setting in config.Settings)
                            {
                                thisPlugin.Settings.Add(new PluginSetting()
                                {
                                    Key = setting.Key, Value = setting.Value
                                });
                            }
                            Plugins.Add(thisPlugin);

                            LogToConsole("PLUGIN MANAGER: Loaded " + thisPlugin.Name + " successfully.\r\nTimeUntilEvent: " + thisPlugin.TimeUntilEvent);
                        }
                        catch (Exception ex)
                        {
                            LogToConsole("PLUGIN MANAGER: Error loading plugin: " + i.Name + "\r\n" + ex.Message + "\r\n" + ex.StackTrace);
                        }
                    }
                }
            }


            LogToConsole("Daemon initialized - starting engine.");
            // LogApplicationActivity("Virvent Syslog Server Initialized", SysLogMessage.Severities.Informational, SysLogMessage.Facilities.log_audit);

            if (StartEngine || StartTimer)
            {
                Start(StartEngine, StartTimer);
            }
        }
Exemplo n.º 30
0
        private static CachingFramework.Redis.Context GetContext(string connection = null)
        {
            var config = AutoConfig.Map <RedCacheAppSettings>();

            return(Connect(config.RedisConnection));
        }