예제 #1
0
        static void Main(string[] args)
        {
            var rand = new Random();

            var paramsProvider = new AppConfigProvider(ConfigurationManager.AppSettings);
            var configProvider = new ConfigurationProvider();
            var configFactory = new ConfigurationFactory(new ClientParams(paramsProvider), configProvider);

            var clientConfig = configFactory.Create<ClientConfiguration>();
            clientConfig.Port = rand.Next()%1000 + 25000;

            LogManager.Debug("Address is : 127.0.0.1:{0}", clientConfig.Port);

            var client = new Client(clientConfig);

            client.Start(Console.ReadLine(), () =>
            {
                var small = SmallTestObject.Create();
                while (true)
                {
                    var key = Console.ReadKey();
                    if (key.Key == ConsoleKey.Enter)
                        break;

                    small.Message = key.KeyChar.ToString();
                    client.SendObject(small);
                }
            });
        }
        public void SubsequentCreatesInSessionFactoryDoNotIncrementGeneratorUntilBlockSizeReached()
        {
            ResetDatabase();

            var sessionFactory = new ConfigurationFactory().CreateConfiguration().BuildSessionFactory();
            const long blockSize = 2;

            // First entity save

            var person = new PersonWithBlockSizeTwo { FirstName = "Tim", LastName = "Howard" };
            SavePersonInNewSession(sessionFactory, person);

            // After first insert the generator should be incremented
            Assert.Equal(1, person.Id);
            Assert.Equal(1 + blockSize, GetCurrentGeneratorValue(sessionFactory));

            // Second entity save

            person = new PersonWithBlockSizeTwo { FirstName = "Lionel", LastName = "Messi" };
            SavePersonInNewSession(sessionFactory, person);

            // After second insert the generator should not be incremented
            Assert.Equal(2, person.Id);
            Assert.Equal(1 + blockSize, GetCurrentGeneratorValue(sessionFactory));

            // Third entity save

            person = new PersonWithBlockSizeTwo { FirstName = "Wayne", LastName = "Rooney" };
            SavePersonInNewSession(sessionFactory, person);

            // After third insert the generator should be incremented again
            Assert.Equal(3, person.Id);
            Assert.Equal(1 + (blockSize * 2), GetCurrentGeneratorValue(sessionFactory));
        }
예제 #3
0
        public static void Main(string[] args)
        {
            Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("nl-NL");
            ConfigurationFactory configurationFactory = new ConfigurationFactory();
            Configuration configuration = configurationFactory.Create();
            if (configuration == null)
            {
                // Newly created.
                return;
            }

            Application.Init();

            if (!authenticate())
            {
                return;
            }

            IDbConnection connection = new ConnectionFactory().createConnection(configuration.ConnectionString);

            IRepositoryFactory repositoryFactory = new RepositoryFactory(connection);

            new MainWindow(repositoryFactory).Show();

            Application.Run();
        }
예제 #4
0
        static void Main(string[] args)
        {
            var paramsProvider = new AppConfigProvider(ConfigurationManager.AppSettings);
            var configProvider = new ConfigurationProvider();

            var factory = new ConfigurationFactory(new ServerParams(paramsProvider), configProvider);

            using(var server = new Server(factory.Create<ServerConfiguration>()))
                server.Listen();
        }
예제 #5
0
        public void Get_Config_Section()
        {
            System.Configuration.Configuration configSection = ConfigurationManager.OpenExeConfiguration(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "MvcInstaller.UnitTests.dll.config"));
            if (configSection == null)
            {
                throw new InvalidOperationException("Configuration file not available.");
            }
            InstallerConfig config = Serializer<InstallerConfig>.Deserialize(AppDomain.CurrentDomain.BaseDirectory + @"\installer.config");
            IConnectionStringComponent component = new ConnectionStringComponent(config);
            IConfigurationFactory factory = new ConfigurationFactory(component);
            factory.Execute(config, configSection);

            configSection.Save();
        }
        public void FirstCreateOfEntityInSessionFactoryAlsoIncrementsGeneratorId()
        {
            ResetDatabase();

            var person = new PersonWithBlockSizeDefault {FirstName = "Tim", LastName = "Howard"};

            var sessionFactory = new ConfigurationFactory().CreateConfiguration().BuildSessionFactory();
            using (var session = sessionFactory.OpenSession())
            using (var tx = session.BeginTransaction())
            {
                session.Save(person);
                tx.Commit();
            }

            Assert.Equal(1, person.Id);
            Assert.Equal(1 + Int16.MaxValue, GetCurrentGeneratorValue(sessionFactory));
        }
        public void Update_configuration_and_save()
        {
            //string path = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "MvcInstaller.Tests.dll.config");
            string path = @"C:\VSProjects\MvcInstaller\MvcInstaller.Tests\web.config";

            //System.Configuration.Configuration configSection = ConfigurationManager.OpenExeConfiguration(path);
            System.Configuration.Configuration configSection = WebConfigurationManager.OpenWebConfiguration(path);
            if (configSection == null)
            {
                throw new InvalidOperationException("Configuration file not available.");
            }
            InstallerConfig config = Serializer<InstallerConfig>.Deserialize(AppDomain.CurrentDomain.BaseDirectory + @"\installer.config");
            IConnectionStringComponent component = new ConnectionStringComponent(config);
            IConfigurationFactory factory = new ConfigurationFactory(component);
            factory.Execute(config, configSection);

            configSection.Save();
        }
        public void RecreateDatabase()
        {
            var configuration = new ConfigurationFactory().CreateConfiguration();
            var schemaExport = new SchemaExport(configuration);

            // The current dir is the bin/Debug folder so we back out of there.
            schemaExport.SetOutputFile(@"..\..\..\database\create_schema.sql");
            schemaExport.Execute(true, true, false);

            // We expect two generator tables - the default one used by most of the model classes,
            // and the one with all params specified that uses a custom table and column.

            var sessionFactory = configuration.BuildSessionFactory();

            // Check default generator table
            VerifyGeneratorTable(sessionFactory, "hibernate_unique_key", "next_id", 1);
            // Check params generator table
            VerifyGeneratorTable(sessionFactory, "HibernateUniqueKey", "NextId", 1);
        }
        public ModelConfiguration(
            [NotNull] ConfigurationFactory configurationFactory, 
            [NotNull] IModel model, 
            [NotNull] CustomConfiguration customConfiguration, 
            [NotNull] IRelationalAnnotationProvider extensionsProvider, 
            [NotNull] CSharpUtilities cSharpUtilities, 
            [NotNull] ModelUtilities modelUtilities)
        {
            Check.NotNull(configurationFactory, nameof(configurationFactory));
            Check.NotNull(model, nameof(model));
            Check.NotNull(customConfiguration, nameof(customConfiguration));
            Check.NotNull(extensionsProvider, nameof(extensionsProvider));
            Check.NotNull(cSharpUtilities, nameof(modelUtilities));
            Check.NotNull(modelUtilities, nameof(cSharpUtilities));

            _configurationFactory = configurationFactory;
            Model = model;
            CustomConfiguration = customConfiguration;
            ExtensionsProvider = extensionsProvider;
            CSharpUtilities = cSharpUtilities;
            ModelUtilities = modelUtilities;
        }
