Exemplo n.º 1
0
        static void Main(string[] args)
        {
            var section = (AkkaConfigurationSection)ConfigurationManager.GetSection("akka");
            _system = ActorSystem.Create("test", section.AkkaConfig);

            _coordinator = _system.ActorOf(Props.Create(() => new IdentityActor())
                .WithRouter(FromConfig.Instance), "fred");

            //_coordinator =
            //    _system.ActorOf(Props.Create(() => new IdentityActor()).WithRouter(new ConsistentHashingPool(5000)),
            //        "fred2");

            int routees = _coordinator.Ask<Routees>(new GetRoutees()).Result.Members.Count();
            Console.WriteLine(routees);

            // Lazy wait for the co-ordinator to deploy.
            Thread.Sleep(5000);

            for (int i = 1; i <= 5000; i++)
            {
                for (int x = 1; x <= 4; x++)
                {
                    _coordinator.Tell(new EntityMessage<long>(i));
                }
            }

            Thread.Sleep(500);

            Console.ReadLine();
        }
        public IdentityManagerActor(IActorRef authenticationActor, TimeSpan timeout)
        {
            _authenticator = authenticationActor;
            _timeout = timeout;

            Receive<CreateUser>(create =>
            {
                // since we're using the PipeTo pattern, we need to close over state
                // that can change between messages, such as Sender
                // for more, see the PipeTo sample: https://github.com/petabridge/akkadotnet-code-samples/tree/master/PipeTo
                var senderClosure = Sender;

                // this actor needs it create user request to be authenticated
                // within 2 seconds or this operation times out & cancels 
                // the Task returned by Ask<>
                _authenticator.Ask<UserResult>(create, _timeout)
                    .ContinueWith(tr =>
                    {
                        // if the task got messed up / failed, return failure result
                        if (tr.IsCanceled || tr.IsFaulted)
                            return new UserResult(false);

                        // otherwise return whatever the actual result was
                        return tr.Result;
                    }).PipeTo(senderClosure);
            });
        }
Exemplo n.º 3
0
        public ActorSelectionSpec() : base(Config)
        {
            _c1 = Sys.ActorOf(Props, "c1");
            _c2 = Sys.ActorOf(Props, "c2");
            _c21 = _c2.Ask<IActorRef>(new Create("c21")).Result;

            _all = new[] {_c1, _c2, _c21};
        }
Exemplo n.º 4
0
        private static void CreateAd(IActorRef adsRoot, string adName, string adUrl, decimal pricePerImpression, decimal availableFunds, params string[] keywords)
        {
            IActorRef adActor = adsRoot.Ask<IActorRef>(new CreateAd(adName)).Result; // Create the ad and keep a reference.
            adActor.Tell(new SetPrice(pricePerImpression));
            adActor.Tell(new SetKeywords(keywords));
            adActor.Tell(new SetAdUrl(adUrl));
            adActor.Tell(new AddFunds(availableFunds));

            _allAdActors.Add(adActor);
        }
Exemplo n.º 5
0
        private IActorRef AskNode(IActorRef node, IQuery query)
        {
            var result = node.Ask(query).Result;

            var actorRef = result as IActorRef;
            if (actorRef != null)
                return actorRef;
            
            var selection = result as ActorSelection;
            return selection != null ? Identify(selection) : null;
        }
Exemplo n.º 6
0
        private static void StressPersistentActor(IActorRef pref, long? failAt, string description)
        {
            if (failAt.HasValue) pref.Tell(new FailAt(failAt.Value));

            var m = new Measure(LoadCycles);
            m.StartMeasure();

            for (int i = 1; i <= LoadCycles; i++) pref.Tell("msg" + i);

            pref.Ask(StopMeasure.Instance, TimeSpan.FromSeconds(100)).Wait();
            var ratio = m.StopMeasure();
            Console.WriteLine("Throughtput: {0} {1} per second", ratio, description);
        }
Exemplo n.º 7
0
        public void Setup(BenchmarkContext context)
        {
            MsgReceived = context.GetCounter("MsgReceived");
            System = ActorSystem.Create("PerfSys");
            Action<IActorDsl> actor = d => d.ReceiveAny((o, c) =>
            {
                MsgReceived.Increment();
            });
            TestActor = System.ActorOf(Props.Create(() => new Act(actor)), "testactor");
            var id = TestActor.Ask<ActorIdentity>(new Identify(null), TimeSpan.FromSeconds(3)).Result;

            Mailbox = new Mailbox(new UnboundedMessageQueue());
            Mailbox.SetActor(TestActor.AsInstanceOf<RepointableActorRef>().Underlying.AsInstanceOf<ActorCell>());
        }
