private IUserActor GetActor(long id) { ActorId actorId = new ActorId(id); return(ActorProxy.Create <IUserActor>(actorId, new Uri("fabric:/Application1/UserActorService"))); }
protected override void Delete(string persistenceId, SnapshotSelectionCriteria criteria) { var proxy = ActorProxy.Create <IServiceFabricSnapshotStore>(new ActorId(persistenceId), _servicefabricServiceUri); proxy.DeleteSnapshotManyAsync(criteria.MaxSequenceNr, criteria.MaxTimeStamp); }
private IUserActor GetUserActor(string userId) { return(ActorProxy.Create <IUserActor>(new ActorId(userId), new Uri("fabric:/ECommerce/UserActorService"))); }
private async Task Fetch() { if (HasLastFetchFinished() == false) { return; } var associationsTask = this.StateManager.GetStateAsync <Dictionary <ActorId, AssociateChunkMetaData> >("associations"); var playersTask = this.StateManager.GetStateAsync <Dictionary <ActorId, MinecraftVersion> >("observers"); var initPlayersTask = this.StateManager.GetStateAsync <Dictionary <ActorId, MinecraftVersion> >("initializeObservers"); await Task.WhenAll(associationsTask, playersTask, initPlayersTask); var associations = associationsTask.Result; var players = playersTask.Result; var initPlayers = initPlayersTask.Result; CalculateDistribution(1000, 4096); ActorId[] actorIds = null; if (players.Count != 0) { actorIds = new ActorId[players.Count]; players.Keys.CopyTo(actorIds, 0); } foreach (var pair in associations) { var association = pair.Value; //if no tracking pieces, then recreate... this handle the re-hydrate of the actor if (_tracking.ContainsKey(pair.Key) == false) { var trackingData = new TrackingChunkMetaData() { fidelity = association.fidelity }; _tracking.Add(pair.Key, trackingData); } var tracking = _tracking[pair.Key]; var task = tracking.updateTask; if (task != null) { var response = task.Result; tracking.playerVersion = response.lastPlayersVersion; tracking.blockVersion = response.lastBlockVersion; } if ((association.needInitObservers.Count > 0) || (actorIds.Length > 0)) { var informActor = ActorProxy.Create <InformActor>(pair.Value.informActorId, this.ServiceUri); tracking.updateTask = informActor.InformOfChange(actorIds, association, tracking); } association.needInitObservers.Clear(); //need to save } //convert over... foreach (var pair in initPlayers) { players.Add(pair.Key, pair.Value); } initPlayers.Clear(); //now save everyting var taskSetInit = this.StateManager.SetStateAsync("initializeObservers", initPlayers); var taskSetObserver = this.StateManager.SetStateAsync("observers", players); var taskSetAssociation = this.StateManager.SetStateAsync("associations", associations); await Task.WhenAll(taskSetInit, taskSetObserver, taskSetAssociation); return; }
public static IDeckActor CreateProxy(string id) { return(new DeckActorProxy(ActorProxy.Create(new ActorId(id), "DeckActor"))); }
/// <summary> /// Registers an observer. This methods is invoked by an observer. /// </summary> /// <param name="topic">The topic.</param> /// <param name="filterExpressions">Specifies filter expressions.</param> /// <param name="entityId">The entity id of the observable.</param> /// This method is called by a management service or actor. /// <returns>The asynchronous result of the operation.</returns> public async Task RegisterObserverActorAsync(string topic, IEnumerable <string> filterExpressions, EntityId entityId) { EntityId id = await this.GetEntityIdAsync(); if (id == null) { return; } if (string.IsNullOrWhiteSpace(topic)) { throw new ArgumentException($"The {nameof(topic)} parameter cannot be null.", nameof(topic)); } if (entityId == null) { throw new ArgumentException($"The {nameof(entityId)} parameter cannot be null.", nameof(entityId)); } IList <string> expressions = filterExpressions as IList <string> ?? filterExpressions.ToList(); for (int k = 1; k <= ConfigurationHelper.MaxQueryRetryCount; k++) { try { if (entityId.Kind == EntityKind.Actor) { IServerObservableActor actorProxy = ActorProxy.Create <IServerObservableActor>(entityId.ActorId, entityId.ServiceUri); await actorProxy.RegisterObserverAsync(topic, expressions, id); } else { IServerObservableService serviceProxy = entityId.PartitionKey.HasValue ? ServiceProxy.Create <IServerObservableService>(entityId.ServiceUri, new ServicePartitionKey(entityId.PartitionKey.Value)) : ServiceProxy.Create <IServerObservableService>(entityId.ServiceUri); await serviceProxy.RegisterObserverAsync(topic, expressions, id); } ConditionalValue <Dictionary <Uri, EntityId> > topicState = await this.StateManager.TryGetStateAsync <Dictionary <Uri, EntityId> >(topic); Dictionary <Uri, EntityId> observableDictionary = topicState.HasValue ? topicState.Value : new Dictionary <Uri, EntityId>(); if (observableDictionary.ContainsKey(entityId.EntityUri)) { return; } observableDictionary.Add(entityId.EntityUri, entityId); StringBuilder stringBuilder = new StringBuilder( $"Observer successfully registered.\r\n[Observable]: {entityId}\r\n[Observer]: {id}\r\n[Subscription]: Topic=[{topic}]"); int i = 1; foreach (string expression in expressions.Where(expression => !string.IsNullOrWhiteSpace(expression))) { stringBuilder.Append($" FilterExpression[{i++}]=[{expression}]"); } await this.StateManager.SetStateAsync(topic, observableDictionary); ActorEventSource.Current.Message(stringBuilder.ToString()); return; } catch (FabricTransientException ex) { ActorEventSource.Current.Error(ex); } catch (AggregateException ex) { foreach (Exception e in ex.InnerExceptions) { ActorEventSource.Current.Error(e); } throw; } catch (Exception ex) { ActorEventSource.Current.Error(ex); throw; } await Task.Delay(ConfigurationHelper.BackoffQueryDelay); } throw new TimeoutException(Constants.RetryTimeoutExhausted); }
private IVariable GetVariableActor(string actorId) { return(ActorProxy.Create <IVariable>(new ActorId(actorId), new Uri("fabric:/ServiceFabricApplication/VariableActorService"))); }
private IUserActor GetActor(string userId) { return(ActorProxy.Create <IUserActor>( new Microsoft.ServiceFabric.Actors.ActorId(userId), new Uri("fabric:/ECommerce/UserActorService"))); }
public static IStockTrendPredictionActor CreateStockTrendPredictionActor(int productId) { return(ActorProxy.Create <IStockTrendPredictionActor>(new ActorId(productId), ApplicationName)); }
public async Task <int> AddItems(AddItemsParams data) { var actor = ActorProxy.Create <ITKCart>(new ActorId(data.ActorId), m_actorUri); return(await actor.AddItems(data.Lines)); }
public async Task UpsertTeamStatsAsync(TeamStatsDto dto) { var actorId = new ActorId($"{dto.TeamId}/{dto.Year}/{dto.Week}".ToUpperInvariant()); var actor = ActorProxy.Create <IFootballStatsActor>(actorId, _settings.ActorServiceUri); await actor.Update(dto); }
public async Task <int> AddItem(AddItemParams data) { var actor = ActorProxy.Create <ITKCart>(new ActorId(data.ActorId), m_actorUri); return(await actor.AddItem(data.Name, data.Count)); }
public async Task SetCustomerInfo(SetCustomerInfoParams data) { var actor = ActorProxy.Create <ITKCart>(new ActorId(data.ActorId), m_actorUri); await actor.SetCustomerInfo(data.Name, data.Surname); }
public async Task ConfirmToQueue(int actorId) { var actor = ActorProxy.Create <ITKCart>(new ActorId(actorId), m_actorUri); await actor.ConfirmToQueue(); }
public override void OnActionCancel(ActorProxy actorProxy) { var mortar = actorProxy.baseEntity as Mortar; mortar.FireLightOff(); }
public static INotificationActor CreateNotificationActor() { return(ActorProxy.Create <INotificationActor>(new ActorId(0), ApplicationName)); }
private IGuyActorCore Guy() { return(ActorProxy.Create <IGuyActorCore>(new ActorId(_connectionGuyDictionary[this.Context.ConnectionId]), new Uri("fabric:/GuyFabric/GuyActorCore"))); }
public static IStockTrendPredictionActor CreateBatchedStockTrendPredictionActor(string actorId) { return(ActorProxy.Create <IStockTrendPredictionActor>(new ActorId(actorId), ApplicationName)); }
/// <summary> /// Unregisters an observer. This methods is invoked by an observer. /// </summary> /// <param name="topic">The topic.</param> /// <param name="entityId">The entity id of the observable.</param> /// This method is called by a management service or actor. /// <returns>The asynchronous result of the operation.</returns> public async Task UnregisterObserverActorAsync(string topic, EntityId entityId) { EntityId id = await this.GetEntityIdAsync(); if (id == null) { return; } if (string.IsNullOrWhiteSpace(topic)) { throw new ArgumentException($"The {nameof(topic)} parameter cannot be null.", nameof(topic)); } if (entityId == null) { throw new ArgumentException($"The {nameof(entityId)} parameter cannot be null.", nameof(entityId)); } for (int k = 1; k <= ConfigurationHelper.MaxQueryRetryCount; k++) { try { ConditionalValue <Dictionary <Uri, EntityId> > topicState = await this.StateManager.TryGetStateAsync <Dictionary <Uri, EntityId> >(topic); if (!topicState.HasValue) { ActorEventSource.Current.Message( $"Observer not registered to the specified topic.\r\n[Observable]: {entityId}\r\n[Observer]: {id}\r\n[Publication]: Topic=[{topic}]"); return; } Dictionary <Uri, EntityId> observableDictionary = topicState.Value; if (!observableDictionary.ContainsKey(entityId.EntityUri)) { ActorEventSource.Current.Message( $"Observer not registered to the specified observable.\r\n[Observable]: {entityId}\r\n[Observer]: {id}\r\n[Publication]: Topic=[{topic}]"); return; } if (entityId.Kind == EntityKind.Actor) { IServerObservableActor actorProxy = ActorProxy.Create <IServerObservableActor>(entityId.ActorId, entityId.ServiceUri); await actorProxy.UnregisterObserverAsync(topic, id); } else { IServerObservableService serviceProxy = entityId.PartitionKey.HasValue ? ServiceProxy.Create <IServerObservableService>(entityId.ServiceUri, new ServicePartitionKey(entityId.PartitionKey.Value)) : ServiceProxy.Create <IServerObservableService>(entityId.ServiceUri); await serviceProxy.UnregisterObserverAsync(topic, id); } observableDictionary.Remove(entityId.EntityUri); if (!observableDictionary.Any()) { await this.StateManager.TryRemoveStateAsync(topic); } else { await this.StateManager.SetStateAsync(topic, observableDictionary); } ActorEventSource.Current.Message( $"Observer successfully unregistered.\r\n[Observable]: {entityId}\r\n[Observer]: {id}\r\n[Subscription]: Topic=[{topic}]"); return; } catch (FabricTransientException ex) { ActorEventSource.Current.Error(ex); } catch (AggregateException ex) { foreach (Exception e in ex.InnerExceptions) { ActorEventSource.Current.Error(e); } throw; } catch (Exception ex) { ActorEventSource.Current.Error(ex); throw; } await Task.Delay(ConfigurationHelper.BackoffQueryDelay); } throw new TimeoutException(Constants.RetryTimeoutExhausted); }
private IIoTActor CreateBuildingActor(string BuildingId, string EventHubName, string ServiceBusNS) { ActorId actorId = new ActorId(string.Format(buildingActorIdFormat, BuildingId, EventHubName, ServiceBusNS)); return(ActorProxy.Create <IIoTActor>(actorId, new Uri(buildingActorService))); }
public virtual async Task ErrorFlowAsync(CancellationToken cancellationToken) { var flowProxy = ActorProxy.Create <IFlowService>(new ActorId(FlowInstanceId.Id), new Uri(FlowServiceUri)); await flowProxy.ErrorFlowAsync(new ActorRequestContext(this.Id.ToString(), Guid.NewGuid().ToString()), FlowInstanceId, null, null, null, cancellationToken); }
public static IProductActor GetProductActor(ActorId productId) { return(ActorProxy.Create <IProductActor>(productId, RepsitoryActorUrl)); }
private DeckActorProxy(ActorProxy proxy) { this.proxy = proxy ?? throw new ArgumentNullException(nameof(proxy)); }
public async Task RunSimulationAsync(string simulationId, string simulationName, IEnumerable <SimulationItem> simulationItems, SimulationIoTHubOptions simulationIoTHubOptions) { var linkOptions = new DataflowLinkOptions { PropagateCompletion = true }; var addDeviceBlock = new TransformBlock <DeviceBlockInformation, DeviceBlockInformation>(async(deviceBlockInformation) => { await deviceBlockInformation.DeviceSimulatorActor.AddDeviceAsync(deviceBlockInformation.DeviceSettings.DeviceServiceSettings, CancellationToken.None); return(deviceBlockInformation); }, new ExecutionDataflowBlockOptions() { MaxDegreeOfParallelism = 4 }); var createTwinBlock = new TransformBlock <DeviceBlockInformation, DeviceBlockInformation>(async(deviceBlockInformation) => { await deviceBlockInformation.DeviceSimulatorActor.CreateDeviceTwinAsync(deviceBlockInformation.DeviceSettings.DeviceServiceSettings, CancellationToken.None); return(deviceBlockInformation); }); var connectToHubBlock = new TransformBlock <DeviceBlockInformation, DeviceBlockInformation>(async(deviceBlockInformation) => { await deviceBlockInformation.DeviceSimulatorActor.ConnectToHubAsync(deviceBlockInformation.DeviceSettings, CancellationToken.None); return(deviceBlockInformation); }); ActionBlock <DeviceBlockInformation> sendEventBlock = null; sendEventBlock = new ActionBlock <DeviceBlockInformation>(async(deviceBlockInformation) => { await deviceBlockInformation.DeviceSimulatorActor.SendEventAsync(); await Task.Delay(deviceBlockInformation.DeviceSettings.DeviceServiceSettings.DeviceInterval); }); addDeviceBlock.LinkTo(createTwinBlock, linkOptions); createTwinBlock.LinkTo(connectToHubBlock, linkOptions); connectToHubBlock.LinkTo(sendEventBlock, linkOptions); // Enumerate the simulations and begin to stand up device instances for each one foreach (var simulationItem in simulationItems) { // Begin producing var deviceItems = Enumerable.Range(0, simulationItem.NumberOfDevices); foreach (var deviceIndex in deviceItems) { // Generate a unique id for this device var deviceNumber = deviceIndex.ToString("000000"); var deviceId = $"{simulationName}_{simulationItem.DeviceType}_{deviceNumber}"; var deviceSimulatorActor = ActorProxy.Create <IDeviceSimulator>(new ActorId(deviceId), deviceActorApplicationUri); var deviceSettings = new DeviceSettings() { InitialStateJson = simulationItem.InitialState, Script = simulationItem.Script, MessageType = simulationItem.MessageType, SimulationSettings = new SimulationSettings() { SimulationId = simulationId, SimulationName = simulationName }, Properties = simulationItem.Properties, DeviceServiceSettings = new DeviceServiceSettings() { DeviceType = simulationItem.DeviceType, DeviceName = deviceId, IoTHubConnectionString = simulationIoTHubOptions.IotHubConnectionString, IoTHubName = simulationIoTHubOptions.IoTHubName, DeviceInterval = simulationItem.Interval, } }; await addDeviceBlock.SendAsync(new DeviceBlockInformation() { DeviceSimulatorActor = deviceSimulatorActor, DeviceSettings = deviceSettings, }); } } // Signal that we've completed adding all the devices addDeviceBlock.Complete(); // Wait for all the devices to be running their simulations await sendEventBlock.Completion; }
protected override void Delete(SnapshotMetadata metadata) { var proxy = ActorProxy.Create <IServiceFabricSnapshotStore>(new ActorId(metadata.PersistenceId), _servicefabricServiceUri); proxy.DeleteSnapshotAsync(metadata.SequenceNr, metadata.Timestamp); }
/// <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 static IProductRepository GetProductRepository(ActorId actorId) { return(ActorProxy.Create <IProductRepository>(actorId, RepsitoryActorUrl)); }
public override IEnumerator Action(ActorProxy actorProxy, ActorProxy targetProxy) { var m = actorProxy.baseEntity as Minion_Support; var ts = actorProxy.transform; if (targetProxy == null || targetProxy.baseEntity.isAlive == false) { m.collider.enabled = true; yield break; } m.collider.enabled = false; ts.LookAt(targetProxy.transform); yield return(null); if (targetProxy == null) { yield break; } SoundManager.instance.Play(m.clip_Jump); actorProxy.PlayAnimationWithRelay(AnimationHash.Skill, targetProxy.baseEntity); var startPos = ts.position; var targetPos = targetProxy.transform.position; var t = 0f; float fV_x; float fV_y; float fV_z; float fg; float fEndTime; float fMaxHeight = 2f; float fHeight; float fEndHeight; float fTime = 0f; float fMaxTime = 0.75f; fEndHeight = targetPos.y - startPos.y; fHeight = fMaxHeight - startPos.y; fg = 2 * fHeight / (fMaxTime * fMaxTime); fV_y = Mathf.Sqrt(2 * fg * fHeight); float a = fg; float b = -2 * fV_y; float c = 2 * fEndHeight; fEndTime = (-b + Mathf.Sqrt(b * b - 4 * a * c)) / (2 * a); fV_x = -(startPos.x - targetPos.x) / fEndTime; fV_z = -(startPos.z - targetPos.z) / fEndTime; var currentPos = new Vector3(); while (t < fEndTime) { t += Time.deltaTime; currentPos.x = startPos.x + fV_x * t; currentPos.y = startPos.y + (fV_y * t) - (0.5f * fg * t * t); currentPos.z = startPos.z + fV_z * t; ts.position = currentPos; yield return(null); } m.collider.enabled = true; var pos = ts.position; pos.y = 0.1f; SoundManager.instance.Play(m.clip_Landing); PoolManager.Get().ActivateObject(m.pref_Dust.name, pos); yield return(null); }
public ITableActor CreateActor(Guid orderId) { var actorId = new ActorId(orderId); return(ActorProxy.Create <ITableActor>(actorId, this._servicename)); }
public ITableActor CreateActor(Guid tableId) { var actorId = new ActorId(tableId); return(ActorProxy.Create <ITableActor>(actorId, ServiceUrl)); }