예제 #10
0
        private static void Main(string[] args)
        {
            var NUM_ACTORS = 0;
            var FILENAME   = "";

            try
            {
                NUM_ACTORS = int.Parse(Environment.GetEnvironmentVariable("NUM_ACTORS"));
                Console.WriteLine("ENV NUM_ACTORS={0}", NUM_ACTORS);
                FILENAME = Environment.GetEnvironmentVariable("FILENAME");
                Console.WriteLine("ENV FILENAME={0}", FILENAME);
            }
            catch (Exception e)
            {
                Console.WriteLine("ERROR trying to obtain value for Env var: ENV NUM_ACTORS & FILENAME. Exception msg={0}", e.Message);
                //return;
            }

            // TODO - Remove these items
            NUM_ACTORS = 60060;
            FILENAME   = @"c:\temp\datagen.bin";

            // Get the configuration of the akka system
            var config = ConfigurationFactory.ParseString(GetConfiguration());

            // Create the containers for all the actors. Using multiple systems to see if startup time is reduced
            var actorSystem = ActorSystem.Create("csl-arch-poc1", config);

            // Create the AccountGenertor actor
            var accountGeneratorActorProps = Props.Create(() => new AccountGenerator());
            var agref = actorSystem.ActorOf(accountGeneratorActorProps, "AccountGenerator");

            // Generate the accounts
            agref.Tell(new GenerateAccounts(FILENAME, NUM_ACTORS));

            Console.WriteLine(
                "Press return to send the created account actors a message causing them to save a snapshot");
            Console.ReadLine();

            agref.Tell(new SendMsgs());

            Console.WriteLine("Enter an actor id to probe or E to stop");
            var finished  = false;
            var actorPath = "/user/AccountGenerator/testActor-";

            while (finished != true)
            {
                var line = Console.ReadLine();
                if (line.Equals("E"))
                {
                    finished = true;
                }
                else
                {
                    // Get the actor reference and send it a display message
                    Console.WriteLine("Sending a display message to " + actorPath + line);
                    actorSystem.ActorSelection(actorPath + line).Tell(new DisplayState());
                }
            }

            Console.WriteLine("Press return to terminate the system");
            Console.ReadLine();

            // Wait until actor system terminated
            actorSystem.Terminate();
        }
예제 #11
0
 /// <summary>
 /// TBD
 /// </summary>
 /// <returns>TBD</returns>
 public static Config DefaultConfig()
 {
     return(ConfigurationFactory.FromResource <DistributedPubSub>("Akka.Cluster.Tools.PublishSubscribe.reference.conf"));
 }
예제 #12
0
 public EmployeeControllerUnitTests(ITestOutputHelper output,
                                    ConfigurationFactory <EmployeeRepo> fixture) : base(output, fixture)
 {
     _controller = new EmployeeController(Repo);
 }