Exemplo n.º 8
0
        public async Task<ImmutableArray<PageDto>> GetPagesForSection(IActorRef actor, SectionDto section)
        {
            var answer = await actor.Ask(new PageActor.GetPagesForSection(section));

            if (answer is PageActor.GetPagesForSectionResult)
            {
                var result = answer as PageActor.GetPagesForSectionResult;

                return result.Pages;
            }

            LogFailure(answer);

            return ImmutableArray<PageDto>.Empty;
        }
        public async Task<DirectoryInfo> GetRootDirectoryFromCommandLine(IActorRef actor)
        {
            var answer = await actor.Ask(new CommandLineArgsParserActor.GetRootDirectoryFromCommandLineArgs());

            if (answer is CommandLineArgsParserActor.GetRootDirectoryFromCommandLineArgsResult)
            {
                var result = answer as CommandLineArgsParserActor.GetRootDirectoryFromCommandLineArgsResult;

                return result.Success ? result.Directory : null;
            }

            LogFailure(answer);

            return null;
        } 
Exemplo n.º 10
0
        public async Task<ImmutableArray<NotebookDto>> GetNotebooks(IActorRef actor)
        {
            var answer = await actor.Ask(new NotebookActor.GetNotebooks());

            if (answer is NotebookActor.GetNotebooksResult)
            {
                var result = answer as NotebookActor.GetNotebooksResult;

                return result.Notebooks;
            }

            LogFailure(answer);

            return ImmutableArray<NotebookDto>.Empty;
        }
Exemplo n.º 11
0
        public async Task<ImmutableArray<SectionDto>> GetSectionsForNotebook(IActorRef actor, NotebookDto notebook)
        {
            var answer = await actor.Ask(new SectionActor.GetSectionsForNotebook(notebook));

            if (answer is SectionActor.GetSectionsForNotebookResult)
            {
                var result = answer as SectionActor.GetSectionsForNotebookResult;

                return result.Sections;
            }

            LogFailure(answer);

            return ImmutableArray<SectionDto>.Empty;
        }
Exemplo n.º 12
0
        private static void SendClusterMessages(IActorRef sys2Router, int keysCol)
        {
            Log.Information("------------------------");
            Log.Information("Starting sending cluster messages");

            var routees = sys2Router.Ask<Routees>(new GetRoutees()).Result;
            Log.Information($"Routees before start: {routees.Members.Count()}");
            foreach (var member in routees.Members)
            {
                member.Send("I am routee before start", ActorRefs.NoSender);
            }

            var recieves = new Dictionary<int, int>();
            int messagesLost = 0;

            var tasks = Enumerable.Range(0, 1000).Select(
                i => Task.Run(
                    async () =>
                        {
                            try
                            {
                                var port =
                                    await sys2Router.Ask<int>(
                                        new ConsistentHashableEnvelope(
                                            new LogActor.PingMessage { Message = $"Hello {i} {i % keysCol}" },
                                            i % keysCol),
                                        TimeSpan.FromMilliseconds(1000));

                                lock (recieves)
                                {
                                    if (!recieves.ContainsKey(port))
                                    {
                                        recieves[port] = 0;
                                    }

                                    recieves[port]++;
                                }
                            }
                            catch (Exception)
                            {
                                Interlocked.Add(ref messagesLost, 1);
                            }
                        }));

            Task.WaitAll(tasks.ToArray());

            if (messagesLost > 0)
            {
                Log.Error("{messagesLost} messages was lost", messagesLost);
            }

            foreach (var key in recieves.Keys)
            {
                Log.Information("{Port} recieved {Count} messages", key, recieves[key]);
            }

            routees = sys2Router.Ask<Routees>(new GetRoutees()).Result;
            Log.Information($"Routees after stop: {routees.Members.Count()}");
            foreach (var member in routees.Members)
            {
                member.Send("I am routee after stop", ActorRefs.NoSender);
            }
        }
Exemplo n.º 13
0
 public ActorLookupSpec()
 {
     c1 = Sys.ActorOf(P, "c1");
     c2 = Sys.ActorOf(P, "c2");
     c21 = c2.Ask<IActorRef>(new Create("c21"), RemainingOrDefault).Result;
     SysImpl = (ActorSystemImpl) Sys;
     user = SysImpl.Guardian;
     syst = SysImpl.SystemGuardian;
     root = SysImpl.LookupRoot;
 }
Exemplo n.º 14
0
 public void Unsubscribe(IActorRef actor, Type topic)
 {
     _local.Unsubscribe(actor, topic);
     _remoteSubscriber.Ask <UnsubscribeAck>(new Unsubscribe(actor, topic), _timeout).Wait();
 }
