static void Main(string[] args) { var player1 = ActorProxy.Create <IPlayer>(ActorId.CreateRandom(), "fabric:/ActorTicTacToeApplication"); var player2 = ActorProxy.Create <IPlayer>(ActorId.CreateRandom(), "fabric:/ActorTicTacToeApplication"); var gameId = ActorId.CreateRandom(); var game = ActorProxy.Create <IGame>(gameId, "fabric:/ActorTicTacToeApplication"); var rand = new Random(); var result1 = player1.JoinGameAsync(gameId, "Player 1"); var result2 = player2.JoinGameAsync(gameId, "Player 2"); if (!result1.Result || !result2.Result) { Console.WriteLine("Failed to join game."); return; } var player1Task = Task.Run(() => { MakeMove(player1, game, gameId); }); var player2Task = Task.Run(() => { MakeMove(player2, game, gameId); }); var gameTask = Task.Run(() => { string winner = ""; while (winner == "") { var board = game.GetGameBoardAsync().Result; PrintBoard(board); winner = game.GetWinnerAsync().Result; Task.Delay(2000).Wait(); } Console.WriteLine("Winner is: " + winner); }); gameTask.Wait(); Console.Read(); }
public void TestRegisterActor_SavesActivator() { var actorType = typeof(TestActor); var actorTypeInformation = ActorTypeInformation.Get(actorType); var host = new ActorHost(actorTypeInformation, ActorId.CreateRandom(), JsonSerializerDefaults.Web, new LoggerFactory(), ActorProxy.DefaultProxyFactory); var actor = new TestActor(host); var activator = Mock.Of <ActorActivator>(); var actorRuntimeOptions = new ActorRuntimeOptions(); actorRuntimeOptions.Actors.RegisterActor <TestActor>(registration => { registration.Activator = activator; }); Assert.Collection( actorRuntimeOptions.Actors, registration => { Assert.Same(actorTypeInformation.ImplementationType, registration.Type.ImplementationType); Assert.Same(activator, registration.Activator); }); }
public async Task validate_month_total_on_events_and_activities() { MockServiceProxyFactory serviceProxyFactory = new MockServiceProxyFactory(); ParticipantActor target = await CreateParticipantActor(ActorId.CreateRandom()); var currentDate = DateTimeOffset.UtcNow; int monthChanger = -1; if (currentDate.Month == 1) { monthChanger = 1; } await target.AddEvent(new ParticipantEvent() { Id = Guid.NewGuid().ToString(), Points = 1, Date = currentDate.AddMonths(monthChanger) }); await target.AddEvent(new ParticipantEvent() { Id = Guid.NewGuid().ToString(), Points = 1, Date = currentDate }); await target.AddActivity(new ParticipantActivity() { Points = 1, Date = currentDate }); var current = await target.StateManager.GetStateAsync <Participations>(ParticipationsKeyName); var participations = await target.GetMonthParticipations(currentDate.Month, currentDate.Year); Assert.AreEqual(2, participations.MonthTotalPoints); }
/// <summary> /// This is the main entry point for your service replica. /// This method executes when this replica of your service becomes primary and /// has write status. /// </summary> /// <param name="cancellationToken"> /// Canceled when Service Fabric needs to shut down /// this service replica. /// </param> protected override async Task RunAsync(CancellationToken cancellationToken) { while (true) { cancellationToken.ThrowIfCancellationRequested(); var actorId = ActorId.CreateRandom(); var microservice = ActorProxy.Create <IMicroservice>( actorId, new Uri("fabric:/Fleetmatics.Workshop.Microservice/MicroserviceActorService")); var random = new Random(); await microservice.SetCountAsync(random.Next(), cancellationToken); var count = await microservice.GetCountAsync(cancellationToken); ServiceEventSource .Current .ServiceMessage(Context, "Current Counter Value: {0}", count); await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken); } }
public static IUserLoader UserLoader(this IServiceFabricToolbox toolbox) { return(toolbox.Actors.CreateActorProxy <IUserLoader>(UserConstants.UserLoaderUri, ActorId.CreateRandom())); }
/// <summary> /// This is the entry point of the service host process. /// </summary> private static void Main() { try { // This line registers an Actor Service to host your actor class with the Service Fabric runtime. // The contents of your ServiceManifest.xml and ApplicationManifest.xml files // are automatically populated when you build this project. // For more information, see https://aka.ms/servicefabricactorsplatform ActorRuntime.RegisterActorAsync <SampleActorSubscriber>( (context, actorType) => new SampleActorSubscriberService( context, actorType, (actorService, actorId) => new SampleActorSubscriber(actorService, actorId))).GetAwaiter().GetResult(); ISampleActorSubscriber actorSubscriber; if (FabricConfiguration.UseCustomServiceRemotingClientFactory) { actorSubscriber = FabricConfiguration.GetProxyFactories().CreateActorProxy <ISampleActorSubscriber>(new Uri("fabric:/PubSubDemo/SampleActorSubscriberService"), ActorId.CreateRandom()); } else { actorSubscriber = ActorProxy.Create <ISampleActorSubscriber>(ActorId.CreateRandom(), new Uri("fabric:/PubSubDemo/SampleActorSubscriberService")); } actorSubscriber.Subscribe().GetAwaiter().GetResult(); Thread.Sleep(Timeout.Infinite); } catch (Exception e) { ActorEventSource.Current.ActorHostInitializationFailed(e.ToString()); throw; } }
public async Task actor_instance_is_created() { var deviceSensor = ActorProxy.Create <IDeviceSensor>(ActorId.CreateRandom(), new Uri("fabric:/LCH.SF.PoC/DeviceSensorActorService")); await deviceSensor.SubmitSensorData(new [] { new KeyValuePair <string, double>("Sensor1", 123.4), }); }
public T Provide() { return(ActorProxy.Create <T>(ActorId.CreateRandom(), FabricRuntime.GetActivationContext().ApplicationName, _actorServiceName)); }
public async Task DeleteAsync_Disposable() { var activator = CreateActivator(typeof(DisposableActor)); var host = new ActorHost(ActorTypeInformation.Get(typeof(DisposableActor)), ActorId.CreateRandom(), JsonSerializerDefaults.Web, NullLoggerFactory.Instance, ActorProxy.DefaultProxyFactory); var state = await activator.CreateAsync(host); var actor = Assert.IsType <DisposableActor>(state.Actor); await activator.DeleteAsync(state); // does not throw Assert.True(actor.IsDisposed); }
public PurchaseController() { proxy = ActorProxy.Create <IEventHubActor>(ActorId.CreateRandom()); logicAppProxy = ActorProxy.Create <ILogicApiActor>(ActorId.CreateRandom()); }
public async Task ReportLocation(Location location) { using (var tx = StateManager.CreateTransaction()) { var timestamps = await StateManager.GetOrAddAsync <IReliableDictionary <Guid, DateTime> >("timestamps"); var orderActorIds = await StateManager.GetOrAddAsync <IReliableDictionary <Guid, ActorId> >("orderIds"); var timestamp = DateTime.UtcNow; var orderActorId = await orderActorIds.GetOrAddAsync(tx, location.OrderId, ActorId.CreateRandom()); await OrderConnectionFactory.GetOrder(orderActorId).SetLocation(timestamp, location.Latitude, location.Longitude); await timestamps.AddOrUpdateAsync(tx, location.OrderId, DateTime.UtcNow, (guid, time) => timestamp); await tx.CommitAsync(); } }
private IAggregationMapper[] BuildMapperPool(int capacity) { return(Enumerable.Range(0, capacity).Select(s => ActorProxy.Create <IAggregationMapper>(ActorId.CreateRandom())).ToArray()); }
private ILearnerActor GetLearnerActor() { return(ActorProxy.Create <ILearnerActor>(ActorId.CreateRandom(), new Uri("fabric:/DCT.ILR.Processing.POC/LearnerActorService"))); }
static void Main(string[] args) { PrintGrid(); Thread.Sleep(1000); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("\n 1.START 2.EXIT "); Console.ForegroundColor = ConsoleColor.Blue; Console.Write("\n Press Key: "); Console.ForegroundColor = ConsoleColor.White; int key = Convert.ToInt16(Console.ReadLine()); Thread.Sleep(1000); if (key == 1) { Console.ForegroundColor = ConsoleColor.DarkYellow; Console.Write("\n Enter Player Name: "); Console.ForegroundColor = ConsoleColor.White; string name = Console.ReadLine(); Console.ForegroundColor = ConsoleColor.DarkCyan; Console.WriteLine("\n COMPUTER V/S " + name.ToUpper()); Console.ForegroundColor = ConsoleColor.White; Console.Write("\nloading................."); var player1 = ActorProxy.Create <IPlayer>(ActorId.CreateRandom(), "fabric:/ActorTicTacToeApplication"); var player2 = ActorProxy.Create <IPlayer>(ActorId.CreateRandom(), "fabric:/ActorTicTacToeApplication"); var gameId = ActorId.CreateRandom(); var game = ActorProxy.Create <IGame>(gameId, "fabric:/ActorTicTacToeApplication"); var rand = new Random(); var result1 = player1.JoinGameAsync(gameId, "Computer"); var result2 = player2.JoinGameAsync(gameId, name); if (!result1.Result || !result2.Result) { Console.WriteLine("Failed to join game."); return; } var player1Task = Task.Run(() => { MakeMove(player1, game, gameId); }); var player2Task = Task.Run(() => { MakeMove(player2, game, gameId); }); var gameTask = Task.Run(() => { string winner = ""; while (winner == "") { var board = game.GetGameBoardAsync().Result; PrintBoard(board); winner = game.GetWinnerAsync().Result; Task.Delay(1000).Wait(); } Console.ForegroundColor = ConsoleColor.Red; Console.Write("\n Winner is: "); Console.ForegroundColor = ConsoleColor.Blue; Console.WriteLine(winner.ToUpper()); }); gameTask.Wait(); Console.Read(); } else { Console.Write("THANKYOU "); } }
public TankSessionMemberItem() { TankId = ActorId.CreateRandom(); }
public static I ForAccessor<I>() where I : class, IActor { return ForAccessor<I>(ActorId.CreateRandom().ToString()); }
/// <summary> /// /// </summary> /// <param name="e"></param> private void StartActor(OnMessageEventArgs e) { IToHActor actorClient2 = ActorProxy.Create <IToHActor>(ActorId.CreateRandom(), new Uri("fabric:/CWF.Fabric.Services/ToHActorService")); Task <int> ii = actorClient2.StartKpuActor(e.Properties["KpuId"] as string, WorkflowsDir, XsdDir, ActivitiesDir, FsmDir, KpuDir, ConnectionString, User, Password); int i = ii.Result; }
private IValidationActor GetValidationActor() { return(ActorProxy.Create <IValidationActor>( ActorId.CreateRandom(), new Uri($"{FabricRuntime.GetActivationContext().ApplicationName}/ValidationActorService"))); }
public async Task StartProcessingAsync(Message <string[]> message) { try { var result = await StateManager.TryGetStateAsync <CancellationTokenSource>(message.Id.ToString()); if (result.HasValue) { ActorEventSource.Current.Message($"SupervisorActor=[{Id}] is already processing MessageId=[{message.Id}]."); return; } var cancellationTokenSource = new CancellationTokenSource(); await StateManager.TryAddStateAsync(message.Id.ToString(), cancellationTokenSource, cancellationTokenSource.Token); foreach (var chunkedCollection in message.Payload.Chunk(ActorsLimit)) { var processingActorProxy = ActorProxy.Create <IPDFRendererActorProcessorService>(ActorId.CreateRandom(), _processorActorUri); await processingActorProxy.ProcessAsync(Id.ToString(), new Message <string[]> { Id = Guid.NewGuid(), Payload = chunkedCollection.ToArray() }, cancellationTokenSource.Token); } } catch (Exception exception) { ActorEventSource.Current.Message($"Error occured in SupervisorActor=[{Id}]: {exception}"); } }
/// <summary> /// get actor proxy via SF API /// </summary> /// <typeparam name="T">desired interface</typeparam> /// <param name="serviceName">name of the service</param> /// <returns>proxy instance</returns> internal T GetActorRef <T>(string serviceName) where T : IActor { var actorUri = new Uri($"{StatelessServiceContext.CodePackageActivationContext.ApplicationName}/{serviceName}"); return(ActorProxy.Create <T>(ActorId.CreateRandom(), actorUri)); }
public async Task DeleteAsync_Disposable() { var activator = new DefaultActorActivator(); var host = new ActorHost(ActorTypeInformation.Get(typeof(DisposableActor)), ActorId.CreateRandom(), NullLoggerFactory.Instance); var actor = new DisposableActor(host); var state = new ActorActivatorState(actor); await activator.DeleteAsync(state); // does not throw Assert.True(actor.IsDisposed); }
/// <summary> /// Entry point. /// </summary> /// <param name="args">Arguments.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> public static async Task Main(string[] args) { var data = new MyData() { PropertyA = "ValueA", PropertyB = "ValueB", }; // Create an actor Id. var actorId = new ActorId("abc"); // Make strongly typed Actor calls with Remoting. // DemoActor is the type registered with Dapr runtime in the service. var proxy = ActorProxy.Create <IDemoActor>(actorId, "DemoActor"); Console.WriteLine("Making call using actor proxy to save data."); await proxy.SaveData(data); Console.WriteLine("Making call using actor proxy to get data."); var receivedData = await proxy.GetData(); Console.WriteLine($"Received data is {receivedData}."); // Making some more calls to test methods. try { Console.WriteLine("Making calls to an actor method which has no argument and no return type."); await proxy.TestNoArgumentNoReturnType(); } catch (Exception ex) { Console.WriteLine($"ERROR: Got exception while making call to method with No Argument & No Return Type. Exception: {ex}"); } try { await proxy.TestThrowException(); } catch (ActorMethodInvocationException ex) { if (ex.InnerException is NotImplementedException) { Console.WriteLine($"Got Correct Exception from actor method invocation."); } else { Console.WriteLine($"Got Incorrect Exception from actor method invocation. Exception {ex.InnerException}"); } } // Making calls without Remoting, this shows method invocation using InvokeAsync methods, the method name and its payload is provided as arguments to InvokeAsync methods. Console.WriteLine("Making calls without Remoting."); var nonRemotingProxy = ActorProxy.Create(actorId, "DemoActor"); await nonRemotingProxy.InvokeAsync("TestNoArgumentNoReturnType"); await nonRemotingProxy.InvokeAsync("SaveData", data); var res = await nonRemotingProxy.InvokeAsync <MyData>("GetData"); Console.WriteLine("Registering the timer and reminder"); await proxy.RegisterTimer(); await proxy.RegisterReminder(); Console.WriteLine("Waiting so the timer and reminder can be triggered"); await Task.Delay(6000); Console.WriteLine("Making call using actor proxy to get data after timer and reminder triggered"); receivedData = await proxy.GetData(); Console.WriteLine($"Received data is {receivedData}."); Console.WriteLine("Deregistering timer. Timers would any way stop if the actor is deactivated as part of Dapr garbage collection."); await proxy.UnregisterTimer(); Console.WriteLine("Deregistering reminder. Reminders are durable and would not stop until an explicit deregistration or the actor is deleted."); await proxy.UnregisterReminder(); Console.WriteLine("Creating a Bank Actor"); var bank = ActorProxy.Create <IBankActor>(ActorId.CreateRandom(), "DemoActor"); while (true) { var balance = await bank.GetAccountBalance(); Console.WriteLine($"Balance for account '{balance.AccountId}' is '{balance.Balance:c}'."); Console.WriteLine($"Withdrawing '{10m:c}'..."); try { await bank.Withdraw(new WithdrawRequest() { Amount = 10m, }); } catch (ActorMethodInvocationException ex) { Console.WriteLine("Overdraft: " + ex.Message); break; } } }
public async Task DeleteAsync_AsyncDisposable() { var activator = CreateActivator(typeof(AsyncDisposableActor)); var host = new ActorHost(ActorTypeInformation.Get(typeof(AsyncDisposableActor)), ActorId.CreateRandom(), NullLoggerFactory.Instance); var state = await activator.CreateAsync(host); var actor = Assert.IsType <AsyncDisposableActor>(state.Actor); await activator.DeleteAsync(state); Assert.True(actor.IsDisposed); }
private IALBActor GetALBActor() { return(ActorProxy.Create <IALBActor>(ActorId.CreateRandom(), _albActorUri)); }
public async Task DeleteAsync_AsyncDisposable() { var activator = new DefaultActorActivator(); var host = new ActorHost(ActorTypeInformation.Get(typeof(AsyncDisposableActor)), ActorId.CreateRandom(), JsonSerializerDefaults.Web, NullLoggerFactory.Instance, ActorProxy.DefaultProxyFactory); var actor = new AsyncDisposableActor(host); var state = new ActorActivatorState(actor); await activator.DeleteAsync(state); Assert.True(actor.IsDisposed); }
/// <summary> /// This is the main entry point for your service replica. /// This method executes when this replica of your service becomes primary and has write status. /// </summary> /// <param name="cancellationToken">Canceled when Service Fabric needs to shut down this service replica.</param> protected override async Task RunAsync(CancellationToken cancellationToken) { var proxyFactory = new ServiceProxyFactory(c => new FabricTransportServiceRemotingClientFactory()); var proxyFactory2 = new ServiceProxyFactory(c => new CorrelatingFabricTransportServiceRemotingClientFactory <ISampleService>()); var proxyFactory3 = new ActorProxyFactory(); //ISampleService service = proxyFactory2.CreateServiceProxy<ISampleService>( // new Uri("fabric:/LogMagic.FabricTestApp2/LogMagic.FabricTestApp.StatelessSimulator")); ISampleService service = CorrelatingProxyFactory.CreateServiceProxy <ISampleService>( new Uri("fabric:/LogMagic.FabricTestApp2/LogMagic.FabricTestApp.StatelessSimulator"), raiseSummary: RaiseSummary, remoteServiceName: "StatelessSimulator"); IActorSimulator actor = CorrelatingProxyFactory.CreateActorProxy <IActorSimulator>(ActorId.CreateRandom()); //actor = proxyFactory3.CreateActorProxy<IActorSimulator>(ActorId.CreateRandom()); using (L.Context("param1", "value1")) { try { string hey = await service.PingSuccessAsync("hey"); await actor.SetCountAsync(5, cancellationToken); int count = await actor.GetCountAsync(cancellationToken); hey = await service.PingFailureAsync("fail"); } catch (Exception ex) { ex = null; } } }
/// <summary> /// Provides the observer with new data. This method is invoked by an observable. /// </summary> /// <param name="topic">The topic.</param> /// <param name="message">The current notification information.</param> /// <param name="entityId">The entity id of the observable.</param> /// <param name="observers"> /// A list of observers in the same cluster node. This field is optional. /// When the list if not null or empty, the observer will forward the message to each observer which EntityId is in the /// list. /// </param> /// <returns>The asynchronous result of the operation.</returns> public virtual async Task NotifyObserverAsync(string topic, Message message, EntityId entityId, IEnumerable <EntityId> observers) { try { EntityId id = await this.GetEntityIdAsync(); if (id == null) { return; } if (entityId == null) { entityId = new EntityId { ActorId = ActorId.CreateRandom(), ServiceUri = this.ServiceUri } } ; ActorEventSource.Current.Message( $"Message Received.\r\n[Observable]: {entityId}\r\n[Observer]: {id}\r\n[Message]: Topic=[{topic}] Body=[{message?.Body ?? "NULL"}]"); if (observers != null) { IList <EntityId> observerList = observers as IList <EntityId> ?? observers.ToList(); if (observerList.Any()) { StringBuilder builder = new StringBuilder($"Observer Proxy:\r\n[From]: {id}"); foreach (EntityId item in observerList) { builder.Append($"\r\n[To]: {item}"); } ActorEventSource.Current.Message(builder.ToString()); List <Task> taskList = new List <Task>(); taskList.AddRange( observerList.Select( observer => ProcessingHelper.NotifyObserverAsync( topic, message, observer, entityId, null))); await Task.WhenAll(taskList.ToArray()); } } } catch (AggregateException ex) { foreach (Exception e in ex.InnerExceptions) { ActorEventSource.Current.Error(e); } throw; } catch (Exception ex) { ActorEventSource.Current.Error(ex); throw; } if (this.NotificationMessageReceived == null) { return; } try { Delegate[] invocationList = this.NotificationMessageReceived.GetInvocationList(); Task[] handlerTasks = new Task[invocationList.Length]; NotificationEventArgs <Message> args = new NotificationEventArgs <Message>(topic, message, entityId); for (int i = 0; i < invocationList.Length; i++) { handlerTasks[i] = ProcessingHelper.ExecuteEventHandlerAsync((Func <NotificationEventArgs <Message>, Task>)invocationList[i], args); } await Task.WhenAll(handlerTasks); } catch (AggregateException ex) { foreach (Exception e in ex.InnerExceptions) { ActorEventSource.Current.Error(e); } } catch (Exception ex) { ActorEventSource.Current.Error(ex); } }
public async Task <IActionResult> GetActorBackendRemotingV1() { string serviceUri = this.serviceContext.CodePackageActivationContext.ApplicationName + "/ActorBackendRemotingV1ActorService"; IActorBackendRemotingV1 proxy = actorProxyFactory.CreateActorProxy <IActorBackendRemotingV1>(new Uri(serviceUri), ActorId.CreateRandom()); var result = await proxy.GetCountAsync(CancellationToken.None); ViewData["Message"] = result; return(View("~/Views/Home/Index.cshtml")); }
public async Task ReportLocation(Location location) { using (var tx = StateManager.CreateTransaction()) { var timestamps = await StateManager.GetOrAddAsync <IReliableDictionary <Guid, DateTime> >("timestamps"); var sheepIds = await StateManager.GetOrAddAsync <IReliableDictionary <Guid, ActorId> >("sheepIds"); var timestamp = DateTime.UtcNow; // Update sheep var sheepActorId = await sheepIds.GetOrAddAsync(tx, location.SheepId, ActorId.CreateRandom()); await SheepConnectionFactory.GetSheep(sheepActorId).SetLocation(timestamp, location.Latitude, location.Longitude); // Update service with new timestamp await timestamps.AddOrUpdateAsync(tx, location.SheepId, DateTime.UtcNow, (guid, time) => timestamp); await tx.CommitAsync(); } }
public static ActorType Create <ActorType>(Uri serviceUri) where ActorType : IActor { var newActorId = ActorId.CreateRandom(); return(ActorProxy.Create <ActorType>(newActorId, serviceUri)); }