private void MainWindow_Loaded(object sender, RoutedEventArgs e) { system = ActorSystem.Create("MyClientSystem"); serverActor = system.ActorSelection("akka.tcp://TestServer@localhost:8081/user/MyServerActor"); uiActor = system.ActorOf(Props.Create(() => new UIActor(this.textBox)), "MyClient"); clientActor = system.ActorOf(Props.Create(() => new ClientActor(serverActor, uiActor)), Guid.NewGuid().ToString()); }
private static GatewayRef StartGateway(ActorSystem system, ChannelType type, int port) { var serializer = PacketSerializer.CreatePacketSerializer(); var initiator = new GatewayInitiator { ListenEndPoint = new IPEndPoint(IPAddress.Any, port), GatewayLogger = LogManager.GetLogger("Gateway"), CreateChannelLogger = (ep, _) => LogManager.GetLogger($"Channel({ep}"), ConnectionSettings = new TcpConnectionSettings { PacketSerializer = serializer }, PacketSerializer = serializer, CreateInitialActors = (context, connection) => new[] { Tuple.Create(context.ActorOf(Props.Create(() => new EntryActor(context.Self.Cast<ActorBoundChannelRef>()))), new TaggedType[] { typeof(IEntry) }, (ActorBindingFlags)0) } }; var gateway = (type == ChannelType.Tcp) ? system.ActorOf(Props.Create(() => new TcpGateway(initiator))).Cast<GatewayRef>() : system.ActorOf(Props.Create(() => new UdpGateway(initiator))).Cast<GatewayRef>(); gateway.Start().Wait(); return gateway; }
static void Main(string[] args) { // initialize MyActorSystem // YOU NEED TO FILL IN HERE MyActorSystem = ActorSystem.Create("MyActorSystem"); // time to make your first actors! var consoleWriterProps = Props.Create(() => new ConsoleWriterActor()); var consoleWriterActor = MyActorSystem.ActorOf(consoleWriterProps, "consoleWriterActor"); var tailCoordinatorActor = MyActorSystem.ActorOf(Props.Create<TailCoordinatorActor>(), "tailCoordinatorActor"); var validationActorProps = Props.Create(() => new FileValidatorActor(consoleWriterActor)); var validationActor = MyActorSystem.ActorOf(validationActorProps, "validationActor"); var consoleReaderProps = Props.Create<ConsoleReaderActor>(); var readerActor = MyActorSystem.ActorOf(consoleReaderProps, "consoleReaderActor"); // tell console reader to begin //YOU NEED TO FILL IN HERE readerActor.Tell(ConsoleReaderActor.StartCommand); // blocks the main thread from exiting until the actor system is shut down MyActorSystem.AwaitTermination(); }
static void Main(string[] args) { // initialize MyActorSystem MyActorSystem = ActorSystem.Create("MyActorSystem"); // make consoleWriterActor var consoleWriterProps = Props.Create(() => new ConsoleWriterActor()); var consoleWriterActor = MyActorSystem.ActorOf(consoleWriterProps, "consoleWriterActor"); // make tailCoordinatorActor var tailCoordinatorProps = Props.Create(() => new TailCoordinatorActor()); var tailCoordinatorActor = MyActorSystem.ActorOf(tailCoordinatorProps, "tailCoordinatorActor"); // make fileValidatorActor, pass consoleWriterActor and tailCoordinatorActor to fileValidatorActorProps var validationActorProps = Props.Create(() => new FileValidationActor(consoleWriterActor)); var validationActor = MyActorSystem.ActorOf(validationActorProps, "validationActor"); // make consoleReaderActor, pass validationActor to consoleReaderProps var consoleReaderProps = Props.Create(() => new ConsoleReaderActor()); var consoleReaderActor = MyActorSystem.ActorOf(consoleReaderProps, "consoleReaderActor"); // tell console reader to begin consoleReaderActor.Tell(ConsoleReaderActor.StartCommand); // blocks the main thread from exiting until the actor system is shut down MyActorSystem.AwaitTermination(); }
static void Main(string[] args) { // make an actor system MyActorSystem = ActorSystem.Create("MyActorSystem"); // this is here to show you what NOT to do // this approach to props has no type safety // it will compile, but can easily blow up in your face at runtime :( // UNCOMMENT THE BELOW TWO LINES, BUILD THE SOLUTION, AND THEN TRY TO RUN IT TO SEE //Props fakeActorProps = Props.Create(typeof(FakeActor)); //IActorRef fakeActor = MyActorSystem.ActorOf(fakeActorProps, "fakeActor"); // set up actors, using props (split props onto own line so easier to read) Props consoleWriterProps = Props.Create<ConsoleWriterActor>(); IActorRef consoleWriterActor = MyActorSystem.ActorOf(consoleWriterProps, "consoleWriterActor"); Props validationActorProps = Props.Create(() => new ValidationActor(consoleWriterActor)); IActorRef validationActor = MyActorSystem.ActorOf(validationActorProps, "validationActor"); Props consoleReaderProps = Props.Create<ConsoleReaderActor>(validationActor); IActorRef consoleReaderActor = MyActorSystem.ActorOf(consoleReaderProps, "consoleReaderActor"); // tell console reader to begin consoleReaderActor.Tell(ConsoleReaderActor.StartCommand); // blocks the main thread from exiting until the actor system is shut down MyActorSystem.AwaitTermination(); }
public static Server.GatewayRef CreateGateway(ActorSystem system, ChannelType type, string name, IPEndPoint endPoint, XunitOutputLogger.Source outputSource, Action<Server.GatewayInitiator> clientInitiatorSetup = null) { // initialize gateway initiator var initiator = new Server.GatewayInitiator() { GatewayLogger = new XunitOutputLogger($"Gateway({name})", outputSource), ListenEndPoint = endPoint, ConnectEndPoint = endPoint, TokenRequired = false, CreateChannelLogger = (_, o) => new XunitOutputLogger($"ServerChannel({name})", outputSource), CheckCreateChannel = (_, o) => true, ConnectionSettings = new Server.TcpConnectionSettings { PacketSerializer = s_serverSerializer }, PacketSerializer = s_serverSerializer, }; clientInitiatorSetup?.Invoke(initiator); // create gateway and start it var gateway = (type == ChannelType.Tcp) ? system.ActorOf(Props.Create(() => new Server.TcpGateway(initiator))).Cast<Server.GatewayRef>() : system.ActorOf(Props.Create(() => new Server.UdpGateway(initiator))).Cast<Server.GatewayRef>(); gateway.Start().Wait(); return gateway; }
static void Main(string[] args) { // initialize MyActorSystem MyActorSystem = ActorSystem.Create("MyActorSystem"); // time to make your first actors! var consoleWriterActor = MyActorSystem.ActorOf(Props.Create<ConsoleWriterActor>(), "MyConsoleWriter"); // Generic syntax // make tailCoordinatorActor Props tailCoordinatorProps = Props.Create(() => new TailCoordinatorActor()); var tailCoordinatorActor = MyActorSystem.ActorOf(tailCoordinatorProps, "tailCoordinatorActor"); // pass tailCoordinatorActor to fileValidatorActorProps (just adding one extra arg) Props fileValidatorActorProps = Props.Create(() => new FileValidatorActor(consoleWriterActor)); var validationActor = MyActorSystem.ActorOf(fileValidatorActorProps, "validationActor"); var consoleReaderActor = MyActorSystem.ActorOf(Props.Create(() => new ConsoleReaderActor()), "MyConsoleReader"); // tell console reader to begin consoleReaderActor.Tell(ConsoleReaderActor.StartCommand); // Fake start with validationActor.Tell(@"c:\MyFile.txt"); // blocks the main thread from exiting until the actor system is shut down MyActorSystem.AwaitTermination(); }
private static void AtLeastOnceDelivery(ActorSystem system) { Console.WriteLine("\n--- AT LEAST ONCE DELIVERY EXAMPLE ---\n"); var delivery = system.ActorOf(Props.Create(()=> new DeliveryActor()),"delivery"); var deliverer = system.ActorOf(Props.Create(() => new AtLeastOnceDeliveryExampleActor(delivery.Path))); delivery.Tell("start"); deliverer.Tell(new Message("foo")); System.Threading.Thread.Sleep(1000); //making sure delivery stops before send other commands delivery.Tell("stop"); deliverer.Tell(new Message("bar")); Console.WriteLine("\nSYSTEM: Throwing exception in Deliverer\n"); deliverer.Tell("boom"); System.Threading.Thread.Sleep(1000); deliverer.Tell(new Message("bar1")); Console.WriteLine("\nSYSTEM: Enabling confirmations in 3 seconds\n"); System.Threading.Thread.Sleep(3000); Console.WriteLine("\nSYSTEM: Enabled confirmations\n"); delivery.Tell("start"); }
static void Main(string[] args) { // initialize MyActorSystem MyActorSystem = ActorSystem.Create("MyActorSystem"); // time to make your first actors! Props consoleWriterProps = Props.Create<ConsoleWriterActor>(); IActorRef consoleWriterActor = MyActorSystem.ActorOf(consoleWriterProps, "consoleWriterActor"); Props tailCoordinatorProps = Props.Create(() => new TailCoordinatorActor()); IActorRef tailCoordinatorActor = MyActorSystem.ActorOf(tailCoordinatorProps, "tailCoordinatorActor"); Props fileValidatorActorProps = Props.Create(() => new FileValidatorActor(consoleWriterActor)); IActorRef validationActor = MyActorSystem.ActorOf(fileValidatorActorProps, "validationActor"); Props consoleReaderProps = Props.Create<ConsoleReaderActor>(); IActorRef consoleReaderActor = MyActorSystem.ActorOf(consoleReaderProps, "consoleReaderActor"); // tell console reader to begin consoleReaderActor.Tell(ConsoleReaderActor.StartCommand); // blocks the main thread from exiting until the actor system is shut down MyActorSystem.AwaitTermination(); }
static void Main(string[] args) { // initialize MyActorSystem MyActorSystem = ActorSystem.Create("MyActorSystem"); // DEMO to show that typeof() is valid but dangerous //Props fakeActorProps = Props.Create(typeof(FakeActor)); //IActorRef fakeActor = MyActorSystem.ActorOf(fakeActorProps, "fakeActor"); Props consoleWriterProps = Props.Create<ConsoleWriterActor>(); IActorRef consoleWriterActor = MyActorSystem.ActorOf(consoleWriterProps, "consoleWriterActor"); Props tailCoordinatorActorProps = Props.Create(() => new TailCoordinatorActor()); IActorRef tailCoordinatorActor = MyActorSystem.ActorOf(tailCoordinatorActorProps, "tailCoordinatorActor"); // pass tailCoordinatorActor to fileValidatorActorProps (just adding one extra arg) Props fileValidatorActorProps = Props.Create(() => new FileValidatorActor(consoleWriterActor)); IActorRef validationActor = MyActorSystem.ActorOf(fileValidatorActorProps, "validationActor"); Props consoleReaderProps = Props.Create<ConsoleReaderActor>(); IActorRef consoleReaderActor = MyActorSystem.ActorOf(consoleReaderProps, "consoleReaderActor"); // tell console reader to begin consoleReaderActor.Tell(ConsoleReaderActor.StartCommand); // blocks the main thread from exiting until the actor system is shut down MyActorSystem.AwaitTermination(); Console.ReadKey(); }
private static void Main(string[] args) { _actorSystem = ActorSystem.Create("TestSystem"); // have a separate actor to write transition changes to the console var consoleWriter = _actorSystem.ActorOf(Props.Create(() => new ConsoleWriter()), "consoleWriter"); var chopsticks = new List<IActorRef>(); // Create 5 chopsticks for (int i = 0; i < 5; i++) { var chopstick = _actorSystem.ActorOf(Props.Create(() => new Chopstick(_actorSystem)), "chopstick" + i); chopsticks.Add(chopstick); } // Create 5 philosophers and assign them their left and right chopstick var philosophers = new List<IActorRef>(); var names = new List<string>() {"Aristotle", "Plato", "Locke", "Socrates", "Marx"}; for (int i = 0; i < names.Count; i++) { var leftChopstick = chopsticks[i]; var rightChopstick = i == 4 ? chopsticks[0] : chopsticks[i + 1]; var philosopher = _actorSystem.ActorOf(Props.Create(() => new Philosopher(names[i],leftChopstick,rightChopstick)), names[i]); philosophers.Add(philosopher); // subscribe the console writer to receive state change transitions philosopher.Tell(new FSMBase.SubscribeTransitionCallBack(consoleWriter)); } foreach (var philosopher in philosophers) { philosopher.Tell(new Think()); } Console.ReadLine(); }
static void Main(string[] args) { var config = ConfigurationFactory.ParseString( File.ReadAllText(Path.Combine(Environment.CurrentDirectory, "akka.config"))); // make actor system MyActorSystem = ActorSystem.Create("MyActorSystem", config); // create top-level actors within the actor system Props consoleWriterProps = Props.Create<ConsoleWriterActor>(); IActorRef consoleWriterActor = MyActorSystem.ActorOf(consoleWriterProps, "consoleWriterActor"); Props tailCoordinatorProps = Props.Create(() => new TailCoordinatorActor()); IActorRef tailCoordinatorActor = MyActorSystem.ActorOf(tailCoordinatorProps, "tailCoordinatorActor"); Props fileValidatorActorProps = Props.Create(() => new FileValidatorActor(consoleWriterActor)); IActorRef fileValidatorActor = MyActorSystem.ActorOf(fileValidatorActorProps, "validationActor"); Props consoleReaderProps = Props.Create<ConsoleReaderActor>(); IActorRef consoleReaderActor = MyActorSystem.ActorOf(consoleReaderProps, "consoleReaderActor"); // begin processing consoleReaderActor.Tell(ConsoleReaderActor.StartCommand); // blocks the main thread from exiting until the actor system is shut down MyActorSystem.AwaitTermination(); }
public bool Start(HostControl hostControl) { ClusterSystem = ActorSystem.Create("webcrawler"); ApiMaster = ClusterSystem.ActorOf(Props.Create(() => new ApiMaster()), "api"); DownloadMaster = ClusterSystem.ActorOf(Props.Create(() => new DownloadsMaster()), "downloads"); //ApiMaster.Tell(new StartJob(new CrawlJob(new Uri("http://www.rottentomatoes.com/", UriKind.Absolute), true), ghettoConsoleActor)); return true; }
private static void ViewExample(ActorSystem system) { Console.WriteLine("\n--- PERSISTENT VIEW EXAMPLE ---\n"); var pref = system.ActorOf(Props.Create<ViewExampleActor>()); var view = system.ActorOf(Props.Create<ExampleView>()); system.Scheduler.ScheduleTellRepeatedly(TimeSpan.Zero, TimeSpan.FromSeconds(2), pref, "scheduled", ActorRefs.NoSender); system.Scheduler.ScheduleTellRepeatedly(TimeSpan.Zero, TimeSpan.FromSeconds(5), view, "snap", ActorRefs.NoSender); }
private void _init() { actorSystem = ActorSystem.Create("strategiesServer"); strategyActor = actorSystem.ActorOf(Props.Create<StrategyManagerActor>(), ConstantsHelper.AKKA_PATH_STRATEGY_MANAGER); persistenceActor = actorSystem.ActorOf(Props.Create<PersistenceActor>(), ConstantsHelper.AKKA_PATH_PERSISTENCE); marketActor = actorSystem.ActorOf(Props.Create<SecuritiesMarketManagerActor>(), ConstantsHelper.AKKA_PATH_MARKET_MANAGER); }
public bool Start(HostControl hostControl) { _agentSystem = ActorSystem.Create("netricagent"); var consumer = _agentSystem.ActorOf<RequestConsumer>("consumer"); var receiver = _agentSystem.ActorOf(Props.Create(() => new EtwEventProcessingActor(consumer)),"receiver"); _ongoingTask = new Task(()=>new EventReceiver(receiver).Start()); _ongoingTask.Start(); return true; }
public EventProcessor() { system = ActorSystem.Create("MusicFileProcessingSystem"); var resourceDownloaderProps = Props.Create<ResourceDownloader>(); var resourceDownloader = system.ActorOf(resourceDownloaderProps, "resourceDownloader"); var resourceStorerProps = Props.Create<BlobStorageActor>(); var resourceStorer = system.ActorOf(resourceStorerProps, "resourceStorer"); var recordCreatorProps = Props.Create<Mp3RecordManager>(resourceDownloader, resourceStorer); recordCreator = system.ActorOf(recordCreatorProps, "recordCreator"); }
public void Start() { _monitorActorSystem = ActorSystem.Create("WinSrvMonitorServer"); _metricDistributerActor = _monitorActorSystem.ActorOf<MetricDistributerActor>("metricDistributer"); _metricCollectorActor = _monitorActorSystem.ActorOf( Props.Create(() => new MetricCollectorActor(_metricDistributerActor)), "metricCollector"); }
public void SetupTickEngine(IGalaxyViewModel state, ITextOutputViewModel textOutput) { _galaxyActorSystem = ActorSystem.Create("GalaxyActors"); Props textOutputProps = Props.Create<ActorTextOutput>(textOutput).WithDispatcher("akka.actor.synchronized-dispatcher"); _actorTextOutput = _galaxyActorSystem.ActorOf(textOutputProps, "TextOutput"); Props teCoordinatorProps = Props.Create<ActorTickEngineCoordinator>(_actorTextOutput, state.Model); _actorTECoordinator = _galaxyActorSystem.ActorOf(teCoordinatorProps, "TECoordinator"); engineInitialised = true; }
private static void Main(string[] args) { MyActorSystem = ActorSystem.Create(nameof(MyActorSystem)); var consoleWriterActor = MyActorSystem.ActorOf(Props.Create(() => new ConsoleWriterActor())); var consoleReaderActor = MyActorSystem.ActorOf(Props.Create(() => new ConsoleReaderActor(consoleWriterActor))); consoleReaderActor.Tell(ConsoleReaderActor.StartCommand); // blocks the main thread from exiting until the actor system is shut down MyActorSystem.AwaitTermination(); }
public void ActorOf_gives_child_unique_name_if_not_specified() { //arrange var system = new ActorSystem("test"); //act var child1 = system.ActorOf<TestActor>(); var child2 = system.ActorOf<TestActor>(); //assert Assert.NotEqual(child1.Path, child2.Path); }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); ActorSystem = ActorSystem.Create("webcrawler"); var notificationActor = ActorSystem.ActorOf(Props.Create(() => new NotificationActor()), "notificationActor"); SystemActors.NotificationActor = notificationActor; SystemActors.SignalRActor = ActorSystem.ActorOf(Props.Create(() => new SignalRActor(notificationActor)), "signalRActor"); }
public static void Create() { GameEventsPusher = new SignalRGameEventPusher(); ActorSystem = ActorSystem.Create("GameSystem"); ActorReferences.GameController = ActorSystem.ActorOf<GameControllerActor>(); ActorReferences.SignalRBridge = ActorSystem.ActorOf( Props.Create(() => new SignalRBridgeActor(GameEventsPusher, ActorReferences.GameController)), "SignalRBridge" ); }
private static void Main(string[] args) { system = ActorSystem.Create("fizz-buzz"); fbActor = system.ActorOf(Props.Create<FizzBuzzActor>(), "fb-actor"); cwActor = system.ActorOf(Props.Create<ConsoleWriterActor>(), "cw-actor"); for (var i = 1; i <= 10000; i++) { fbActor.Tell(new FizzBuzzMessage(i)); } Console.ReadKey(); }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); ActorSystem = ActorSystem.Create("webcrawler"); var router = ActorSystem.ActorOf(Props.Create(() => new RemoteJobActor()).WithRouter(FromConfig.Instance), "tasker"); SystemActors.CommandProcessor = ActorSystem.ActorOf(Props.Create(() => new CommandProcessor(router)), "commands"); SystemActors.SignalRActor = ActorSystem.ActorOf(Props.Create(() => new SignalRActor()), "signalr"); }
public void Start() { ClusterSystem = ActorSystem.Create("sys"); var router = ClusterSystem.ActorOf(Props.Create(() => new RemoteJobActor()).WithRouter(FromConfig.Instance), "tasker"); var commandExecutor = ClusterSystem.ActorOf(Props.Create(() => new CommandExecutor(router)), "commands"); ObjectFactory.Initialize(cfg => cfg.For<IActorRef>().Singleton().Use(commandExecutor).Named("commands")); _restServiceHost = new RESTServiceHost(); _restServiceHost.Init(); _restServiceHost.Start(REST_SERVICE_URL); }
static void Main(string[] args) { // initialize MyActorSystem MyActorSystem = ActorSystem.Create("MyActorSystem"); var consoleWriterActor = MyActorSystem.ActorOf(Props.Create(() => new ConsoleWriterActor())); var consoleReaderActor = MyActorSystem.ActorOf(Props.Create(() => new ConsoleReaderActor(consoleWriterActor))); // tell console reader to begin consoleReaderActor.Tell(ConsoleReaderActor.StartCommand); // blocks the main thread from exiting until the actor system is shut down MyActorSystem.AwaitTermination(); }
private static GatewayRef[] StartGateway(ActorSystem system, ChannelType type, int port, int port2) { var serializer = PacketSerializer.CreatePacketSerializer(); var environment = new EntryActorEnvironment(); // First gateway var initiator = new GatewayInitiator { ListenEndPoint = new IPEndPoint(IPAddress.Any, port), GatewayLogger = LogManager.GetLogger("Gateway"), GatewayInitialized = a => { environment.Gateway = a.Cast<ActorBoundGatewayRef>(); }, CreateChannelLogger = (ep, _) => LogManager.GetLogger($"Channel({ep}"), ConnectionSettings = new TcpConnectionSettings { PacketSerializer = serializer }, PacketSerializer = serializer, CreateInitialActors = (context, connection) => new[] { Tuple.Create(context.ActorOf(Props.Create(() => new EntryActor(environment, context.Self.Cast<ActorBoundChannelRef>()))), new TaggedType[] { typeof(IEntry) }, (ActorBindingFlags)0) } }; var gateway = (type == ChannelType.Tcp) ? system.ActorOf(Props.Create(() => new TcpGateway(initiator))).Cast<GatewayRef>() : system.ActorOf(Props.Create(() => new UdpGateway(initiator))).Cast<GatewayRef>(); gateway.Start().Wait(); // Second gateway var initiator2 = new GatewayInitiator { ListenEndPoint = new IPEndPoint(IPAddress.Any, port2), ConnectEndPoint = new IPEndPoint(IPAddress.Loopback, port2), GatewayLogger = LogManager.GetLogger("Gateway2"), TokenRequired = true, GatewayInitialized = a => { environment.Gateway2nd = a.Cast<ActorBoundGatewayRef>(); }, CreateChannelLogger = (ep, _) => LogManager.GetLogger($"Channel2({ep}"), ConnectionSettings = new TcpConnectionSettings { PacketSerializer = serializer }, PacketSerializer = serializer, }; var gateway2 = (type == ChannelType.Tcp) ? system.ActorOf(Props.Create(() => new TcpGateway(initiator2))).Cast<GatewayRef>() : system.ActorOf(Props.Create(() => new UdpGateway(initiator2))).Cast<GatewayRef>(); gateway2.Start().Wait(); return new[] { gateway, gateway2 }; }
static void Main(string[] args) { _actorSystem = ActorSystem.Create("coach"); var actor = _actorSystem.ActorOf(Props.Empty.WithRouter(FromConfig.Instance), "event"); _actorSystem.ActorOf(Props.Create<StartSupervisorActor>(actor), "supervisor"); var startActor = _actorSystem.ActorSelection("/user/supervisor/start"); var counter = 0; Console.WriteLine("Node 1 started..."); Console.WriteLine("Press [ESC] to stop, [L] 1k messages, [H] for 10k, [M] for 100k or any other key to send a single message"); while (true) { ConsoleKeyInfo result = Console.ReadKey(); if (result.Key == ConsoleKey.Escape) { break; } switch (result.Key) { case ConsoleKey.L: { counter = TransmitMessageManyTimes(counter, startActor, 1000); break; } case ConsoleKey.H: { counter = TransmitMessageManyTimes(counter, startActor, 10000); break; } case ConsoleKey.M: { counter = TransmitMessageManyTimes(counter, startActor, 100000); break; } default: { counter = TransmitMessageManyTimes(counter, startActor, 1); break; } } //actor.Tell(new AuditMessage("Hi - " + counter.ToString())); } Console.ReadKey(); }
public bool Start(HostControl hostControl) { actorSystem = ActorSystem.Create("akkaconcert"); // System.Threading.Thread.Sleep(5000); var EventMaster = actorSystem.ActorOf(Props.Create<Concert>().WithRouter(FromConfig.Instance), "eventpool"); user = actorSystem.ActorOf( Props.Create(() => new User(EventMaster,1)),"user1"); Console.WriteLine("Running!"); return true; }
protected virtual void BuildActorSystem() { _clusterEvents? .Subscribe(ProcessClusterEvent); _actorSystem?.ActorOf(Props.Create <ClusterListenerActor>(_clusterEvents)); }
/// <summary> /// MultiNodeTestRunner takes the following <see cref="args"/>: /// /// C:\> Akka.MultiNodeTestRunner.exe [assembly name] [-Dmultinode.enable-filesink=on] [-Dmultinode.output-directory={dir path}] [-Dmultinode.spec={spec name}] /// /// <list type="number"> /// <listheader> /// <term>Argument</term> /// <description>The name and possible value of a given Akka.MultiNodeTestRunner.exe argument.</description> /// </listheader> /// <item> /// <term>AssemblyName</term> /// <description> /// The full path or name of an assembly containing as least one MultiNodeSpec in the current working directory. /// /// i.e. "Akka.Cluster.Tests.MultiNode.dll" /// "C:\akka.net\src\Akka.Cluster.Tests\bin\Debug\Akka.Cluster.Tests.MultiNode.dll" /// </description> /// </item> /// <item> /// <term>-Dmultinode.enable-filesink</term> /// <description>Having this flag set means that the contents of this test run will be saved in the /// current working directory as a .JSON file. /// </description> /// </item> /// <item> /// <term>-Dmultinode.multinode.output-directory</term> /// <description>Setting this flag means that any persistent multi-node test runner output files /// will be written to this directory instead of the default, which is the same folder /// as the test binary. /// </description> /// </item> /// <item> /// <term>-Dmultinode.listen-address={ip}</term> /// <description> /// Determines the address that this multi-node test runner will use to listen for log messages from /// individual NodeTestRunner.exe processes. /// /// Defaults to 127.0.0.1 /// </description> /// </item> /// <item> /// <term>-Dmultinode.listen-port={port}</term> /// <description> /// Determines the port number that this multi-node test runner will use to listen for log messages from /// individual NodeTestRunner.exe processes. /// /// Defaults to 6577 /// </description> /// </item> /// <item> /// <term>-Dmultinode.spec={spec name}</term> /// <description> /// Setting this flag means that only tests which contains the spec name will be executed /// otherwise all tests will be executed /// </description> /// </item> /// </list> /// </summary> static void Main(string[] args) { OutputDirectory = CommandLine.GetProperty("multinode.output-directory") ?? string.Empty; TestRunSystem = ActorSystem.Create("TestRunnerLogging"); SinkCoordinator = TestRunSystem.ActorOf(Props.Create <SinkCoordinator>(), "sinkCoordinator"); var listenAddress = IPAddress.Parse(CommandLine.GetPropertyOrDefault("multinode.listen-address", "127.0.0.1")); var listenPort = CommandLine.GetInt32OrDefault("multinode.listen-port", 6577); var listenEndpoint = new IPEndPoint(listenAddress, listenPort); var specName = CommandLine.GetPropertyOrDefault("multinode.spec", ""); var tcpLogger = TestRunSystem.ActorOf(Props.Create(() => new TcpLoggingServer(SinkCoordinator)), "TcpLogger"); TestRunSystem.Tcp().Tell(new Tcp.Bind(tcpLogger, listenEndpoint)); var assemblyName = Path.GetFullPath(args[0].Trim('"')); //unquote the string first EnableAllSinks(assemblyName); PublishRunnerMessage(String.Format("Running MultiNodeTests for {0}", assemblyName)); using (var controller = new XunitFrontController(AppDomainSupport.IfAvailable, assemblyName)) { using (var discovery = new Discovery()) { controller.Find(false, discovery, TestFrameworkOptions.ForDiscovery()); discovery.Finished.WaitOne(); foreach (var test in discovery.Tests.Reverse()) { if (!string.IsNullOrEmpty(test.Value.First().SkipReason)) { PublishRunnerMessage(string.Format("Skipping test {0}. Reason - {1}", test.Value.First().MethodName, test.Value.First().SkipReason)); continue; } if (!string.IsNullOrWhiteSpace(specName) && !test.Value[0].MethodName.Contains(specName)) { continue; } PublishRunnerMessage(string.Format("Starting test {0}", test.Value.First().MethodName)); var processes = new List <Process>(); StartNewSpec(test.Value); foreach (var nodeTest in test.Value) { //Loop through each test, work out number of nodes to run on and kick off process var process = new Process(); processes.Add(process); process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.FileName = "Akka.NodeTestRunner.exe"; process.StartInfo.Arguments = $@"-Dmultinode.test-assembly=""{assemblyName}"" -Dmultinode.test-class=""{ nodeTest.TypeName}"" -Dmultinode.test-method=""{nodeTest.MethodName }"" -Dmultinode.max-nodes={test.Value.Count} -Dmultinode.server-host=""{"localhost" }"" -Dmultinode.host=""{"localhost"}"" -Dmultinode.index={nodeTest.Node - 1 } -Dmultinode.listen-address={listenAddress} -Dmultinode.listen-port={listenPort}"; var nodeIndex = nodeTest.Node; //TODO: might need to do some validation here to avoid the 260 character max path error on Windows var folder = Directory.CreateDirectory(Path.Combine(OutputDirectory, nodeTest.MethodName)); var logFilePath = Path.Combine(folder.FullName, "node" + nodeIndex + ".txt"); var fileActor = TestRunSystem.ActorOf(Props.Create(() => new FileSystemAppenderActor(logFilePath))); process.OutputDataReceived += (sender, eventArgs) => { if (eventArgs?.Data != null) { fileActor.Tell(eventArgs.Data); } }; var closureTest = nodeTest; process.Exited += (sender, eventArgs) => { if (process.ExitCode == 0) { ReportSpecPassFromExitCode(nodeIndex, closureTest.TestName); } }; process.Start(); process.BeginOutputReadLine(); PublishRunnerMessage(string.Format("Started node {0} on pid {1}", nodeTest.Node, process.Id)); } foreach (var process in processes) { process.WaitForExit(); var exitCode = process.ExitCode; process.Close(); } PublishRunnerMessage("Waiting 3 seconds for all messages from all processes to be collected."); Thread.Sleep(TimeSpan.FromSeconds(3)); FinishSpec(); } } } Console.WriteLine("Complete"); PublishRunnerMessage("Waiting 5 seconds for all messages from all processes to be collected."); Thread.Sleep(TimeSpan.FromSeconds(5)); CloseAllSinks(); //Block until all Sinks have been terminated. TestRunSystem.WhenTerminated.Wait(TimeSpan.FromMinutes(1)); if (Debugger.IsAttached) { Console.ReadLine(); //block when debugging } //Return the proper exit code Environment.Exit(ExitCodeContainer.ExitCode); }
/// <summary> /// Configures the Akka Actor Syste, /// </summary> private static void StartAkka() { actorSystem = ActorSystem.Create("akka-playground"); _root = actorSystem.ActorOf(Props.Create <RootActor>(), "root"); }
static void Main(string[] args) { TestKit testKit = new TestKit(); ActorSystem actorSystem = testKit.Sys; using (actorSystem) { TestProbe probe = testKit.CreateTestProbe("test-probe"); /*In the first, we just test that we get back the list of * proper IDs once we have added a few devices.*/ Action test1 = new Action(() => { IActorRef deviceManagerActor = actorSystem.ActorOf(DeviceManager.Props("device-manager")); deviceManagerActor.Tell(new RequestTrackDevice("group", "device1"), probe.Ref); probe.ExpectMsg <DeviceRegistered>(); deviceManagerActor.Tell(new RequestTrackDevice("group", "device2"), probe.Ref); probe.ExpectMsg <DeviceRegistered>(); deviceManagerActor.Tell(new RequestDeviceList(requestId: 0), probe.Ref); probe.ExpectMsg <ReplyDeviceList>(s => s.RequestId == 0 && s.Ids.Contains("device1") && s.Ids.Contains("device2")); Console.WriteLine("Test 1 passed."); Console.WriteLine(""); }); test1.Invoke(); /*The second test case makes sure that the device ID * is properly removed after the device actor has been stopped.*/ Action test2 = new Action(() => { IActorRef deviceManagerActor = actorSystem.ActorOf(DeviceManager.Props("device-manager")); deviceManagerActor.Tell(new RequestTrackDevice("group", "device1"), probe.Ref); probe.ExpectMsg <DeviceRegistered>(); IActorRef toShutDown = probe.LastSender; deviceManagerActor.Tell(new RequestTrackDevice("group", "device2"), probe.Ref); probe.ExpectMsg <DeviceRegistered>(); deviceManagerActor.Tell(new RequestDeviceList(requestId: 0), probe.Ref); probe.ExpectMsg <ReplyDeviceList>(s => s.RequestId == 0 && s.Ids.Contains("device1") && s.Ids.Contains("device2")); probe.Watch(toShutDown); toShutDown.Tell(PoisonPill.Instance); probe.ExpectTerminated(toShutDown); // using awaitAssert to retry because it might take longer for the groupActor // to see the Terminated, that order is undefined probe.AwaitAssert(() => { deviceManagerActor.Tell(new RequestDeviceList(requestId: 1), probe.Ref); probe.ExpectMsg <ReplyDeviceList>(s => s.RequestId == 1 && s.Ids.Contains("device2")); }); Console.WriteLine("Test 2 passed."); Console.WriteLine(""); }); test2.Invoke(); Console.WriteLine("UserMessage: App is finished."); // Exit the system after ENTER is pressed Console.ReadLine(); } }
public AkkaIOTransport(ActorSystem system, Config config) { _settings = new Settings(config); _manager = system.ActorOf(Props.Create(() => new TransportManager()), "IO-TRANSPORT"); }
void IFeatureActorRef <TInterface> .Init(ActorSystem system, Func <Props> resolver) => Actor = system.ActorOf(resolver(), _name);
public static IActorRef CreateActorInDebugMode(this ActorSystem system, Props actorProps, string actorName, Action <object> messageLogger = null, string debugerPrefix = "DEBUG_") { return(system.ActorOf(Props.Create(() => new MainDebugModeActor(actorProps, debugerPrefix + actorName, messageLogger)), actorName)); }
public async Task <IActionResult> Login(ApplicationUser user, string returnUrl = null) { var use_sams = false; if (!string.IsNullOrWhiteSpace(_configuration["sams:is_enabled"])) { bool.TryParse(_configuration["sams:is_enabled"], out use_sams); } if (use_sams) { return(RedirectToAction("SignIn")); } const string badUserNameOrPasswordMessage = "Username or password is incorrect."; if ( user == null || string.IsNullOrWhiteSpace(user.UserName) || string.IsNullOrWhiteSpace(user.Password) ) { return(BadRequest(badUserNameOrPasswordMessage)); } try { var unsuccessful_login_attempts_number_before_lockout = Program.config_unsuccessful_login_attempts_number_before_lockout; var unsuccessful_login_attempts_within_number_of_minutes = Program.config_unsuccessful_login_attempts_within_number_of_minutes; var unsuccessful_login_attempts_lockout_number_of_minutes = Program.config_unsuccessful_login_attempts_lockout_number_of_minutes; var password_days_before_expires = Program.config_password_days_before_expires; var is_locked_out = false; var failed_login_count = 0; DateTime grace_period_date = DateTime.Now; try { //var session_event_request_url = $"{Program.config_couchdb_url}/session/_design/session_event_sortable/_view/by_date_created_user_id?startkey=[" + "{}" + $",\"{user.UserName}\"]&decending=true&limit={unsuccessful_login_attempts_number_before_lockout}"; var session_event_request_url = $"{Program.config_couchdb_url}/session/_design/session_event_sortable/_view/by_user_id?startkey=\"{user.UserName}\"&endkey=\"{user.UserName}\""; var session_event_curl = new cURL("GET", null, session_event_request_url, null, Program.config_timer_user_name, Program.config_timer_password); string response_from_server = await session_event_curl.executeAsync(); //var session_event_response = Newtonsoft.Json.JsonConvert.DeserializeObject<mmria.common.model.couchdb.get_sortable_view_reponse_object_key_header<mmria.common.model.couchdb.session_event>>(response_from_server); var session_event_response = Newtonsoft.Json.JsonConvert.DeserializeObject <mmria.common.model.couchdb.get_sortable_view_reponse_header <mmria.common.model.couchdb.session_event> >(response_from_server); DateTime first_item_date = DateTime.Now; DateTime last_item_date = DateTime.Now; var MaxRange = DateTime.Now.AddMinutes(-unsuccessful_login_attempts_within_number_of_minutes); session_event_response.rows.Sort(new mmria.common.model.couchdb.Compare_Session_Event_By_DateCreated <mmria.common.model.couchdb.session_event>()); /* * if(password_days_before_expires > 0) * { * var date_of_last_password_change = DateTime.MinValue; * * foreach(var session_event in session_event_response.rows) * { * if(session_event.value.action_result == mmria.common.model.couchdb.session_event.session_event_action_enum.password_changed) * { * date_of_last_password_change = session_event.value.date_created; * break; * } * } * * if(date_of_last_password_change != DateTime.MinValue) * { * days_til_password_expires = password_days_before_expires - (int)(DateTime.Now - date_of_last_password_change).TotalDays; * } * } */ foreach (var session_event in session_event_response.rows.Where(row => row.value.date_created >= MaxRange)) { if (session_event.value.action_result == mmria.common.model.couchdb.session_event.session_event_action_enum.failed_login) { failed_login_count++; if (failed_login_count == 1) { first_item_date = session_event.value.date_created; } if (failed_login_count >= unsuccessful_login_attempts_number_before_lockout) { last_item_date = session_event.value.date_created; grace_period_date = first_item_date.AddMinutes(unsuccessful_login_attempts_lockout_number_of_minutes); if (DateTime.Now < grace_period_date) { is_locked_out = true; break; } } } else if (session_event.value.action_result == mmria.common.model.couchdb.session_event.session_event_action_enum.successful_login) { break; } } } catch (Exception ex) { System.Console.WriteLine($"{ex}"); } if (is_locked_out) { return(RedirectToAction("Locked", new { user_name = user.UserName, grace_period_date = grace_period_date })); //return View("~/Views/Account/Locked.cshtml"); } string post_data = string.Format("name={0}&password={1}", user.UserName, user.Password); byte[] post_byte_array = System.Text.Encoding.ASCII.GetBytes(post_data); string request_string = Program.config_couchdb_url + "/_session"; System.Net.WebRequest request = System.Net.WebRequest.Create(new Uri(request_string)); //request.UseDefaultCredentials = true; request.PreAuthenticate = false; //request.Credentials = new System.Net.NetworkCredential("mmrds", "mmrds"); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = post_byte_array.Length; using (System.IO.Stream stream = request.GetRequestStream()) { stream.Write(post_byte_array, 0, post_byte_array.Length); } System.Net.WebResponse response = (System.Net.HttpWebResponse)request.GetResponse(); System.IO.Stream dataStream = response.GetResponseStream(); System.IO.StreamReader reader = new System.IO.StreamReader(dataStream); string responseFromServer = await reader.ReadToEndAsync(); mmria.common.model.couchdb.login_response json_result = Newtonsoft.Json.JsonConvert.DeserializeObject <mmria.common.model.couchdb.login_response>(responseFromServer); mmria.common.model.couchdb.login_response[] result = new mmria.common.model.couchdb.login_response[] { json_result }; this.Response.Headers.Add("Set-Cookie", response.Headers["Set-Cookie"]); string[] set_cookie = response.Headers["Set-Cookie"].Split(';'); string[] auth_array = set_cookie[0].Split('='); if (auth_array.Length > 1) { string auth_session_token = auth_array[1]; result[0].auth_session = auth_session_token; } else { result[0].auth_session = ""; } if (json_result.ok && !string.IsNullOrWhiteSpace(json_result.name)) { const string Issuer = "https://contoso.com"; var claims = new List <Claim>(); claims.Add(new Claim(ClaimTypes.Name, json_result.name, ClaimValueTypes.String, Issuer)); foreach (var role in json_result.roles) { if (role == "_admin") { claims.Add(new Claim(ClaimTypes.Role, "installation_admin", ClaimValueTypes.String, Issuer)); } } foreach (var role in mmria.server.util.authorization.get_current_user_role_jurisdiction_set_for(json_result.name).Select(jr => jr.role_name).Distinct()) { claims.Add(new Claim(ClaimTypes.Role, role, ClaimValueTypes.String, Issuer)); } //Response.Cookies.Append("uid", json_result.name); //Response.Cookies.Append("roles", string.Join(",",json_result.roles)); //claims.Add(new Claim("EmployeeId", string.Empty, ClaimValueTypes.String, Issuer)); //claims.Add(new Claim("EmployeeId", "123", ClaimValueTypes.String, Issuer)); //claims.Add(new Claim(ClaimTypes.DateOfBirth, "1970-06-08", ClaimValueTypes.Date)); //var userIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); var session_idle_timeout_minutes = 30; if (_configuration["mmria_settings:session_idle_timeout_minutes"] != null) { int.TryParse(_configuration["mmria_settings:session_idle_timeout_minutes"], out session_idle_timeout_minutes); } var userIdentity = new ClaimsIdentity("SuperSecureLogin"); userIdentity.AddClaims(claims); var userPrincipal = new ClaimsPrincipal(userIdentity); await HttpContext.SignInAsync( CookieAuthenticationDefaults.AuthenticationScheme, userPrincipal, new AuthenticationProperties { ExpiresUtc = DateTime.UtcNow.AddMinutes(session_idle_timeout_minutes), IsPersistent = false, AllowRefresh = false, }); } var Session_Event_Message = new mmria.server.model.actor.Session_Event_Message ( DateTime.Now, user.UserName, this.GetRequestIP(), json_result.ok && json_result.name != null? mmria.server.model.actor.Session_Event_Message.Session_Event_Message_Action_Enum.successful_login: mmria.server.model.actor.Session_Event_Message.Session_Event_Message_Action_Enum.failed_login ); _actorSystem.ActorOf(Props.Create <mmria.server.model.actor.Record_Session_Event>()).Tell(Session_Event_Message); //this.ActionContext.Response.Headers.Add("Set-Cookie", auth_session_token); } catch (Exception ex) { Console.WriteLine(ex); var Session_Event_Message = new mmria.server.model.actor.Session_Event_Message ( DateTime.Now, user.UserName, this.GetRequestIP(), mmria.server.model.actor.Session_Event_Message.Session_Event_Message_Action_Enum.failed_login ); _actorSystem.ActorOf(Props.Create <mmria.server.model.actor.Record_Session_Event>()).Tell(Session_Event_Message); } /* * var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme); * identity.AddClaim(new Claim(ClaimTypes.Name, lookupUser.UserName)); * * await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity)); */ if (returnUrl == null) { returnUrl = TempData["returnUrl"]?.ToString(); } if (returnUrl != null) { return(Redirect(returnUrl)); } return(RedirectToAction(nameof(HomeController.Index), "Home")); }
protected virtual IActorRef CreateForwardingActor(ActorSystem actorSystem) { return(actorSystem.ActorOf <ForwardingActor>("forwarder")); }
/// <summary> /// Creates an <see cref="EchoReceiver"/> actor which subscribes to the distributed pub/sub topic. /// This topic is filled with messages from the cluster seed job. /// </summary> static void RunDistributedPubSubClient(ActorSystem system) { var echo = system.ActorOf(Props.Create(() => new EchoReceiver())); echo.Tell(new object()); }
/// <summary> /// MultiNodeTestRunner takes the following <see cref="args"/>: /// /// C:\> Akka.MultiNodeTestRunner.exe [assembly name] [-Dmultinode.enable-filesink=on] /// /// <list type="number"> /// <listheader> /// <term>Argument</term> /// <description>The name and possible value of a given Akka.MultiNodeTestRunner.exe argument.</description> /// </listheader> /// <item> /// <term>AssemblyName</term> /// <description> /// The full path or name of an assembly containing as least one MultiNodeSpec in the current working directory. /// /// i.e. "Akka.Cluster.Tests.dll" /// "C:\akka.net\src\Akka.Cluster.Tests\bin\Debug\Akka.Cluster.Tests.dll" /// </description> /// </item> /// <item> /// <term>-Dmultinode.enable-filesink</term> /// <description>Having this flag set means that the contents of this test run will be saved in the /// current working directory as a .JSON file. /// </description> /// </item> /// </list> /// </summary> static void Main(string[] args) { TestRunSystem = ActorSystem.Create("TestRunnerLogging"); SinkCoordinator = TestRunSystem.ActorOf(Props.Create <SinkCoordinator>(), "sinkCoordinator"); var assemblyName = args[0]; EnableAllSinks(assemblyName); using (var controller = new XunitFrontController(assemblyName)) { using (var discovery = new Discovery()) { controller.Find(false, discovery, TestFrameworkOptions.ForDiscovery()); discovery.Finished.WaitOne(); foreach (var test in discovery.Tests.Reverse()) { PublishRunnerMessage(string.Format("Starting test {0}", test.Value.First().MethodName)); var processes = new List <Process>(); StartNewSpec(test.Value); foreach (var nodeTest in test.Value) { //Loop through each test, work out number of nodes to run on and kick off process var process = new Process(); processes.Add(process); process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.FileName = "Akka.NodeTestRunner.exe"; process.StartInfo.Arguments = String.Format(@"-Dmultinode.test-assembly=""{0}"" -Dmultinode.test-class=""{1}"" -Dmultinode.test-method=""{2}"" -Dmultinode.max-nodes={3} -Dmultinode.server-host=""{4}"" -Dmultinode.host=""{5}"" -Dmultinode.index={6}", assemblyName, nodeTest.TypeName, nodeTest.MethodName, test.Value.Count, "localhost", "localhost", nodeTest.Node - 1); var nodeIndex = nodeTest.Node; process.OutputDataReceived += (sender, line) => { //ignore any trailing whitespace if (string.IsNullOrEmpty(line.Data) || string.IsNullOrWhiteSpace(line.Data)) { return; } string message = line.Data; if (!message.StartsWith("[NODE", true, CultureInfo.InvariantCulture)) { message = "[NODE" + nodeIndex + "]" + message; } PublishToAllSinks(message); }; var closureTest = nodeTest; process.Exited += (sender, eventArgs) => { if (process.ExitCode == 0) { ReportSpecPassFromExitCode(nodeIndex, closureTest.TestName); } }; process.Start(); process.BeginOutputReadLine(); PublishRunnerMessage(string.Format("Started node {0} on pid {1}", nodeTest.Node, process.Id)); } foreach (var process in processes) { process.WaitForExit(); var exitCode = process.ExitCode; process.Close(); } PublishRunnerMessage("Waiting 3 seconds for all messages from all processes to be collected."); Thread.Sleep(TimeSpan.FromSeconds(3)); FinishSpec(); } } } Console.WriteLine("Complete"); PublishRunnerMessage("Waiting 5 seconds for all messages from all processes to be collected."); Thread.Sleep(TimeSpan.FromSeconds(5)); CloseAllSinks(); //Block until all Sinks have been terminated. TestRunSystem.AwaitTermination(TimeSpan.FromMinutes(1)); //Return the proper exit code Environment.Exit(ExitCodeContainer.ExitCode); }
public AkkaProtocolStressTest(ITestOutputHelper output) : base(AkkaProtocolStressTestConfig, output) { systemB = ActorSystem.Create("systemB", Sys.Settings.Config); remote = systemB.ActorOf(Props.Create <Echo>(), "echo"); }
/// <summary> /// Starts a job, which establishes cluster client receptionist for target <see cref="EchoReceiver"/> actor, /// making it visible from outside of the cluster. /// </summary> static void RunClusterClientSeed(ActorSystem system) { var receptionist = ClusterClientReceptionist.Get(system); receptionist.RegisterService(system.ActorOf(Props.Create <EchoReceiver>(), "my-service")); }
private void CreateTopLevelActors() { _system.ActorOf(ServerActor.Props(), ActorPaths.ServerActor.Name); }
/// <summary> /// MultiNodeTestRunner takes the following <see cref="args"/>: /// /// C:\> Akka.MultiNodeTestRunner.exe [assembly name] [-Dmultinode.enable-filesink=on] [-Dmultinode.output-directory={dir path}] [-Dmultinode.spec={spec name}] /// /// <list type="number"> /// <listheader> /// <term>Argument</term> /// <description>The name and possible value of a given Akka.MultiNodeTestRunner.exe argument.</description> /// </listheader> /// <item> /// <term>AssemblyName</term> /// <description> /// The full path or name of an assembly containing as least one MultiNodeSpec in the current working directory. /// /// i.e. "Akka.Cluster.Tests.MultiNode.dll" /// "C:\akka.net\src\Akka.Cluster.Tests\bin\Debug\Akka.Cluster.Tests.MultiNode.dll" /// </description> /// </item> /// <item> /// <term>-Dmultinode.enable-filesink</term> /// <description>Having this flag set means that the contents of this test run will be saved in the /// current working directory as a .JSON file. /// </description> /// </item> /// <item> /// <term>-Dmultinode.multinode.output-directory</term> /// <description>Setting this flag means that any persistent multi-node test runner output files /// will be written to this directory instead of the default, which is the same folder /// as the test binary. /// </description> /// </item> /// <item> /// <term>-Dmultinode.listen-address={ip}</term> /// <description> /// Determines the address that this multi-node test runner will use to listen for log messages from /// individual NodeTestRunner.exe processes. /// /// Defaults to 127.0.0.1 /// </description> /// </item> /// <item> /// <term>-Dmultinode.listen-port={port}</term> /// <description> /// Determines the port number that this multi-node test runner will use to listen for log messages from /// individual NodeTestRunner.exe processes. /// /// Defaults to 6577 /// </description> /// </item> /// <item> /// <term>-Dmultinode.spec={spec name}</term> /// <description> /// Setting this flag means that only tests which contains the spec name will be executed /// otherwise all tests will be executed /// </description> /// </item> /// </list> /// </summary> static void Main(string[] args) { OutputDirectory = CommandLine.GetPropertyOrDefault("multinode.output-directory", string.Empty); FailedSpecsDirectory = CommandLine.GetPropertyOrDefault("multinode.failed-specs-directory", "FAILED_SPECS_LOGS"); TestRunSystem = ActorSystem.Create("TestRunnerLogging"); var suiteName = Path.GetFileNameWithoutExtension(Path.GetFullPath(args[0].Trim('"'))); var teamCityFormattingOn = CommandLine.GetPropertyOrDefault("multinode.teamcity", "false"); if (!Boolean.TryParse(teamCityFormattingOn, out TeamCityFormattingOn)) { throw new ArgumentException("Invalid argument provided for -Dteamcity"); } var listenAddress = IPAddress.Parse(CommandLine.GetPropertyOrDefault("multinode.listen-address", "127.0.0.1")); var listenPort = CommandLine.GetInt32OrDefault("multinode.listen-port", 6577); var listenEndpoint = new IPEndPoint(listenAddress, listenPort); var specName = CommandLine.GetPropertyOrDefault("multinode.spec", ""); var platform = CommandLine.GetPropertyOrDefault("multinode.platform", "net"); var reporter = CommandLine.GetPropertyOrDefault("multinode.reporter", "console"); var clearOutputDirectory = CommandLine.GetInt32OrDefault("multinode.clear-output", 0); if (clearOutputDirectory > 0 && Directory.Exists(OutputDirectory)) { Directory.Delete(OutputDirectory, true); } Props coordinatorProps; switch (reporter.ToLowerInvariant()) { case "trx": coordinatorProps = Props.Create(() => new SinkCoordinator(new[] { new TrxMessageSink(suiteName) })); break; case "teamcity": coordinatorProps = Props.Create(() => new SinkCoordinator(new[] { new TeamCityMessageSink(Console.WriteLine, suiteName) })); break; case "console": coordinatorProps = Props.Create(() => new SinkCoordinator(new[] { new ConsoleMessageSink() })); break; default: throw new ArgumentException($"Given reporter name '{reporter}' is not understood, valid reporters are: trx and teamcity"); } SinkCoordinator = TestRunSystem.ActorOf(coordinatorProps, "sinkCoordinator"); #if CORECLR if (!_validNetCorePlatform.Contains(platform)) { throw new Exception($"Target platform not supported: {platform}. Supported platforms are net and netcore"); } #else if (platform != "net") { throw new Exception($"Target platform not supported: {platform}. Supported platforms are net"); } #endif var tcpLogger = TestRunSystem.ActorOf(Props.Create(() => new TcpLoggingServer(SinkCoordinator)), "TcpLogger"); TestRunSystem.Tcp().Tell(new Tcp.Bind(tcpLogger, listenEndpoint), sender: tcpLogger); var assemblyPath = Path.GetFullPath(args[0].Trim('"')); //unquote the string first EnableAllSinks(assemblyPath, platform); PublishRunnerMessage($"Running MultiNodeTests for {assemblyPath}"); #if CORECLR // In NetCore, if the assembly file hasn't been touched, // XunitFrontController would fail loading external assemblies and its dependencies. var assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(assemblyPath); var asms = assembly.GetReferencedAssemblies(); var basePath = Path.GetDirectoryName(assemblyPath); foreach (var asm in asms) { try { Assembly.Load(new AssemblyName(asm.FullName)); } catch (Exception) { var path = Path.Combine(basePath, asm.Name + ".dll"); try { AssemblyLoadContext.Default.LoadFromAssemblyPath(path); } catch (Exception e) { Console.Out.WriteLine($"Failed to load dll: {path}"); } } } #endif using (var controller = new XunitFrontController(AppDomainSupport.IfAvailable, assemblyPath)) { using (var discovery = new Discovery()) { controller.Find(false, discovery, TestFrameworkOptions.ForDiscovery()); discovery.Finished.WaitOne(); if (discovery.WasSuccessful) { foreach (var test in discovery.Tests.Reverse()) { if (!string.IsNullOrEmpty(test.Value.First().SkipReason)) { PublishRunnerMessage($"Skipping test {test.Value.First().MethodName}. Reason - {test.Value.First().SkipReason}"); continue; } if (!string.IsNullOrWhiteSpace(specName) && CultureInfo.InvariantCulture.CompareInfo.IndexOf(test.Value.First().TestName, specName, CompareOptions.IgnoreCase) < 0) { PublishRunnerMessage($"Skipping [{test.Value.First().MethodName}] (Filtering)"); continue; } var processes = new List <Process>(); PublishRunnerMessage($"Starting test {test.Value.First().MethodName}"); Console.Out.WriteLine($"Starting test {test.Value.First().MethodName}"); StartNewSpec(test.Value); #if CORECLR var ntrNetPath = Path.Combine(AppContext.BaseDirectory, "Akka.NodeTestRunner.exe"); var ntrNetCorePath = Path.Combine(AppContext.BaseDirectory, "Akka.NodeTestRunner.dll"); var alternateIndex = 0; #endif var timelineCollector = TestRunSystem.ActorOf(Props.Create(() => new TimelineLogCollectorActor())); string testOutputDir = null; string runningSpecName = null; foreach (var nodeTest in test.Value) { //Loop through each test, work out number of nodes to run on and kick off process var sbArguments = new StringBuilder() //.Append($@"-Dmultinode.test-assembly=""{assemblyPath}"" ") .Append($@"-Dmultinode.test-class=""{nodeTest.TypeName}"" ") .Append($@"-Dmultinode.test-method=""{nodeTest.MethodName}"" ") .Append($@"-Dmultinode.max-nodes={test.Value.Count} ") .Append($@"-Dmultinode.server-host=""{"localhost"}"" ") .Append($@"-Dmultinode.host=""{"localhost"}"" ") .Append($@"-Dmultinode.index={nodeTest.Node - 1} ") .Append($@"-Dmultinode.role=""{nodeTest.Role}"" ") .Append($@"-Dmultinode.listen-address={listenAddress} ") .Append($@"-Dmultinode.listen-port={listenPort} "); #if CORECLR string fileName = null; switch (platform) { case "net": fileName = ntrNetPath; sbArguments.Insert(0, $@" -Dmultinode.test-assembly=""{assemblyPath}"" "); break; case "netcore": fileName = "dotnet"; sbArguments.Insert(0, $@" -Dmultinode.test-assembly=""{assemblyPath}"" "); sbArguments.Insert(0, ntrNetCorePath); break; } var process = new Process { StartInfo = new ProcessStartInfo { FileName = fileName, UseShellExecute = false, RedirectStandardOutput = true, Arguments = sbArguments.ToString(), WorkingDirectory = Path.GetDirectoryName(assemblyPath) } }; #else sbArguments.Insert(0, $@"-Dmultinode.test-assembly=""{assemblyPath}"" "); var process = new Process { StartInfo = new ProcessStartInfo { FileName = "Akka.NodeTestRunner.exe", UseShellExecute = false, RedirectStandardOutput = true, Arguments = sbArguments.ToString() } }; #endif processes.Add(process); var nodeIndex = nodeTest.Node; var nodeRole = nodeTest.Role; #if CORECLR if (platform == "netcore") { process.StartInfo.FileName = "dotnet"; process.StartInfo.Arguments = ntrNetCorePath + " " + process.StartInfo.Arguments; process.StartInfo.WorkingDirectory = Path.GetDirectoryName(assemblyPath); } #endif //TODO: might need to do some validation here to avoid the 260 character max path error on Windows var folder = Directory.CreateDirectory(Path.Combine(OutputDirectory, nodeTest.TestName)); testOutputDir = testOutputDir ?? folder.FullName; var logFilePath = Path.Combine(folder.FullName, $"node{nodeIndex}__{nodeRole}__{platform}.txt"); runningSpecName = nodeTest.TestName; var nodeInfo = new TimelineLogCollectorActor.NodeInfo(nodeIndex, nodeRole, platform, nodeTest.TestName); var fileActor = TestRunSystem.ActorOf(Props.Create(() => new FileSystemAppenderActor(logFilePath))); process.OutputDataReceived += (sender, eventArgs) => { if (eventArgs?.Data != null) { fileActor.Tell(eventArgs.Data); timelineCollector.Tell(new TimelineLogCollectorActor.LogMessage(nodeInfo, eventArgs.Data)); if (TeamCityFormattingOn) { // teamCityTest.WriteStdOutput(eventArgs.Data); TODO: open flood gates } } }; var closureTest = nodeTest; process.Exited += (sender, eventArgs) => { if (process.ExitCode == 0) { ReportSpecPassFromExitCode(nodeIndex, nodeRole, closureTest.TestName); } }; process.Start(); process.BeginOutputReadLine(); PublishRunnerMessage($"Started node {nodeIndex} : {nodeRole} on pid {process.Id}"); } var specFailed = false; foreach (var process in processes) { process.WaitForExit(); specFailed = specFailed || process.ExitCode > 0; process.Dispose(); } PublishRunnerMessage("Waiting 3 seconds for all messages from all processes to be collected."); Thread.Sleep(TimeSpan.FromSeconds(3)); if (testOutputDir != null) { var dumpTasks = new List <Task>() { // Dump aggregated timeline to file for this test timelineCollector.Ask <Done>(new TimelineLogCollectorActor.DumpToFile(Path.Combine(testOutputDir, "aggregated.txt"))), // Print aggregated timeline into the console timelineCollector.Ask <Done>(new TimelineLogCollectorActor.PrintToConsole()) }; if (specFailed) { var dumpFailureArtifactTask = timelineCollector.Ask <Done>( new TimelineLogCollectorActor.DumpToFile(Path.Combine(Path.GetFullPath(OutputDirectory), FailedSpecsDirectory, $"{runningSpecName}.txt"))); dumpTasks.Add(dumpFailureArtifactTask); } Task.WaitAll(dumpTasks.ToArray()); } FinishSpec(test.Value, timelineCollector); } Console.WriteLine("Complete"); PublishRunnerMessage("Waiting 5 seconds for all messages from all processes to be collected."); Thread.Sleep(TimeSpan.FromSeconds(5)); } else { var sb = new StringBuilder(); sb.AppendLine("One or more exception was thrown while discovering test cases. Test Aborted."); foreach (var err in discovery.Errors) { for (int i = 0; i < err.ExceptionTypes.Length; ++i) { sb.AppendLine(); sb.Append($"{err.ExceptionTypes[i]}: {err.Messages[i]}"); sb.Append(err.StackTraces[i]); } } PublishRunnerMessage(sb.ToString()); Console.Out.WriteLine(sb.ToString()); } } } AbortTcpLoggingServer(tcpLogger); CloseAllSinks(); //Block until all Sinks have been terminated. TestRunSystem.WhenTerminated.Wait(TimeSpan.FromMinutes(1)); if (Debugger.IsAttached) { Console.ReadLine(); //block when debugging } //Return the proper exit code Environment.Exit(ExitCodeContainer.ExitCode); }
private static void CreateReaderActor() => wintailActorSystem.ActorOf(Props.Create(() => new ConsoleReaderActor(CreateWriterActor())), "consoleReader").Tell(("start"));
public CalculatorActorInstance(ActorSystem actorSystem) { _actor = actorSystem.ActorOf(Props.Create <CalculatorActor>(), "Calculator"); }
protected override void Load(ContainerBuilder builder) { //TODO: Expose and register this as appart of configuration system ActorAssemblyDefinitionConfiguration actorAssemblyConfig = new ActorAssemblyDefinitionConfiguration(Array.Empty <string>()); foreach (var s in actorAssemblyConfig.AssemblyNames) { Debug.Log($"Actor Assembly: {s}"); } Debug.Log(AppDomain.CurrentDomain.GetAssemblies().Aggregate("Loaded Assemblies: ", (s, assembly) => $"{s} {assembly.GetName().Name}")); //The below loads the actor assemblies defined in the configuration. //It then searches for all message handlers and then registers them. //It's a complicated process. //TODO: Support actually loading unloaded assemblies (like 3rd party user assemblies) foreach (Assembly actorAssemblyToParse in actorAssemblyConfig.AssemblyNames .Select(d => AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => d == a.GetName().Name.ToLower())) .Where(a => a != null)) { Debug.Log($"Parsing ActorAssembly: {actorAssemblyToParse.GetName().Name}"); foreach (Type t in actorAssemblyToParse.GetTypes()) { //If they have the handler attribute, we should just register it. if (t.GetCustomAttributes <EntityActorMessageHandlerAttribute>().Any()) { Debug.Log($"Register ActorMessageHandler: {t.Name}"); //Now we need to find the actor state type Type actorStateType = t.GetInterfaces() .First(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IEntityActorMessageHandler <,>)) .GenericTypeArguments.First(); var handlerRegisteration = builder.RegisterType(t) .AsSelf() .As(typeof(IEntityActorMessageHandler <,>).MakeGenericType(new Type[2] { actorStateType, typeof(EntityActorMessage) })) .As <IEntityActorMessageHandler>() .SingleInstance(); foreach (var attri in t.GetCustomAttributes <EntityActorMessageHandlerAttribute>()) { //TODO: Support multiple level inherited types. //If the actor has a different state type we should assume it's valid if it can be assigned. Type specificActorStateType = attri.TargetActorType.BaseType.GenericTypeArguments.Reverse().First(); if (specificActorStateType != actorStateType) { if (actorStateType.IsAssignableFrom(specificActorStateType)) { handlerRegisteration = handlerRegisteration .As(typeof(IEntityActorMessageHandler <,>).MakeGenericType(new Type[2] { specificActorStateType, typeof(EntityActorMessage) })); } else { throw new InvalidOperationException($"Actor: {attri.TargetActorType.Name} attempted to use Handler: {t.Name} but had non-matching state Types: {actorStateType.Name}/{specificActorStateType.Name}"); } } } } else if (typeof(IEntityActor).IsAssignableFrom(t)) { //Don't want to register abstract entities. if (!t.IsAbstract) { Debug.Log($"Register Actor: {t.Name}"); builder.RegisterType(t) .AsSelf(); } } } } //Below is an open generic registeration of the generic router //this makes it EASY to inject into the actors builder.RegisterGeneric(typeof(ReflectionBasedGenericMessageRouter <,>)) .As(typeof(IEntityActorMessageRouteable <,>)) .SingleInstance(); //Create the root of the actor system. builder.RegisterInstance(ActorSystem.Create("Root")) .AsSelf() .As <ActorSystem>() .As <IActorRefFactory>() .SingleInstance(); builder.Register <IScheduler>(context => { ActorSystem actorSystem = context.Resolve <ActorSystem>(); return(actorSystem.Scheduler); }) .As <IScheduler>() .SingleInstance(); //Creates the autofac dependency resolver that can be used to actually resolve //the Actor's dependencies. builder.Register(context => { if (!context.IsRegistered <IEntityActorMessageRouteable <DefaultWorldActor, WorldActorState> >()) { Debug.LogError($"CRITICAL dependency for Actor IOC not registered."); } if (!context.IsRegistered <DefaultWorldActor>()) { Debug.LogError($"CRITICAL dependency for Actor IOC not registered."); } return(new AutoFacDependencyResolver(context.Resolve <ILifetimeScope>(), context.Resolve <ActorSystem>())); }) .As <IDependencyResolver>() .AsSelf() .SingleInstance(); builder.RegisterType <DefaultWorldActor>() .AsSelf(); builder.RegisterType <UnityAkkaActorLoggerAdapter>() .AsSelf() .As <ILoggingAdapter>() .SingleInstance(); builder.RegisterType <UnityLoggerActor>() .AsSelf(); builder.RegisterType <DefaultGameObjectEntityActorFactory>() .As <IGameObjectEntityActorFactory>() .SingleInstance(); //This creates the World actor. builder.Register(context => { try { IDependencyResolver resolver = context.Resolve <IDependencyResolver>(); ActorSystem actorSystem = context.Resolve <ActorSystem>(); actorSystem.ActorOf(resolver.Create <UnityLoggerActor>(), "Logger"); IActorRef worldActorReference = actorSystem.ActorOf(resolver.Create <DefaultWorldActor>(), "World"); if (worldActorReference.IsNobody()) { Debug.LogError($"FAILED TO CREATE WORLD ACTOR."); } return(new WorldActorReferenceAdapter(worldActorReference)); } catch (Exception e) { Debug.LogError($"Failed to create WorldActor in IoC. Reason: {e.Message}\n\nStack: {e.StackTrace}"); throw; } }) .As <IWorldActorRef>() .SingleInstance(); }
public bool Start(HostControl hostControl) { ClusterSystem = ActorSystem.Create("sys"); ClusterSystem.ActorOf(Props.Create(() => new ApiMaster()).WithRouter(FromConfig.Instance), "api"); return(true); }
public void Restarting_cluster_node_with_same_hostname_and_port_must_handover_to_next_oldest() { Join(_sys1, _sys1); Join(_sys2, _sys1); var proxy2 = _sys2.ActorOf( ClusterSingletonProxy.Props("user/echo", ClusterSingletonProxySettings.Create(_sys2)), "proxy2"); Within(TimeSpan.FromSeconds(5), () => { AwaitAssert(() => { var probe = CreateTestProbe(_sys2); proxy2.Tell("hello", probe.Ref); probe.ExpectMsg("hello", TimeSpan.FromSeconds(1)); }); }); Shutdown(_sys1); // it will be downed by the join attempts of the new incarnation // ReSharper disable once PossibleInvalidOperationException var sys1Port = Cluster.Get(_sys1).SelfAddress.Port.Value; var sys3Config = ConfigurationFactory.ParseString(@"akka.remote.dot-netty.tcp.port=" + sys1Port) .WithFallback(_sys1.Settings.Config); _sys3 = ActorSystem.Create(_sys1.Name, sys3Config); Join(_sys3, _sys2); Within(TimeSpan.FromSeconds(5), () => { AwaitAssert(() => { var probe = CreateTestProbe(_sys2); proxy2.Tell("hello2", probe.Ref); probe.ExpectMsg("hello2", TimeSpan.FromSeconds(1)); }); }); Cluster.Get(_sys2).Leave(Cluster.Get(_sys2).SelfAddress); Within(TimeSpan.FromSeconds(15), () => { AwaitAssert(() => { Cluster.Get(_sys3) .State.Members.Select(x => x.UniqueAddress) .Should() .Equal(Cluster.Get(_sys3).SelfUniqueAddress); }); }); var proxy3 = _sys3.ActorOf(ClusterSingletonProxy.Props("user/echo", ClusterSingletonProxySettings.Create(_sys3)), "proxy3"); Within(TimeSpan.FromSeconds(5), () => { AwaitAssert(() => { var probe = CreateTestProbe(_sys3); proxy3.Tell("hello3", probe.Ref); probe.ExpectMsg("hello3", TimeSpan.FromSeconds(1)); }); }); }
/// <summary> /// Requires RemoteActorViewerActorAddress to be in app config in order to call CreateActorInDebugMode //todo : pass address from here /// </summary> public static IActorRef CreateActorInDebugMode <TActorType>(this ActorSystem system, ActorSetUpOptions options = null, Action <object> messageLogger = null, string debugerPrefix = "DEBUG_") where TActorType : ActorBase { var actorName = typeof(TActorType).Name; return(system.ActorOf(Props.Create(() => new MainDebugModeActor(GetActorProps <TActorType>(system, options), debugerPrefix + actorName, messageLogger)), actorName)); }
public static IActorRef CreateInstance(ActorSystem actorSystem, IMemberRepository memberRepository) { return(actorSystem.ActorOf(Props.Create(typeof(MembershipActor), memberRepository), "Membership")); }
/// <summary> /// Initialize actors. /// </summary> private void InitializeActors() { var processorManager = _system.ActorOf <MessageIngestor>(ActorPaths.MessageIngestor.Name); var indexer = _system.ActorOf(_system.DI().Props <Indexer>(), ActorPaths.Indexer.Name); var userManager = _system.ActorOf(_system.DI().Props <UserManager>(), ActorPaths.UserManager.Name); }
static void Main(string[] args) { MovieStreamingActorSystem = ActorSystem.Create("MovieStreamingActorSystem"); Console.WriteLine("Actor system created"); var playbackActorProps = Props.Create <PlaybackActor>(); IActorRef playbackActorRef = MovieStreamingActorSystem.ActorOf(playbackActorProps, "Playback"); //IActorRef playbackActorRef = MovieStreamingActorSystem // .ActorSelection("akka.tcp://[email protected]:8092/user/Playback") // .ResolveOne(TimeSpan.FromSeconds(3)) // .Result; IActorRef userActorRef = MovieStreamingActorSystem.ActorOf <UserActor>("UserActor"); do { Thread.Sleep(500); Console.WriteLine(); var cmd = Console.ReadLine(); if (cmd.StartsWith("play")) { var userId = int.Parse(cmd.Split(',')[1]); var title = cmd.Split(',')[2]; var msg = new PlayMovieMessage(title, userId); MovieStreamingActorSystem.ActorSelection("/user/Playback/UserCoordinator").Tell(msg); } if (cmd.StartsWith("stop")) { var userId = int.Parse(cmd.Split(',')[1]); var title = cmd.Split(',')[2]; var msg = new StopMovieMessage(userId); MovieStreamingActorSystem.ActorSelection("/user/Playback/UserCoordinator").Tell(msg); } if (cmd == "exit") { MovieStreamingActorSystem.Terminate(); Console.ReadKey(); Environment.Exit(1); } } while (true); //userActorRef.Tell(new PlayMovieMessage("Akka The Movie", 9)); //Console.ReadLine(); //userActorRef.Tell(new StopMovieMessage()); //Console.ReadLine(); //userActorRef.Tell(new PlayMovieMessage("test1", 9)); //Console.ReadLine(); //userActorRef.Tell(new StopMovieMessage()); //Console.ReadLine(); //userActorRef.Tell(new PlayMovieMessage("test2", 9)); //Console.ReadLine(); //userActorRef.Tell(new StopMovieMessage()); //Console.ReadLine(); //userActorRef.Tell(new PlayMovieMessage("test3", 9)); //Console.ReadLine(); //userActorRef.Tell(new StopMovieMessage()); //Console.ReadLine(); //userActorRef.Tell(new StopMovieMessage()); //Console.ReadLine(); MovieStreamingActorSystem.Terminate(); }
public void StartConsensus(Wallet wallet) { Consensus = ActorSystem.ActorOf(ConsensusService.Props(this.LocalNode, this.TaskManager, wallet)); Consensus.Tell(new ConsensusService.Start()); }
private IInternalActorRef CreateRemoteActor(Props props, string name) { _remoteSystem.ActorOf(props, name); Sys.ActorSelection(new RootActorPath(_remoteAddress) / "user" / name).Tell(new Identify(name), TestActor); return(ExpectMsg <ActorIdentity>().Subject.AsInstanceOf <IInternalActorRef>()); }
public void Start() { _actorSystem = ActorSystem.Create("api").WithIocContainer(); _processingMaster = _actorSystem.ActorOf <DocumentImageProcessingMaster>("image-processing"); }
public async System.Threading.Tasks.Task <mmria.common.model.couchdb.document_put_response> Post([FromBody] export_queue_item queue_item) { //bool valid_login = false; //mmria.common.data.api.Set_Queue_Request queue_request = null; mmria.common.model.couchdb.document_put_response result = new mmria.common.model.couchdb.document_put_response(); /* * try * { * * System.IO.Stream dataStream0 = await this.Request.Content.ReadAsStreamAsync(); * // Open the stream using a StreamReader for easy access. * //dataStream0.Seek(0, System.IO.SeekOrigin.Begin); * System.IO.StreamReader reader0 = new System.IO.StreamReader (dataStream0); * // Read the content. * object_string = reader0.ReadToEnd (); * * queue_item = Newtonsoft.Json.JsonConvert.DeserializeObject<export_queue_item>(object_string); * * } * catch(Exception ex) * { * //Console.WriteLine (ex); * } */ //if(queue_request.case_list.Length == 1) try { Newtonsoft.Json.JsonSerializerSettings settings = new Newtonsoft.Json.JsonSerializerSettings(); settings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore; string object_string = Newtonsoft.Json.JsonConvert.SerializeObject(queue_item, settings); string export_queue_request_url = Program.config_couchdb_url + "/export_queue/" + queue_item._id; var export_queue_curl = new cURL("PUT", null, export_queue_request_url, object_string, Program.config_timer_user_name, Program.config_timer_password); string responseFromServer = await export_queue_curl.executeAsync(); result = Newtonsoft.Json.JsonConvert.DeserializeObject <mmria.common.model.couchdb.document_put_response>(responseFromServer); if ( result.ok && ( queue_item.status.StartsWith("In Queue...", StringComparison.OrdinalIgnoreCase) || queue_item.status.StartsWith("Deleted", StringComparison.OrdinalIgnoreCase) ) ) { var juris_user_name = User.Claims.Where(c => c.Type == ClaimTypes.Name).FirstOrDefault().Value; mmria.server.model.actor.ScheduleInfoMessage new_scheduleInfo = new mmria.server.model.actor.ScheduleInfoMessage ( Program.config_cron_schedule, Program.config_couchdb_url, Program.config_timer_user_name, Program.config_timer_password, Program.config_export_directory, juris_user_name ); //_actorSystem.ActorOf(Props.Create<mmria.server.model.actor.quartz.Process_Export_Queue>(), "Process_Export_Queue").Tell(new_scheduleInfo); _actorSystem.ActorOf(Props.Create <mmria.server.model.actor.quartz.Process_Export_Queue>()).Tell(new_scheduleInfo); } else // if (!result.ok) { } } catch (Exception ex) { //Console.Write("auth_session_token: {0}", auth_session_token); //Console.WriteLine (ex); } return(result); }
public ThrottlerTransportAdapterSpec(ITestOutputHelper output) : base(ThrottlerTransportAdapterSpecConfig, output) { systemB = ActorSystem.Create("systemB", Sys.Settings.Config); remote = systemB.ActorOf(Props.Create <Echo>(), "echo"); }
private static void InitializeDevicesActor(ActorSystem actorSystem) { actorSystem.ActorOf(DevicesActor.CreateProps(), "devices"); }