Exemplo n.º 15
0
 private Task AdjustEventLogClock(IActorRef log) =>
 log.Ask(new AdjustEventLogClock(), timeout: settings.RemoteOperationTimeout)
 .Unwrap <AdjustEventLogClockSuccess, Exception>();
Exemplo n.º 16
0
 private void BecomeAsking()
 {
     _canAcceptJobSender = Sender;
     _pendingJobReplies  = _coordinator.Ask <Routees>(new GetRoutees()).Result.Members.Count();
     Become(Asking);
 }
Exemplo n.º 17
0
        public async Task <object> CreateAsync(int regionId, int propertyId)
        {
            var message = new RequestAddProperty(regionId, propertyId);

            return(await _availabilityManager.Ask(message));
        }
 public async Task <int> ActiveIslands()
 {
     return(await _routerActor.Ask <int>(new GetIslandCountMessage(), TimeSpan.FromMilliseconds(_maxAskDelayMiliseconds)));
 }
        public async Task ConsistentHashingGroupRouterMustCreateRouteesFromConfiguration()
        {
            var currentRoutees = await _router3.Ask <Routees>(new GetRoutees(), GetTimeoutOrDefault(null));

            currentRoutees.Members.Count().ShouldBe(3);
        }
Exemplo n.º 20
0
        static async Task AkkaTest(int concurrent)
        {
            mCount = 0;
            long        start = EventCenter.Watch.ElapsedMilliseconds;
            List <Task> tasks = new List <Task>();

            for (int k = 0; k < concurrent; k++)
            {
                var task = Task.Run(async() =>
                {
                    for (int i = 0; i < mFors; i++)
                    {
                        Income income = new Income {
                            Memory = i
                        };
                        var result = await henryActor.Ask <decimal>(income);
                        System.Threading.Interlocked.Increment(ref mCount);
                    }
                });
                tasks.Add(task);

                task = Task.Run(async() =>
                {
                    for (int i = 0; i < mFors; i++)
                    {
                        Payout payout = new Payout {
                            Memory = i
                        };
                        var result = await henryActor.Ask <decimal>(payout);
                        System.Threading.Interlocked.Increment(ref mCount);
                    }
                });
                tasks.Add(task);


                task = Task.Run(async() =>
                {
                    for (int i = 0; i < mFors; i++)
                    {
                        Income income = new Income {
                            Memory = i
                        };
                        var result = await nbActor.Ask <decimal>(income);
                        System.Threading.Interlocked.Increment(ref mCount);
                    }
                });
                tasks.Add(task);

                task = Task.Run(async() =>
                {
                    for (int i = 0; i < mFors; i++)
                    {
                        Payout payout = new Payout {
                            Memory = i
                        };
                        var result = await nbActor.Ask <decimal>(payout);
                        System.Threading.Interlocked.Increment(ref mCount);
                    }
                });
                tasks.Add(task);
            }
            Task.WaitAll(tasks.ToArray());
            var get         = new Get();
            var henryAmount = await henryActor.Ask <decimal>(get);

            var nbAmount = await nbActor.Ask <decimal>(get);

            double usetime = EventCenter.Watch.ElapsedMilliseconds - start;

            Console.WriteLine($"Akka concurrent{concurrent}|use time:{EventCenter.Watch.ElapsedMilliseconds - start}|count:{mCount}|rps:{(mCount / usetime * 1000):####}|henry:{henryAmount}|nb:{nbAmount}");
        }
        public async Task <ActionResult> CreateBasket()
        {
            var id = await _basketManagerActor.Ask(new CreateBasket());

            return(StatusCode(200, id));
        }
Exemplo n.º 22
0
 public async Task <Basket> Execute(int customerId)
 {
     _logger.LogInformation($"Getting basket with customer id of {customerId}.");
     return(await _basketActor.Ask <Basket>(new BasketActor.GetBasket(customerId)));
 }
Exemplo n.º 23
0
 public async Task <IEnumerable <MarketlineVO> > Reply(GameDataUpdateMessage message)
 {
     return(await _actor.Ask <IEnumerable <MarketlineVO> >(message));
 }
 private IEnumerable<Routee> CurrentRoutees(IActorRef router)
 {
     return router.Ask<Routees>(new GetRoutees(), GetTimeoutOrDefault(null)).Result.Members;
 }