예제 #13
0
        public void Properly_quarantine_stashed_inbound_connections()
        {
            var localAddress     = new Address("akka.test", "system1", "localhost", 1);
            var rawLocalAddress  = new Address("test", "system1", "localhost", 1);
            var remoteAddress    = new Address("akka.test", "system2", "localhost", 2);
            var rawRemoteAddress = new Address("test", "system2", "localhost", 2);
            var remoteUID        = 16;

            var config = ConfigurationFactory.ParseString(@"
                  akka.remote.enabled-transports = [""akka.remote.test""]
                  akka.remote.retry-gate-closed-for = 5s     
                  akka.remote.log-remote-lifecycle-events = on  
     
            akka.remote.test {
                registry-key = JMeMndLLsw
                local-address = """ + $"test://{localAddress.System}@{localAddress.Host}:{localAddress.Port}" + @"""
            }").WithFallback(_remoteSystem.Settings.Config);

            var thisSystem = ActorSystem.Create("this-system", config);

            MuteSystem(thisSystem);

            try
            {
                // Set up a mock remote system using the test transport
                var registry             = AssociationRegistry.Get("JMeMndLLsw");
                var remoteTransport      = new TestTransport(rawRemoteAddress, registry);
                var remoteTransportProbe = CreateTestProbe();

                registry.RegisterTransport(remoteTransport, Task.FromResult <IAssociationEventListener>
                                               (new ActorAssociationEventListener(remoteTransportProbe)));

                // Hijack associations through the test transport
                AwaitCondition(() => registry.TransportsReady(rawLocalAddress, rawRemoteAddress));
                var testTransport = registry.TransportFor(rawLocalAddress).Value.Item1;
                testTransport.WriteBehavior.PushConstant(true);

                // Force an outbound associate on the real system (which we will hijack)
                // we send no handshake packet, so this remains a pending connection
                var dummySelection = thisSystem.ActorSelection(ActorPath.Parse(remoteAddress + "/user/noonethere"));
                dummySelection.Tell("ping", Sys.DeadLetters);

                var remoteHandle = remoteTransportProbe.ExpectMsg <InboundAssociation>(TimeSpan.FromMinutes(4));
                remoteHandle.Association.ReadHandlerSource.TrySetResult((IHandleEventListener)(new ActionHandleEventListener(ev => {})));

                // Now we initiate an emulated inbound connection to the real system
                var inboundHandleProbe = CreateTestProbe();
                var inboundHandleTask  = remoteTransport.Associate(rawLocalAddress);
                inboundHandleTask.Wait(TimeSpan.FromSeconds(3));
                var inboundHandle = inboundHandleTask.Result;
                inboundHandle.ReadHandlerSource.SetResult(new ActorHandleEventListener(inboundHandleProbe));

                AwaitAssert(() =>
                {
                    registry.GetRemoteReadHandlerFor(inboundHandle.AsInstanceOf <TestAssociationHandle>()).Should().NotBeNull();
                });

                var pduCodec = new AkkaPduProtobuffCodec(Sys);

                var handshakePacket = pduCodec.ConstructAssociate(new HandshakeInfo(rawRemoteAddress, remoteUID));

                // Finish the inbound handshake so now it is handed up to Remoting
                inboundHandle.Write(handshakePacket);

                // No disassociation now, the connection is still stashed
                inboundHandleProbe.ExpectNoMsg(1000);

                // Quarantine unrelated connection
                RARP.For(thisSystem).Provider.Quarantine(remoteAddress, -1);
                inboundHandleProbe.ExpectNoMsg(1000);

                // Quarantine the connection
                RARP.For(thisSystem).Provider.Quarantine(remoteAddress, remoteUID);

                // Even though the connection is stashed it will be disassociated
                inboundHandleProbe.ExpectMsg <Disassociated>();
            }
            finally
            {
                Shutdown(thisSystem);
            }
        }
예제 #14
0
        static void Main(string[] args)
        {
            var config = ConfigurationFactory.ParseString(@"
akka {  
    log-config-on-start = on
    stdout-loglevel = DEBUG
    loglevel = ERROR
    actor {
        provider = ""Akka.Remote.RemoteActorRefProvider, Akka.Remote""
        
        debug {  
          receive = on 
          autoreceive = on
          lifecycle = on
          event-stream = on
          unhandled = on
        }

        deployment {
            /localactor {
                router = round-robin-pool
                nr-of-instances = 5
            }
            /remoteactor {
                router = round-robin-pool
                nr-of-instances = 5
                remote = ""akka.tcp://system2@localhost:8080""
            }
        }
    }
    remote {
        helios.tcp {
            transport-class = ""Akka.Remote.Transport.Helios.HeliosTcpTransport, Akka.Remote""
		    applied-adapters = []
		    transport-protocol = tcp
		    port = 8090
		    hostname = localhost
        }
    }
}
");

            using (var system = ActorSystem.Create("system1", config))
            {
                var reply = system.ActorOf <ReplyActor>("reply");
                //create a local group router (see config)
                var local = system.ActorOf(Props.Create(() => new SomeActor("hello", 123)), "localactor");

                //create a remote deployed actor
                var remote = system.ActorOf(Props.Create(() => new SomeActor(null, 123)), "remoteactor");

                //these messages should reach the workers via the routed local ref
                local.Tell("Local message 1", reply);
                local.Tell("Local message 2", reply);
                local.Tell("Local message 3", reply);
                local.Tell("Local message 4", reply);
                local.Tell("Local message 5", reply);

                //this should reach the remote deployed ref
                remote.Tell("Remote message 1", reply);
                remote.Tell("Remote message 2", reply);
                remote.Tell("Remote message 3", reply);
                remote.Tell("Remote message 4", reply);
                remote.Tell("Remote message 5", reply);
                Console.ReadLine();
                for (int i = 0; i < 10000; i++)
                {
                    remote.Tell(i);
                }

                Console.ReadLine();
            }
        }
예제 #15
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MQConfigFactory" /> class.
 /// </summary>
 /// <param name="configuarationFactory">ConfigurationFactory to wrap</param>
 public MQConfigFactory(ConfigurationFactory configuarationFactory)
 {
     this.configurationFactory = configuarationFactory;
 }
예제 #16
0
 public static Config DefaultConfig()
 {
     return(ConfigurationFactory.FromResource <AkkatectureClusteringDefaultSettings>("Akkatecture.Clustering.Configuration.default.conf"));
 }
        public ConfigurationViewModel(ILifetimeScope lifetimeScope, Dispatcher dispatcher, IActionInvoker actionInvoker)
            : base(lifetimeScope, dispatcher, actionInvoker)
        {
            ErrorText = RegisterProperty <string>(nameof(ErrorText));

            ConfigText = RegisterProperty <string>(nameof(ConfigText))
                         .WithValidator(s =>
            {
                try
                {
                    ConfigurationFactory.ParseString(s);
                    return(null);
                }
                catch (Exception e)
                {
                    return(e.Message);
                }
            });

            GetState <ServicesConfigState>().Query(EmptyQuery.Instance)
            .ContinueWith(c => ConfigText.Set(c.Result?.BaseConfiguration));

            IsSetupVisible = RegisterProperty <bool>(nameof(IsSetupVisible));

            Receive <StartConfigurationSetup>(_ => IsSetupVisible += true);

            NewCommad
            .WithExecute(() =>
            {
                IsSetupVisible += false;
                Context.System.EventStream.Publish(StartInitialHostSetup.Get);
            })
            .ThenRegister("SetupNext");

            ConnectionString = RegisterProperty <string>(nameof(ConnectionString))
                               .WithValidator(s =>
            {
                try
                {
                    MongoUrl.Create(s);
                    return(null);
                }
                catch (Exception e)
                {
                    return(e.Message);
                }
            });

            void ValidateMongoUrl()
            {
                var result = ServicesConfigState.MongoUrlValidator.Validate(ConnectionString.Value);

                if (result.IsValid)
                {
                    ErrorText += string.Empty;
                }
                else
                {
                    ErrorText += result.Errors.FirstOrDefault()?.ErrorMessage ?? string.Empty;
                }
            }

            NewCommad
            .WithCanExecute(b => b.FromProperty(ConnectionString.IsValid))
            .WithExecute(ValidateMongoUrl)
            .ThenRegister("ValidateConnection");

            NewCommad
            .WithCanExecute(b => b.FromProperty(ConnectionString.IsValid))
            .ToStateAction(() => new ApplyMongoUrlAction(ConnectionString.Value))
            .ThenRegister("ApplyConnection");
        }
예제 #18
0
        static void Main(string[] args)
        {
            Console.WriteLine("Openning database");
            cdb.OpenConnection();
            Console.WriteLine("Setting up actors");

            var hocon = ConfigurationFactory.ParseString(@"akka {
    actor {
        provider = remote
    }

    remote {
        dot-netty.tcp {
            port = 0
            hostname = localhost
        }
    }
}");

            using (var system = ActorSystem.Create("feed-system", hocon))
            {
                nerActor       = system.ActorOf <NLPHelper.NERActor>("ner");
                wordCountActor = system.ActorOf <NLPHelper.WordCountingActor>("wordCount");
                nerCountActor  = system.ActorOf <NLPHelper.NERCountingActor>("nerCount");
                stopActor      = system.ActorOf <NLPHelper.StopwordActor>("stopWord");
                stemActor      = system.ActorOf <NLPHelper.StemmingActor>("stemActor");

                /*
                 * var actor1 = system.ActorOf<USGSFeedActor>();
                 * actor1.Tell(new processFeedMessage() { path = "all_week.atom" } );
                 *
                 * var actor2 = system.ActorOf<InciWeb.InciWebFeedActor>();
                 * // actor2.Tell(new InciWeb.processInciWeb());
                 *
                 * var actor3 = system.ActorOf<NCMC.NCMCFeedActor>();
                 * actor3.Tell(new NCMC.processFeedMessage());
                 *
                 * var actor4 = system.ActorOf<CSPC.CPSCFeedActor>();
                 * // actor4.Tell(new CSPC.processFeedMessage());
                 *
                 * var actor5 = system.ActorOf<WeatherGov.WeatherGovFeedActor>();
                 *
                 * // var actor6 = system.ActorOf<Police.SeattlePDFeedActor>();
                 * // actor6.Tell(new Police.ProcessFeed());
                 *
                 * // var actor7 = system.ActorOf<SpotCrime.DiscoverFeedActor>();
                 * // actor7.Tell(new SpotCrime.processDiscover());
                 */

                var actor8 = system.ActorOf <RiverORC.RiverORCFeedActor>("riverFeed");
                actor8.Tell(new RiverORC.processFeedMessage());

                var actor9 = system.ActorOf <CNNUS.CNNFeedActor>("cnn");
                actor9.Tell(new CNNUS.processCNN());

                var actor10 = system.ActorOf <Reuters.ReutersFeedActor>("reuters");
                actor10.Tell(new Reuters.processReuters());

                var actor11 = system.ActorOf <FoxNews.FoxFeedActor>("fox");
                actor11.Tell(new FoxNews.processFox());

                var actor12 = system.ActorOf <USAToday.USATodayFeedActor>("usat");
                actor12.Tell(new USAToday.processUSAToday());

                var actor13 = system.ActorOf <NewsFeeds.GenericFeedActor>("gen");
                actor13.Tell(new NewsFeeds.processFeed());

                List <string> cbseed = new List <string>()
                {
                    "https://www.cbsnews.com/latest/rss/main",
                    "https://www.cbsnews.com/latest/rss/us",
                    "https://www.cbsnews.com/latest/rss/politics",
                    "https://www.cbsnews.com/latest/rss/world",
                    "https://www.cbsnews.com/latest/rss/technology",
                };

                List <string> bbcFeeds = new List <string>()
                {
                    "http://feeds.bbci.co.uk/news/rss.xml",
                    "http://feeds.bbci.co.uk/news/world/rss.xml",
                    "http://feeds.bbci.co.uk/news/uk/rss.xml",
                    "http://feeds.bbci.co.uk/news/politics/rss.xml",
                    "http://feeds.bbci.co.uk/news/technology/rss.xml",
                    "http://feeds.bbci.co.uk/news/world/us_and_canada/rss.xml"
                };


                // Exit the system after ENTER is pressed
                Console.ReadLine();
            }
        }
예제 #19
0
 private static Config ConfigFromTemplate(Type snapshotStoreType)
 {
     return(ConfigurationFactory.ParseString(string.Format(_specConfigTemplate, snapshotStoreType.FullName)));
 }
예제 #20
0
 /// <summary>
 /// TBD
 /// </summary>
 /// <returns>TBD</returns>
 public static Config DefaultConfig() =>
 ConfigurationFactory.FromResource <DistributedData>("Akka.DistributedData.reference.conf");
예제 #21
0
        public void Can_assign_quoted_null_string_to_field()
        {
            var hocon = @"a=""null""";

            Assert.Equal("null", ConfigurationFactory.ParseString(hocon).GetString("a"));
        }
예제 #22
0
        public void Can_assign_unescaped_path_like_variable_to_field()
        {
            var hocon = @"a=""""""C:\Dev\somepath\to\a\file.txt""""""";

            Assert.Equal("C:\\Dev\\somepath\\to\\a\\file.txt", ConfigurationFactory.ParseString(hocon).GetString("a"));
        }
예제 #23
0
        public void Can_assign_triple_quoted_string_with_unescaped_chars_to_field()
        {
            var hocon = @"a=""""""hello\y\o\u""""""";

            Assert.Equal("hello\\y\\o\\u", ConfigurationFactory.ParseString(hocon).GetString("a"));
        }
        private void SetUpGenFormWebConfiguration()
        {
            Isolate.CleanUp();
            _configuration = WebConfigurationManager.OpenWebConfiguration("/GenForm");
            _factory = Isolate.Fake.Instance<ConfigurationFactory>();
            Isolate.WhenCalled(() => _factory.GetConfiguration()).WillReturn(_configuration);

            _configSettingSource = new ConfigurationSettingSource(_factory);
        }
예제 #25
0
        public void CanTrimConcatenatedValue()
        {
            var hocon = "a= \t \t 1 2 3 \t \t,";

            Assert.Equal("1 2 3", ConfigurationFactory.ParseString(hocon).GetString("a"));
        }
예제 #26
0
        public void TestMethod1()
        {
            Configuration configSection = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            //Configuration configSection = WebConfigurationManager.OpenWebConfiguration(null);

            if (configSection == null)
            {
                throw new InvalidOperationException("Configuration file not available.");
            }
            InstallerConfig config = Serializer<InstallerConfig>.Deserialize(AppDomain.CurrentDomain.BaseDirectory + @"\installer.config");
            IConnectionStringComponent component = new ConnectionStringComponent(config);
            IConfigurationFactory factory = new ConfigurationFactory(component);
            factory.Execute(config, configSection);

            configSection.Save();
        }
예제 #27
0
        public void CanConsumeCommaAfterValue()
        {
            var hocon = "a=1,";

            Assert.Equal("1", ConfigurationFactory.ParseString(hocon).GetString("a"));
        }
예제 #28
0
        public void CanAssignTrippleQuotedStringToField()
        {
            var hocon = @"a=""""""hello""""""";

            Assert.Equal("hello", ConfigurationFactory.ParseString(hocon).GetString("a"));
        }
예제 #29
0
        public void CanAssignIpAddressToField()
        {
            var hocon = @"a=127.0.0.1";

            Assert.Equal("127.0.0.1", ConfigurationFactory.ParseString(hocon).GetString("a"));
        }
예제 #30
0
        public void Stash_inbound_connections_until_UID_is_known_for_pending_outbound()
        {
            var localAddress     = new Address("akka.test", "system1", "localhost", 1);
            var rawLocalAddress  = new Address("test", "system1", "localhost", 1);
            var remoteAddress    = new Address("akka.test", "system2", "localhost", 2);
            var rawRemoteAddress = new Address("test", "system2", "localhost", 2);

            var config = ConfigurationFactory.ParseString(@"
                  akka.remote.enabled-transports = [""akka.remote.test""]
                  akka.remote.retry-gate-closed-for = 5s     
                  akka.remote.log-remote-lifecycle-events = on
                  akka.loglevel = DEBUG
     
            akka.remote.test {
                registry-key = TRKAzR
                local-address = """ + $"test://{localAddress.System}@{localAddress.Host}:{localAddress.Port}" + @"""
            }").WithFallback(_remoteSystem.Settings.Config);

            var thisSystem = ActorSystem.Create("this-system", config);

            MuteSystem(thisSystem);

            try
            {
                // Set up a mock remote system using the test transport
                var registry             = AssociationRegistry.Get("TRKAzR");
                var remoteTransport      = new TestTransport(rawRemoteAddress, registry);
                var remoteTransportProbe = CreateTestProbe();

                registry.RegisterTransport(remoteTransport, Task.FromResult <IAssociationEventListener>
                                               (new ActorAssociationEventListener(remoteTransportProbe)));

                // Hijack associations through the test transport
                AwaitCondition(() => registry.TransportsReady(rawLocalAddress, rawRemoteAddress));
                var testTransport = registry.TransportFor(rawLocalAddress).Value.Item1;
                testTransport.WriteBehavior.PushConstant(true);

                // Force an outbound associate on the real system (which we will hijack)
                // we send no handshake packet, so this remains a pending connection
                var dummySelection = thisSystem.ActorSelection(ActorPath.Parse(remoteAddress + "/user/noonethere"));
                dummySelection.Tell("ping", Sys.DeadLetters);

                var remoteHandle = remoteTransportProbe.ExpectMsg <InboundAssociation>(TimeSpan.FromMinutes(4));
                remoteHandle.Association.ReadHandlerSource.TrySetResult((IHandleEventListener)(new ActionHandleEventListener(ev => { })));

                // Now we initiate an emulated inbound connection to the real system
                var inboundHandleProbe = CreateTestProbe();
                var inboundHandleTask  = remoteTransport.Associate(rawLocalAddress);
                inboundHandleTask.Wait(TimeSpan.FromSeconds(3));
                var inboundHandle = inboundHandleTask.Result;
                inboundHandle.ReadHandlerSource.SetResult(new ActorHandleEventListener(inboundHandleProbe));

                AwaitAssert(() =>
                {
                    registry.GetRemoteReadHandlerFor(inboundHandle.AsInstanceOf <TestAssociationHandle>()).Should().NotBeNull();
                });

                var pduCodec = new AkkaPduProtobuffCodec(Sys);

                var handshakePacket = pduCodec.ConstructAssociate(new HandshakeInfo(rawRemoteAddress, 0));
                var brokenPacket    = pduCodec.ConstructPayload(ByteString.CopyFrom(0, 1, 2, 3, 4, 5, 6));

                // Finish the inbound handshake so now it is handed up to Remoting
                inboundHandle.Write(handshakePacket);
                // Now bork the connection with a malformed packet that can only signal an error if the Endpoint is already registered
                // but not while it is stashed
                inboundHandle.Write(brokenPacket);

                // No disassociation now - the connection is still stashed
                inboundHandleProbe.ExpectNoMsg(1000);

                // Finish the handshake for the outbound connection - this will unstash the inbound pending connection.
                remoteHandle.Association.Write(handshakePacket);

                inboundHandleProbe.ExpectMsg <Disassociated>(TimeSpan.FromMinutes(5));
            }
            finally
            {
                Shutdown(thisSystem);
            }
        }
예제 #31
0
        public void CanAssignConcatenatedValueToField()
        {
            var hocon = @"a=1 2 3";

            Assert.Equal("1 2 3", ConfigurationFactory.ParseString(hocon).GetString("a"));
        }
예제 #32
0
 static ResourcesTests()
 {
     using (Configuration configuration = new Configuration(new Context(ConfigurationFactory.Create())))
         configuration.UpdateDatabase();
 }
 /// <summary>
 /// Deletes all data and resets the ID generators
 /// </summary>
 private static void ResetDatabase()
 {
     var sessionFactory = new ConfigurationFactory().CreateConfiguration().BuildSessionFactory();
     using (var session = sessionFactory.OpenSession())
     using (var tx = session.BeginTransaction())
     {
         var directSql = session.CreateSQLQuery(DatabaseHelper.ResetDatabaseScript());
         directSql.ExecuteUpdate();
         tx.Commit();
     }
 }
예제 #34
0
 /// <summary>
 /// Creates a new <see cref="ActorSystem"/> with the specified name.
 /// </summary>
 /// <param name="name">The name of the actor system to create. The name must be uri friendly.
 /// <remarks>Must contain only word characters (i.e. [a-zA-Z0-9] plus non-leading '-'</remarks>
 /// </param>
 /// <returns>A newly created actor system with the given name.</returns>
 public static ActorSystem Create(string name)
 {
     return(CreateAndStartSystem(name, ConfigurationFactory.Load()));
 }
        public void GeneratorIsInitializedToZeroWithBlockSizeTwo()
        {
            ResetDatabase();

            // Note: zero should be skipped as an ID to conform to expected NHibernate behavior

            var sessionFactory = new ConfigurationFactory().CreateConfiguration().BuildSessionFactory();
            const long smallBlockSize = 2;

            // Set generator to zero
            using (var session = sessionFactory.OpenSession())
            using (var tx = session.BeginTransaction())
            {
                var sqlQuery = session.CreateSQLQuery("UPDATE hibernate_unique_key SET next_id = 0");
                sqlQuery.ExecuteUpdate();
                tx.Commit();
            }
            Assert.Equal(0, GetCurrentGeneratorValue(sessionFactory));

            // ** First save of entity should get ID 1 (generator incremented)
            var personWithSmallBlockSize = new PersonWithBlockSizeTwo { FirstName = "Tim", LastName = "Howard" };
            SavePersonInNewSession(sessionFactory, personWithSmallBlockSize);
            Assert.Equal(1, personWithSmallBlockSize.Id);
            Assert.Equal(smallBlockSize, GetCurrentGeneratorValue(sessionFactory));

            // ** Second save of entity should get ID 2 (generator incremented)
            personWithSmallBlockSize = new PersonWithBlockSizeTwo { FirstName = "Tim", LastName = "Howard" };
            SavePersonInNewSession(sessionFactory, personWithSmallBlockSize);
            Assert.Equal(2, personWithSmallBlockSize.Id);
            Assert.Equal(smallBlockSize * 2, GetCurrentGeneratorValue(sessionFactory));

            // ** Third save of entity should get ID 3 (generator not incremented)
            personWithSmallBlockSize = new PersonWithBlockSizeTwo { FirstName = "Tim", LastName = "Howard" };
            SavePersonInNewSession(sessionFactory, personWithSmallBlockSize);
            Assert.Equal(3, personWithSmallBlockSize.Id);
            Assert.Equal(smallBlockSize * 2, GetCurrentGeneratorValue(sessionFactory));

            // ** Fourth save of entity should get ID 4 (generator incremented)
            personWithSmallBlockSize = new PersonWithBlockSizeTwo { FirstName = "Tim", LastName = "Howard" };
            SavePersonInNewSession(sessionFactory, personWithSmallBlockSize);
            Assert.Equal(4, personWithSmallBlockSize.Id);
            Assert.Equal(smallBlockSize * 3, GetCurrentGeneratorValue(sessionFactory));
        }
예제 #36
0
 public static Config GetConfig()
 {
     return(ConfigurationFactory.ParseString(@"akka.actor.provider = cluster
                                             akka.extensions = [""Akka.Cluster.Tools.PublishSubscribe.DistributedPubSubExtensionProvider,Akka.Cluster.Tools""]
                                             akka.remote.dot-netty.tcp.port = 0"));
 }
예제 #37
0
 public ConfigurationSettingSource(ConfigurationFactory factory)
 {
     _factory = factory;
 }
        public void RemoteNodeShutdownAndComesBack_must_properly_reset_system_message_buffer_state_when_new_system_with_same_Address_comes_up()
        {
            RunOn(() =>
            {
                var secondAddress = Node(_config.Second).Address;
                Sys.ActorOf <RemoteNodeShutdownAndComesBackMultiNetSpec.Subject>("subject");
                EnterBarrier("actors-started");

                var subject       = _identify(_config.Second, "subject");
                var sysmsgBarrier = _identify(_config.Second, "sysmsgBarrier");

                // Prime up the system message buffer
                Watch(subject);
                EnterBarrier("watch-established");

                // Wait for proper system message propagation
                // (Using a helper actor to ensure that all previous system messages arrived)
                Watch(sysmsgBarrier);
                Sys.Stop(sysmsgBarrier);
                ExpectTerminated(sysmsgBarrier);

                // Drop all messages from this point so no SHUTDOWN is ever received
                TestConductor.Blackhole(_config.Second, _config.First, ThrottleTransportAdapter.Direction.Send).Wait();

                // Shut down all existing connections so that the system can enter recovery mode (association attempts)
                RARP.For(Sys)
                .Provider.Transport.ManagementCommand(new ForceDisassociate(Node(_config.Second).Address))
                .Wait(TimeSpan.FromSeconds(3));

                // Trigger reconnect attempt and also queue up a system message to be in limbo state (UID of remote system
                // is unknown, and system message is pending)
                Sys.Stop(subject);

                // Get rid of old system -- now SHUTDOWN is lost
                TestConductor.Shutdown(_config.Second).Wait();

                // At this point the second node is restarting, while the first node is trying to reconnect without resetting
                // the system message send state

                // Now wait until second system becomes alive again
                Within(TimeSpan.FromSeconds(30), () =>
                {
                    // retry because the Subject actor might not be started yet
                    AwaitAssert(() =>
                    {
                        var p = CreateTestProbe();
                        Sys.ActorSelection(new RootActorPath(secondAddress) / "user" / "subject").Tell(new Identify("subject"), p.Ref);
                        p.ExpectMsg <ActorIdentity>(i => i.Subject != null && "subject".Equals(i.MessageId), TimeSpan.FromSeconds(1));
                    });
                });

                ExpectTerminated(subject, TimeSpan.FromSeconds(10));

                // Establish watch with the new system. This triggers additional system message traffic. If buffers are out
                // of sync the remote system will be quarantined and the rest of the test will fail (or even in earlier
                // stages depending on circumstances).
                Sys.ActorSelection(new RootActorPath(secondAddress) / "user" / "subject").Tell(new Identify("subject"));
                var subjectNew = ExpectMsg <ActorIdentity>(i => i.Subject != null).Subject;
                Watch(subjectNew);

                subjectNew.Tell("shutdown");
                // we are waiting for a Terminated here, but it is ok if it does not arrive
                ReceiveWhile(TimeSpan.FromSeconds(5), msg => msg as ActorIdentity);
            }, _config.First);

            RunOn(() =>
            {
                var addr = ((ExtendedActorSystem)Sys).Provider.DefaultAddress;
                Sys.ActorOf <RemoteNodeShutdownAndComesBackMultiNetSpec.Subject>("subject");
                Sys.ActorOf <RemoteNodeShutdownAndComesBackMultiNetSpec.Subject>("sysmsgBarrier");
                EnterBarrier("actors-started");

                EnterBarrier("watch-established");

                Sys.WhenTerminated.Wait(TimeSpan.FromSeconds(30));

                var freshConfig = new StringBuilder().AppendLine("akka.remote.helios.tcp {").AppendLine("hostname = " + addr.Host)
                                  .AppendLine("port = " + addr.Port)
                                  .AppendLine("}").ToString();

                var freshSystem = ActorSystem.Create(Sys.Name,
                                                     ConfigurationFactory.ParseString(freshConfig)
                                                     .WithFallback(Sys.Settings.Config));

                freshSystem.ActorOf <RemoteNodeShutdownAndComesBackMultiNetSpec.Subject>("subject");

                freshSystem.WhenTerminated.Wait(TimeSpan.FromSeconds(30));
            }, _config.Second);
        }
예제 #39
0
        public void CanConcatenateArray()
        {
            var hocon = @"a=[1,2] [3,4]";

            Assert.True(new[] { 1, 2, 3, 4 }.SequenceEqual(ConfigurationFactory.ParseString(hocon).GetIntList("a")));
        }
예제 #40
0
 private static Config GetAkkaConfigurationFromHoconFile(string configFileName = "akka.hocon")
 {
     return(ConfigurationFactory.ParseString(File.ReadAllText(configFileName)));
 }
예제 #41
0
        public void CanAssignDoubleToField()
        {
            var hocon = @"a=1.1";

            Assert.Equal(1.1, ConfigurationFactory.ParseString(hocon).GetDouble("a"));
        }
        public void IsolateTheWebSettingSource()
        {
            _settingName = "Test";
            _configuration = Isolate.Fake.Instance<Configuration>();

            _settings = Isolate.Fake.Instance<KeyValueConfigurationCollection>();
            // Note: have to fake the keyvalueconfiguration element, when actually creating it
            // using constructor(key, value), after creation element.key returns empty string???
            var fakeElement = Isolate.Fake.Instance<KeyValueConfigurationElement>();
            Isolate.WhenCalled(() => fakeElement.Key).WillReturn(_settingName);
            Isolate.WhenCalled(() => _settings[_settingName]).WillReturn(fakeElement);
            var empty = new[] {_settingName};
            Isolate.WhenCalled(() => _settings.AllKeys).WillReturn(empty);

            _connections = Isolate.Fake.Instance<ConnectionStringSettingsCollection>();
            var fakeConnection = Isolate.Fake.Instance<ConnectionStringSettings>();
            Isolate.WhenCalled(() => fakeConnection.Name).WillReturn(_settingName);
            Isolate.WhenCalled(() => _connections[_settingName]).WillReturn(fakeConnection);

            Isolate.WhenCalled(() => _configuration.AppSettings.Settings).WillReturn(_settings);
            Isolate.WhenCalled(() => _configuration.ConnectionStrings.ConnectionStrings).WillReturn(_connections);

            _factory = Isolate.Fake.Instance<ConfigurationFactory>();
            Isolate.WhenCalled(() => _factory.GetConfiguration()).WillReturn(_configuration);

            _configSettingSource = new ConfigurationSettingSource(_factory);
        }
예제 #43
0
        public void CanAssignNullToField()
        {
            var hocon = @"a=null";

            Assert.Null(ConfigurationFactory.ParseString(hocon).GetString("a"));
        }
예제 #44
0
        public void CanAssignValueToQuotedField()
        {
            var hocon = @"""a""=1";

            Assert.Equal(1L, ConfigurationFactory.ParseString(hocon).GetLong("a"));
        }
        public void InterleavedEntitiesWithDifferentBlockSizes()
        {
            ResetDatabase();

            var sessionFactory = new ConfigurationFactory().CreateConfiguration().BuildSessionFactory();
            const long smallBlockSize = 2;
            const long defaultBlockSize = Int16.MaxValue;

            long expectedDatabaseGeneratorValue = 1;
            Assert.Equal(expectedDatabaseGeneratorValue, GetCurrentGeneratorValue(sessionFactory));

            // ** First save of entity with small block size

            var personWithSmallBlockSize = new PersonWithBlockSizeTwo { FirstName = "Tim", LastName = "Howard" };
            SavePersonInNewSession(sessionFactory, personWithSmallBlockSize);

            // Generator should be incremented by the small block size
            long expectedSmallBlockSizeGeneratorValue = expectedDatabaseGeneratorValue;
            expectedDatabaseGeneratorValue += smallBlockSize;
            Assert.Equal(expectedSmallBlockSizeGeneratorValue, personWithSmallBlockSize.Id);
            Assert.Equal(expectedDatabaseGeneratorValue, GetCurrentGeneratorValue(sessionFactory));

            // ** First save of entity with default block size

            var personWithDefaultBlockSize = new PersonWithBlockSizeDefault { FirstName = "Tim", LastName = "Howard" };
            SavePersonInNewSession(sessionFactory, personWithDefaultBlockSize);

            // This entity should be allocated a default block
            // Database Generator should be incremented by default block size
            long expectedDefaultBlockSizeGeneratorValue = expectedDatabaseGeneratorValue;
            expectedDatabaseGeneratorValue += defaultBlockSize;
            Assert.Equal(expectedDefaultBlockSizeGeneratorValue, personWithDefaultBlockSize.Id);
            Assert.Equal(expectedDatabaseGeneratorValue, GetCurrentGeneratorValue(sessionFactory));

            // ** Second save of entity with small block size

            personWithSmallBlockSize = new PersonWithBlockSizeTwo { FirstName = "Lionel", LastName = "Messi" };
            SavePersonInNewSession(sessionFactory, personWithSmallBlockSize);

            // Database Generator should not be incremented
            expectedSmallBlockSizeGeneratorValue++;
            Assert.Equal(expectedSmallBlockSizeGeneratorValue, personWithSmallBlockSize.Id);
            Assert.Equal(expectedDatabaseGeneratorValue, GetCurrentGeneratorValue(sessionFactory));

            // ** Second save of entity with default block size

            personWithDefaultBlockSize = new PersonWithBlockSizeDefault { FirstName = "Tim", LastName = "Howard" };
            SavePersonInNewSession(sessionFactory, personWithDefaultBlockSize);

            // Database Generator should not be incremented
            expectedDefaultBlockSizeGeneratorValue++;
            Assert.Equal(expectedDefaultBlockSizeGeneratorValue, personWithDefaultBlockSize.Id);
            Assert.Equal(expectedDatabaseGeneratorValue, GetCurrentGeneratorValue(sessionFactory));

            // Third save of entity with small block size

            personWithSmallBlockSize = new PersonWithBlockSizeTwo { FirstName = "Wayne", LastName = "Rooney" };
            SavePersonInNewSession(sessionFactory, personWithSmallBlockSize);

            // Database Generator should be incremented again
            expectedSmallBlockSizeGeneratorValue = expectedDatabaseGeneratorValue;
            expectedDatabaseGeneratorValue += smallBlockSize;
            Assert.Equal(expectedSmallBlockSizeGeneratorValue, personWithSmallBlockSize.Id);
            Assert.Equal(expectedDatabaseGeneratorValue, GetCurrentGeneratorValue(sessionFactory));
        }
예제 #46
0
        public void CanAssignValueToPathExpression()
        {
            var hocon = @"a.b.c=1";

            Assert.Equal(1L, ConfigurationFactory.ParseString(hocon).GetLong("a.b.c"));
        }
예제 #47
0
        public void CanAssignLongToField()
        {
            var hocon = @"a=1";

            Assert.Equal(1L, ConfigurationFactory.ParseString(hocon).GetLong("a"));
        }
예제 #48
0
 /// <summary>
 /// Initializes a new instance of the <see cref="WorkerConfigFactory" /> class.
 /// </summary>
 /// <param name="configuarationFactory">ConfigurationFactory to wrap</param>
 public WorkerConfigFactory(ConfigurationFactory configuarationFactory)
 {
     this.configurationFactory = configuarationFactory;
 }
 private static ISessionFactory BuildFactory()
 {
     Configuration cfg = new ConfigurationFactory().Build();
     ISessionFactory sessionFactory = cfg.BuildSessionFactory();
     return sessionFactory;
 }