Exemplo n.º 25
0
        protected override void OnReceive(object pMessage)
        {
            switch (pMessage)
            {
            case Block block:
                if (!ConnectionIsClosed())
                {
                    _writer.WriteLine($"id:{block.Index}");
                    _writer.WriteLine("event: new_block");
                    _writer.WriteLine($"data: {JsonConvert.SerializeObject(block)}");
                    _writer.WriteLine();
                    _writer.Flush();
                }

                break;

            case Transaction transaction:
                if (!ConnectionIsClosed())
                {
                    _writer.WriteLine($"id:{transaction.Id}");
                    _writer.WriteLine("event: new_transaction");
                    _writer.WriteLine($"data: {JsonConvert.SerializeObject(transaction)}");
                    _writer.WriteLine();
                    _writer.Flush();
                }

                break;

            case Replay _:
                if (!ConnectionIsClosed())
                {
                    var currentBlocks = _persistence
                                        .Ask <ReadOnlyCollection <Block> >(
                        new Persistence.GetBlocks(), TimeSpan.FromSeconds(5)).Result;
                    foreach (var block in currentBlocks)
                    {
                        _writer.WriteLine($"id:{block.Index}");
                        _writer.WriteLine("event: new_block");
                        _writer.WriteLine($"data: {JsonConvert.SerializeObject(block)}");
                        _writer.WriteLine();
                        _writer.Flush();
                    }
                }

                break;

            case CheckConnection _:
                if (!ConnectionIsClosed())
                {
                    ValidateConnection();
                }

                break;

            case HeartBeat _:
                if (!ConnectionIsClosed())
                {
                    _writer.WriteLine(":heartbeat");
                    _writer.WriteLine();
                    _writer.Flush();

                    KeepAliveConnection();
                }

                break;
            }
        }
Exemplo n.º 26
0
 public static void Step(IActorRef journal)
 {
     journal.Ask(Token.Instance, TimeSpan.FromSeconds(3)).Wait();
 }
Exemplo n.º 27
0
        public Mp3RecordManager(IActorRef resourceDownloader, IActorRef resourceStorer)
        {
            Receive<NewRecordMessage>(async message =>
            {
                newRecord = message;
                path = message.Artist + "\\" + message.Album + "\\" + message.Track + ".mp3";
                var pathHash = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(path));
                var rowKey = message.Album + " - " + message.Track; //BitConverter.ToString(pathHash).Replace("-", "");
                var tableClient = storageAccount.CreateCloudTableClient();
                var table = tableClient.GetTableReference(StorageTableName);
                trackEntity = new TrackEntity
                {
                    Album = message.Album,
                    AlbumArtUrl = message.AlbumImageLocation.AbsoluteUri,
                    AlbumArtDownloaded = false,
                    Artist = message.Artist,
                    Track = message.Track,
                    TrackDownloaded = false,
                    TrackUrl = message.FileLocation.AbsoluteUri,
                    PartitionKey = message.Artist,
                    RowKey = rowKey,
                    Timestamp = DateTime.UtcNow
                };
                var partitionFilter = TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal,
                    trackEntity.PartitionKey);
                var rowFilter = TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.Equal, trackEntity.RowKey);
                var finalFilter = TableQuery.CombineFilters(partitionFilter, TableOperators.And, rowFilter);
                var query = new TableQuery<TrackEntity>().Where(finalFilter);

                var entities = table.ExecuteQuery(query, new TableRequestOptions {RetryPolicy = new NoRetry()});
                if (!entities.Any())
                {
                    var insertOperation = TableOperation.Insert(trackEntity);
                    table.Execute(insertOperation);

                    if (message.AlbumImageLocation != null)
                    {
                        var albumArtDownloadedMessage =
                            await
                                resourceDownloader.Ask<AlbumArtDownloaded>(
                                    new DownloadAlbumArt(message.AlbumImageLocation));
                        trackEntity.AlbumImage = albumArtDownloadedMessage.Resource;
                    }
                    var mp3Downloaded =
                        await resourceDownloader.Ask<Mp3Downloaded>(new DownloadMp3(message.FileLocation));

                    Log.Information("Received downloaded MP3. Length: {length}, Location: {resourceUri}", mp3Downloaded.Resource.Length,
                        mp3Downloaded.ResourceUri);

                    var memoryStream = new MemoryStream();
                    memoryStream.Write(mp3Downloaded.Resource, 0, mp3Downloaded.Resource.Length);

                    var simpleFile = new SimpleFile(path, memoryStream);
                    var simpleFileAbstraction = new SimpleFileAbstraction(simpleFile);
                    var file = File.Create(simpleFileAbstraction);

                    file.Tag.Composers = new[] {newRecord.Artist};
                    file.Tag.AlbumArtists = new[] {newRecord.Artist};
                    file.Tag.Title = newRecord.Track;
                    file.Tag.Album = newRecord.Album;

                    file.Tag.Pictures = new IPicture[]
                    {
                        new Picture(trackEntity.AlbumImage)
                    };

                    file.Save();
                    var savedFile = ReadToEnd(simpleFile.Stream);
                    resourceStorer.Tell(new StoreBlobRequest(path, savedFile));

                    Log.Information("Creating record: {artist}", message.Artist);
                }
            });

            Receive<Mp3Downloaded>(message =>
            {
                Log.Information("receieved downloaded MP3. Length: {length}, Resource URI: {resourceUri}",
                    message.Resource.Length,
                    message.ResourceUri);

                var memoryStream = new MemoryStream();
                memoryStream.Write(message.Resource, 0, message.Resource.Length);

                var simpleFile = new SimpleFile(path, memoryStream);
                var simpleFileAbstraction = new SimpleFileAbstraction(simpleFile);
                var file = File.Create(simpleFileAbstraction);

                file.Tag.Composers = new[] {newRecord.Artist};
                file.Tag.AlbumArtists = new[] {newRecord.Artist};
                file.Tag.Title = newRecord.Track;
                file.Tag.Album = newRecord.Album;

                file.Tag.Pictures = new IPicture[]
                {
                    new Picture(trackEntity.AlbumImage)
                };

                file.Save();
                var savedFile = ReadToEnd(simpleFile.Stream);
                resourceStorer.Tell(new StoreBlobRequest(path, savedFile));
            });

            Receive<AlbumArtDownloaded>(message =>
            {
                // this is the Album Art Image file.
                if (newRecord.AlbumImageLocation != null &&
                    message.ResourceUri.AbsoluteUri == newRecord.AlbumImageLocation.AbsoluteUri)
                {
                    var path = newRecord.Artist + "\\" + newRecord.Album + ".jpg";
                    resourceStorer.Tell(new StoreBlobRequest(path, message.Resource));
                }
            });
        }
Exemplo n.º 28
0
        public async Task <ActionResult <IEnumerable <Product> > > Get()
        {
            var response = await _productActor.Ask <AllProducts>(new GetAllProducts(1));

            return(Ok(response.Products));
        }
Exemplo n.º 29
0
 public override Task <long> ReadHighestSequenceNrAsync(string persistenceId, long fromSequenceNr)
 {
     return(_store.Ask(new AsyncWriteTarget.ReadHighestSequenceNr(persistenceId, fromSequenceNr))
            .ContinueWith(t => (long)t.Result));
 }
Exemplo n.º 30
0
        public static async Task <ActorResultBuilder> Query(this IActorRef actor, object message)
        {
            var answer = await actor.Ask(message);

            return(new ActorResultBuilder(answer));
        }
Exemplo n.º 31
0
        public async Task <EventLogClock> ReadEventLogClock(IActorRef targetLog)
        {
            var response = await targetLog.Ask <GetEventLogClockSuccess>(new GetEventLogClock(), timeout : settings.LocalReadTimeout);

            return(response.Clock);
        }
Exemplo n.º 32
0
        static void Main(string[] args)
        {
            //Starts the watch timer
            var watch = System.Diagnostics.Stopwatch.StartNew();

            //Start the actor system
            NOPActorSystem = ActorSystem.Create("NOPActorSystem");

            //Build up all actors
            IActorRef FBEGateActor               = NOPActorSystem.ActorOf(Props.Create(() => new FBEGate()), "FBEGateActor");
            IActorRef FBERemoteControlActor      = NOPActorSystem.ActorOf(Props.Create(() => new FBERemoteControl()), "FBERemoteControlActor");
            IActorRef PremisseIsClosedActor      = NOPActorSystem.ActorOf(Props.Create(() => new PremisseIsClosed()), "PremisseIsClosedActor");
            IActorRef PremisseIsOpenActor        = NOPActorSystem.ActorOf(Props.Create(() => new PremisseIsOpen()), "PremisseIsOpenActor");
            IActorRef PremisseChangeStateActor   = NOPActorSystem.ActorOf(Props.Create(() => new PremisseChangeState()), "PremisseChangeStateActor");
            IActorRef ConditionCloseGateActor    = NOPActorSystem.ActorOf(Props.Create(() => new ConditionCloseGate()), "ConditionCloseGateActor");
            IActorRef ConditionOpenGateActor     = NOPActorSystem.ActorOf(Props.Create(() => new ConditionOpenGate()), "ConditionOpenGateActor");
            IActorRef ConditionStateChangedActor = NOPActorSystem.ActorOf(Props.Create(() => new ConditionStateChanged()), "ConditionStateChangedActor");

            //Set all actor references
            var FBEGateActorTask1               = FBEGateActor.Ask(new ActorReference(ActorRefType.PremisseIsClosedRef, PremisseIsClosedActor));
            var FBEGateActorTask2               = FBEGateActor.Ask(new ActorReference(ActorRefType.PremisseIsOpenRef, PremisseIsOpenActor));
            var FBERemoteControlActorTask1      = FBERemoteControlActor.Ask(new ActorReference(ActorRefType.PremisseChangeStateRef, PremisseChangeStateActor));
            var PremisseIsClosedActorTask1      = PremisseIsClosedActor.Ask(new ActorReference(ActorRefType.ConditionCloseGateRef, ConditionCloseGateActor));
            var PremisseIsOpenActorTask1        = PremisseIsOpenActor.Ask(new ActorReference(ActorRefType.ConditionOpenGateRef, ConditionOpenGateActor));
            var PremisseChangeStateActorTask1   = PremisseChangeStateActor.Ask(new ActorReference(ActorRefType.ConditionCloseGateRef, ConditionCloseGateActor));
            var PremisseChangeStateActorTask2   = PremisseChangeStateActor.Ask(new ActorReference(ActorRefType.ConditionOpenGateRef, ConditionOpenGateActor));
            var PremisseChangeStateActorTask3   = PremisseChangeStateActor.Ask(new ActorReference(ActorRefType.ConditionStateChangedRef, ConditionStateChangedActor));
            var ConditionCloseGateActorTask1    = ConditionCloseGateActor.Ask(new ActorReference(ActorRefType.FBEGateRef, FBEGateActor));
            var ConditionCloseGateActorTask2    = ConditionCloseGateActor.Ask(new ActorReference(ActorRefType.FBERemoteControlRef, FBERemoteControlActor));
            var ConditionOpenGateActorTask1     = ConditionOpenGateActor.Ask(new ActorReference(ActorRefType.FBEGateRef, FBEGateActor));
            var ConditionOpenGateActorTask2     = ConditionOpenGateActor.Ask(new ActorReference(ActorRefType.FBERemoteControlRef, FBERemoteControlActor));
            var ConditionStateChangedActorTask1 = ConditionStateChangedActor.Ask(new ActorReference(ActorRefType.FBERemoteControlRef, FBERemoteControlActor));

            //Wait for all references to be set
            FBEGateActorTask1.Wait();
            FBEGateActorTask1.Wait();
            FBEGateActorTask2.Wait();
            FBERemoteControlActorTask1.Wait();
            PremisseIsClosedActorTask1.Wait();
            PremisseIsOpenActorTask1.Wait();
            PremisseChangeStateActorTask1.Wait();
            PremisseChangeStateActorTask2.Wait();
            PremisseChangeStateActorTask3.Wait();
            ConditionCloseGateActorTask1.Wait();
            ConditionCloseGateActorTask2.Wait();
            ConditionOpenGateActorTask1.Wait();
            ConditionStateChangedActorTask1.Wait();

            //ActionTriggers
            int i = 4;

            while ((i--) > 0)
            {
                FBERemoteControlActor.Tell(RemoteControlState.ButtonPress);
            }

            //Tells to shut down the actor system
            FBERemoteControlActor.Tell(RemoteControlState.End);

            //Blocks the main thread from exiting until the actor system is shut down
            NOPActorSystem.WhenTerminated.Wait();

            //Stop the watch timer
            watch.Stop();
            var elapsedMs = watch.ElapsedMilliseconds;

            //Wait for a key press to finish the application
            Console.Write("Time elapsed [ms]:");
            Console.WriteLine(elapsedMs);
            Console.WriteLine("Press any key to terminate");
            Console.ReadKey();
        }
 public override void OnGoToStep(GoToStep msg)
 {
     _ownerName = _ownerActor.Ask <string>(new WhatIsYourName()).Result;
     Context.ActorSelection("/user/Application/io/Out").Tell(new RememberFriendsShowIntro(_ownerName));
 }
Exemplo n.º 34
0
 public static Task <T> ShardedAsk <T>(this IActorRef shardRegion, string entityId, object message) =>
 shardRegion.Ask <T>(new ShardEnvelope(entityId, message), TimeSpan.FromSeconds(5));
Exemplo n.º 35
0
        private IEnumerable <Routee> CurrentRoutees(IActorRef router)
        {
            var routerAsk = router.Ask <Routees>(new GetRoutees(), GetTimeoutOrDefault(null));

            return(routerAsk.Result.Members);
        }
Exemplo n.º 36
0
        public async Task <GetAllTeamsResponse> GetAllTeams()
        {
            var request = new GetAllTeamsRequest();

            return(await _teamActor.Ask <GetAllTeamsResponse>(request));
        }
 public override async Task <MarketSubscribeAck> Subscribe(string tickerSymbol, MarketEventType[] events, IActorRef subscriber)
 {
     return(await _targetActor.Ask <MarketSubscribeAck>(new MarketSubscribe(tickerSymbol, events, subscriber),
                                                        TimeSpan.FromSeconds(3)));
 }
Exemplo n.º 38
0
 private int RouteeSize(IActorRef router)
 {
     return(router.Ask <Routees>(new GetRoutees()).Result.Members.Count());
 }
Exemplo n.º 39
0
 private int RouteeSize(IActorRef router)
 {
     return router.Ask<Routees>(new GetRoutees()).Result.Members.Count();
 }
Exemplo n.º 40
0
        private Routees CurrentRoutees(IActorRef router)
        {
            var routerAsk = router.Ask <Routees>(new GetRoutees(), GetTimeoutOrDefault(null));

            return(routerAsk.Result);
        }
Exemplo n.º 41
0
        public void DeathWatch_must_fail_a_monitor_which_doesnt_handle_Terminated()
        {
            EventFilter.Exception<ActorKilledException>().And.Exception<DeathPactException>().Expect(2, () =>
            {
                var strategy = new FailedSupervisorStrategy(TestActor);
                _supervisor = Sys.ActorOf(Props.Create(() => new Supervisor(strategy)).WithDeploy(Deploy.Local));

                var failed = _supervisor.Ask(Props.Empty).Result as IActorRef;
                var brother = _supervisor.Ask(Props.Create(() => new BrotherActor(failed))).Result as IActorRef;

                StartWatching(brother);

                failed.Tell(Kill.Instance);
                var result = ReceiveWhile(TimeSpan.FromSeconds(5), msg =>
                {
                    var res = 0;
                    msg.Match()
                        .With<FF>(ff =>
                        {
                            if (ff.Fail.Cause is ActorKilledException && ff.Fail.Child == failed) res = 1;
                            if (ff.Fail.Cause is DeathPactException && ff.Fail.Child == brother) res = 2;
                        })
                        .With<WrappedTerminated>(x => res = x.Terminated.ActorRef == brother ? 3 : 0);
                    return res.ToString();
                }, 3);

                ((IInternalActorRef)TestActor).IsTerminated.ShouldBe(false);
                result.ShouldOnlyContainInOrder("1", "2", "3");
            });
        }
Exemplo n.º 42
0
 public Asker(IActorRef other)
 {
     ReceiveAsync<string>(async _ =>
     {
         var sender = Sender;
         var self = Self;
         var res = await other.Ask("start");
         Assert.Same(sender, Sender);
         Assert.Same(self, Self);
         Sender.Tell(res);
     });
 }
 protected Routees CurrentRoutees(IActorRef router)
 {
     var routerAsk = router.Ask<Routees>(new GetRoutees(), GetTimeoutOrDefault(null));
     return routerAsk.Result;
 }
 private async void GetResponseFromClusterMembers(string message)
 {
     Sender.Tell(await mediator.Ask <string>(new Send("/user/destination", message, localAffinity: true)));
 }
Exemplo n.º 45
0
 public BlockingAsker(IActorRef other)
 {
     Receive<string>(_ =>
     {
         //not async, blocking wait
         var res = other.Ask("start").Result;
         Sender.Tell(res);
     });
 }
 /// <summary>
 /// Responds to the provided <paramref name="message"/> passing the <paramref name="message"/> to an Akka.Net actor.
 /// </summary>
 /// <param name="message">The <see cref="HelloWorldRepliedTo"/> to respond to or "handle"</param>
 public void Handle(HelloWorldRepliedTo message)
 {
     IActorRef item   = AggregateResolver.ResolveActor <HelloWorldRepliedToEventHandlerActor>();
     bool      result = item.Ask <bool>(message).Result;
     // item.Tell(message);
 }
        private void Receives()
        {
            Receive <AttemptJobStart>(attempt =>
            {
                CommandRouter.Ask <Routees>(new GetRoutees()).ContinueWith(tr =>
                {
                    var route = new StartJobRoutes(tr.Result.Members.Count());
                    return(route);
                }, TaskContinuationOptions.AttachedToParent & TaskContinuationOptions.ExecuteSynchronously).PipeTo(Self, Sender);
            });

            Receive <StartJobRoutes>(ic => ic.NodeCount == 0, ic =>
            {
                Sender.Tell(ic);
            });

            Receive <StartJobRoutes>(ic =>
            {
                Sender.Tell(ic);


                // TODO:  Need to create a task to get the markts and to run them all.
                JobInfo job  = new JobInfo("RunMe");
                var startJob = new StartJob(new Job(job), Sender);

                CommandRouter.Tell(startJob);

                JobInfo job2  = new JobInfo("MyPetMonkey1");
                var startJob2 = new StartJob(new Job(job2), Sender);

                CommandRouter.Tell(startJob2);

                JobInfo job3  = new JobInfo("AkkaNet");
                var startJob3 = new StartJob(new Job(job3), Sender);

                CommandRouter.Tell(startJob3);
            });

            Receive <AttemptSubscription>(attempt =>
            {
                CommandRouter.Tell(new SubscribeToAllJobs(Sender), Self);
                CommandRouter.Ask <Routees>(new GetRoutees()).ContinueWith(tr =>
                {
                    var message = string.Empty;

                    if (!tr.Result.Members.Any())
                    {
                        message = "Could not find item tasker.  Is the Tasker service running?";
                    }
                    else
                    {
                        message = "Item tasker is running.";
                    }

                    return(new SignalRItemStatusActor.ClusterRoutes(message));
                }, TaskContinuationOptions.AttachedToParent & TaskContinuationOptions.ExecuteSynchronously).PipeTo(Sender);
                Sender.Tell(new SubscribeToAllJobs(Sender), Self);
            });

            Receive <AttemptUnSubscribe>(attempt =>
            {
                CommandRouter.Tell(new UnSubscribeToAllJobs(Sender), Self);
                CommandRouter.Ask <Routees>(new GetRoutees()).ContinueWith(tr =>
                {
                    var grrr =
                        new SignalRItemStatusActor.ClusterRoutes(string.Format("{0} has {1} routees: {2}", CommandRouter,
                                                                               tr.Result.Members.Count(),
                                                                               string.Join(",",
                                                                                           tr.Result.Members.Select(
                                                                                               y => y.ToString()))));

                    return(grrr);
                }, TaskContinuationOptions.AttachedToParent & TaskContinuationOptions.ExecuteSynchronously).PipeTo(Sender);
                Sender.Tell(new UnSubscribeToAllJobs(Sender), Self);
            });
        }
 public Task <EvaluationResult> AskEvaluate(string data, bool script)
 => _actor.Ask <EvaluationResult>(new EvaluateExpression(data, script), TimeSpan.FromMinutes(2));
 public Task <string> GetAnswerFromCluster(string message)
 {
     return(askActor.Ask <string>(message));
 }
Exemplo n.º 50
0
        private static async Task Run(IActorRef player1)
        {
            Console.WriteLine("type; look, where, name, inventory");
            while (true)
            {
                var input   = Console.ReadLine();
                var parts   = input.Split(new char[] { ' ' }, 2, StringSplitOptions.RemoveEmptyEntries);
                var command = parts.FirstOrDefault();
                switch (command)
                {
                case "say":
                case "s":
                {
                    var message = parts.ElementAtOrDefault(1);
                    player1.Tell(new Say(message));
                    break;
                }

                case "where":
                {
                    player1.Tell(new Where());
                    break;
                }

                case "name":
                {
                    var name = await player1.Ask <string>(new GetName());

                    Console.WriteLine($"Your name is {name}.");
                    break;
                }

                case "look":
                case "l":
                {
                    player1.Tell(new Look());
                    break;
                }

                case "inventory":
                case "inv":
                {
                    player1.Tell(new Inventory());
                    break;
                }

                case "take":
                case "t":
                case "get":
                {
                    var name = parts.ElementAtOrDefault(1);
                    player1.Tell(new Take(name));
                    break;
                }

                case "drop":
                case "d":
                {
                    var name = parts.ElementAtOrDefault(1);
                    player1.Tell(new Drop(name));
                    break;
                }

                case "put":
                {
                    var commands  = parts.ElementAtOrDefault(1).Split(new[] { " in " }, StringSplitOptions.RemoveEmptyEntries);
                    var what      = commands.ElementAtOrDefault(0);
                    var container = commands.ElementAtOrDefault(1);
                    player1.Tell(new Put(what, container));
                    break;
                }

                case "kill":
                case "attack":
                case "fight":
                {
                    var name = parts.ElementAtOrDefault(1);
                    player1.Tell(new StartFight(name));
                    break;
                }
                }
            }
        }