Exemple #1
0
 public void SendFile(ActorId to, string sourceFile, string destFile)
 {
     foreach (var chunk in Chunks(destFile, sourceFile))
     {
         Node.Send(to, Id, "ReceiveFileChunk", chunk);
     }
 }
 public int GetStatefulPositionCount()
 {
     var actorId = new ActorId(11111);
     var actorAddress = new Uri("fabric:/DartShooting/StatefulActorService");
     IStatefulActor proxy = ActorProxy.Create<IStatefulActor>(actorId, actorAddress);
     return proxy.GetCountAsync().Result;
 }
 public async Task<int> Sub(ActorId idgs, int a, int b)
 {
     ActorEventSource.Current.ActorMessage(this, $"Sub {a} - {b}");
     var proxy = ActorProxy.Create<ITKActorGlobalSum>(idgs, "fabric:/TK_ServiceFabricCalculatorV2");
     await proxy.IncrementSub();
     return a - b;
 }
 public StatelessActor.Interfaces.Models.Position GetPosition()
 {
     var actorId = new ActorId(11111);
     var actorAddress = new Uri("fabric:/DartShooting/StatelessActorService");
     IStatelessActor proxy = ActorProxy.Create<IStatelessActor>(actorId, actorAddress);
     return proxy.GetRandomPosition().Result;
 }
Exemple #5
0
 private static async Task InitializeAsync()
 {
     var hubId = new ActorId("PUBLISH");// Kind of topic;
     var movieId = new ActorId(ImdbType.Movie.ToString());// Kind of topic;
     var starId = new ActorId(ImdbType.Star.ToString());// Kind of topic;
     var proxyHub = ActorProxy.Create<IImdbHub>(hubId, "fabric:/IMDB_Fabric");
     var proxyTopMovie = ActorProxy.Create<IImdbTopRated>(movieId, "fabric:/IMDB_Fabric");
     var proxyTopStar = ActorProxy.Create<IImdbTopRated>(starId, "fabric:/IMDB_Fabric");
     var proxyFaults = ActorProxy.Create<IImdbFaults>(hubId, "fabric:/IMDB_Fabric");
     while (true)
     {
         try
         {
             var subscriber = new ImdbEvents();
             await proxyHub.SubscribeAsync<IImdbEvents>(subscriber);
             await proxyFaults.SubscribeAsync<IImdbFaultEvents>(subscriber);
             await proxyTopMovie.SubscribeAsync<IImdbTopRatedEvents>(subscriber);
             await proxyTopStar.SubscribeAsync<IImdbTopRatedEvents>(subscriber);
             Console.WriteLine("Ready");
             break;
         }
         catch (Exception)
         {
             var actorRef = proxyHub.GetActorReference();
             var uri = actorRef?.ServiceUri;
             Console.WriteLine($"Wait for: {uri}");
             await Task.Delay(2000);
         }
     }
 }
Exemple #6
0
 protected virtual void RunConsole(IMail mail, string exe, string[] args, ActorId shell)
 {
     var console = new ConsoleProcessActor(exe, exe, args);
     Node.Add(console);
     console.AttachConsole(shell);
     Node.Reply(mail, console.Id);
 }
        static async Task MainAsync(string[] args)
        {
            var actorId = new ActorId("49a0400b-3cc1-478b-9db3-9ccb267d37f9");
            var applicationName = "fabric:/IoTSample";

            var device = ActorProxy.Create<IDevice>(actorId, applicationName);
            await device.SubscribeAsync(new DeviceActivityEventsHandler());

            var x = "";
            Console.WriteLine("Hit a to activate the device or x to exit.");

            while (x != "x")
            {
                if (x == "a")
                {
                    await device.MarkAsActive();
                }

                var isActive = await device.IsActive();

                Console.WriteLine("Device is " + (isActive ? "active" : "inactive") );
                
                x = Console.ReadLine();
            }
            
        }
Exemple #8
0
 private static void OutputDeviceInfo(ActorId actorID, Device device)
 {
     Console.WriteLine("Info from Actor {0}: Switch={1}, Temperature={2}, Time={3}",
                         actorID,
                         device.SwitchStatus,
                         device.Temperature,
                         device.UpdateTime);
 }
Exemple #9
0
 private static async void MakeMove(IPlayer player, IGame game, ActorId gameId)
 {
     Random rand = new Random();
     while (true)
     {
         await player.MakeMoveAsync(gameId, rand.Next(0, 3), rand.Next(0, 3));
         await Task.Delay(rand.Next(500, 2000));
     }
 }
        public LiveVehicle Get(int id)
        {
            ActorId vehicleActorId = new ActorId(id);

            var vehicleProxy = ActorProxy.Create<ILiveVehicleActor>(vehicleActorId, "fabric:/LiveVStatefulApp");

            LiveVehicle retVehicle = vehicleProxy.GetCurrentVehicleLiveDataAsync().Result;            
            return retVehicle;           
        }
Exemple #11
0
 public void Send(ActorId to, ActorId fromId, MessageId msg, string name, params object[] args)
 {
     Send(new RpcMail{
         From = fromId,
         To = to,
         MessageId = msg,
         Message = new FunctionCall(name, args),
     });
 }
Exemple #12
0
 public void Send(ActorId to, string name, params object[] args)
 {
     Send(new RpcMail{
         To = to,
         From = ActorId.Empty,
         MessageId = new MessageId(Guid.NewGuid()),
         Message = new FunctionCall(name, args),
     });
 }
 public async Task<int> Add3(ActorId idgs, int a, int b, int c)
 {
     ActorEventSource.Current.ActorMessage(this, $"Add {a} + {b} + {c}");
     var proxy = ActorProxy.Create<ITKActorAdd>(ActorId.NewId(), "fabric:/TK_ServiceFabricCalculatorV2");
     var r1 = await proxy.Add(idgs, a,b);
     proxy = ActorProxy.Create<ITKActorAdd>(ActorId.NewId(), "fabric:/TK_ServiceFabricCalculatorV2"); // New entity
     var r2 = await proxy.Add(idgs, r1, c);
     return r2;
 }
        public IConnection Get(ActorId id)
        {
            if (IsLocal(ref id))
                return localConnection;

            var s = id.ToString().Split('/');
            var computer = NormalizedComputerName(s[0]);
            return Get(new Cls.Connections.EndPoint(computer));
        }
        private static IEnumerable<ActorId> CreateVisualObjectActorIds(int numObjects)
        {
            ActorId[] actorIds = new ActorId[numObjects];
            for (int i = 0; i < actorIds.Length; i++)
            {
                actorIds[i] = new ActorId(string.Format(CultureInfo.InvariantCulture, "Visual Object # {0}", i));
            }

            return actorIds;
        }
        public IEnumerable<int> GetVehiclesListInZipCodeArea(string zipCode)
        {
            ActorId vehiclesLocatorQueryActorId = new ActorId(zipCode);
            var vehiclesLocatorQueryActor = ActorProxy.Create<IVehiclesLocatorActor>(vehiclesLocatorQueryActorId, "fabric:/LiveVStatefulApp");

            var vehiclesListIds = vehiclesLocatorQueryActor.GetVehicleIdListAsync().Result;

            return vehiclesListIds.AsEnumerable();

            //return new string[] { "Element 1", "Element 2" };
        }
Exemple #17
0
 public void Remove(ActorId id)
 {
     lock (actors)
     {
         DistributedActor actor;
         if (!actors.TryGetValue(id.Name, out actor))
             return;
         if (!IsMatch(id, actor.Id))
             return;
         actors.Remove(id.Name);
     }
 }
        public Task OpenAsync(PartitionContext context)
        {
            var subscription = query(pump);
            subscription.Subscribe(async d =>
            {
                string deviceId = d.deviceId;
                var actorId = new ActorId(deviceId);
                var device = ActorProxy.Create<IDevice>(actorId);
                await device.MarkAsActive();
            });

            return Task.FromResult(0);
        }
        /// <summary>
        /// This method uses an IReliableQueue to store completed RestockRequests which are later sent to the client using batch processing.
        /// We could send the request immediately but we prefer to minimize traffic back to the Inventory Service by batching multiple requests
        /// in one trip. 
        /// </summary>
        /// <param name="actorId"></param>
        /// <param name="request"></param>
        public async void RestockRequestCompleted(ActorId actorId, RestockRequest request)
        {
            IReliableQueue<RestockRequest> completedRequests = await this.StateManager.GetOrAddAsync<IReliableQueue<RestockRequest>>(CompletedRequestsQueueName);

            using (ITransaction tx = this.StateManager.CreateTransaction())
            {
                await completedRequests.EnqueueAsync(tx, request);
                await tx.CommitAsync();
            }

            IRestockRequestActor restockRequestActor = ActorProxy.Create<IRestockRequestActor>(actorId, this.ApplicationName);
            await restockRequestActor.UnsubscribeAsync<IRestockRequestEvents>(this); //QUESTION:What does this method do?
        }
        private Task<string> GetObjectAsync(ActorId objectId, CancellationToken cancellationToken)
        {
            IVisualObjectActor actorProxy = ActorProxy.Create<IVisualObjectActor>(objectId, this.serviceUri);

            try
            {
                return actorProxy.GetStateAsJsonAsync();
            }
            catch (Exception)
            {
                // ignore the exceptions
                return Task.FromResult(String.Empty);
            }
        }
        public IActionResult Post([FromBody]LiveVehicle vehicle)
        {
            //Add vehicle as new vehicle Actor and add it to the VehicleLocator collection
            //Check first that it doesn't exist!

            //Here we would find out the ZipCode related to the GPS coordinates provided by the vehicle data.
            //For now, I set the ZipCode directly
            vehicle.CurrentZipCode = "98101";

            //Add (if not exists to List of vehicles per ZipCode in VehiclesLocatorActor Service)

            //Create a VehicleLocator proxy to check if the vehicle already exists in our system
            //I use ZipCode as ID for the VehiclesList locator actor ID service            
            ActorId vehiclesLocatorActorId = new ActorId(vehicle.CurrentZipCode);
            var vehicleLocatorProxy = ActorProxy.Create<IVehiclesLocatorActor>(vehiclesLocatorActorId, "fabric:/LiveVStatefulApp");

            bool vehicleExist = false;
            vehicleExist = vehicleLocatorProxy.IsVehicleInZipCodeAreaAsync(vehicle.VehicleId).Result;

            string detailedResponse;

            if (!vehicleExist)
            {
                //Add vehicle to ZipCode Area Actor Manager
                vehicleLocatorProxy.AddVehicleToZipAreaAsync(vehicle.VehicleId);

                //Create and update the vehicle actor just in case it didn't exist
                ActorId vehicleActorId = new ActorId(vehicle.VehicleId);
                var vehicleProxy = ActorProxy.Create<ILiveVehicleActor>(vehicleActorId, "fabric:/LiveVStatefulApp");

                //Add/Update data to Vehicle Actor
                vehicleProxy.SetVehicleLiveDataAsync(vehicle).Wait();

                detailedResponse = "Vehicle ID " + vehicle.VehicleId.ToString() + "added to ZipCode area " + vehicle.CurrentZipCode;
            }
            else
                detailedResponse = "Vehicle already in ZipCode area. Nothing is added";

            // Get the response.  
            //(The response could be improved by adding the Partition where the Actor has been created, etc.) 
            // --> (CDLTLL) --> System.Fabric.FabricRuntime.GetNodeContext().NodeName

            //string message = "Vehicle added to MyShuttle Live IoT system";
            //String.Format("{0} added to partition {1} at {2}", seatMap.Name, client.ResolvedServicePartition.Info.Id, serviceAddress),
            //Encoding.UTF8,
            //"text/html");

            return new HttpStatusCodeResult(201); //201 Created              
        }
Exemple #22
0
 public ActorId[] Get(ActorId id)
 {
     lock (creatorToOther)
     {
         var actors = new HashSet<ActorId>();
         List<ActorId> a;
         foreach (var alias in DnsAlias.Get(id))
         {
             if (creatorToOther.TryGetValue(alias, out a))
                 actors.AddRange(a);
             if (otherToCreator.TryGetValue(alias, out a))
                 actors.AddRange(a);
         }
         return actors.ToArray();
     }
 }
Exemple #23
0
        protected override async Task RunAsync(
            CancellationToken cancellationToken)
        {
            var auth = await AuthorizeAsync();
            var twitterCtx = new TwitterContext(auth);

            await ClearOldTwits(twitterCtx);

            var stream = from srm in twitterCtx.Streaming
                         where srm.Type == StreamingType.Filter &&
                                srm.Track == "sdpf"
                         select srm;

            cancellationToken.Register(
                () => Environment.Exit(-1));

            #region Log

            var logId = Constants.Singleton;
            var logProxy = ActorProxy.Create<IImdbFaults>(logId);
            await logProxy.Report($"Twitter Start Listening");

            #endregion // Log

            await stream.StartAsync(async context =>
            {
                if (context.Entity == null && context.EntityType != StreamEntityType.Status)
                    return;
                var status = (Status)context.Entity;
                var url = status.Entities.UrlEntities.FirstOrDefault()?.ExpandedUrl;

                var input = new Input
                {
                    UserImageUrl = status.User.ProfileImageUrl,
                    UserName = status.User.Name
                };

                var id = new ActorId(url); // cache process effort by routing to the same actor
                var proxy = ActorProxy.Create<IImdb>(id, "fabric:/IMDB_Fabric");
                if (!await proxy.TryProcess(input))
                    Trace.WriteLine($"Fault url [{url}]");
                else
                    await logProxy.Report($"Twitt {url}");
            });

            await Task.Delay(TimeSpan.FromSeconds(0.5), cancellationToken);
        }
		static void Main(string[] args)
		{
			string applicationName = "fabric:/MyServiceFabricApp";
			var actorId = new ActorId("PubActor");
			IPublishingActor pubActor = null;

			while (pubActor == null)
			{
				try
				{
					pubActor = ActorProxy.Create<IPublishingActor>(actorId, applicationName);
				}
				catch
				{
					Thread.Sleep(200);
				}
			}

			
			RegisterSubscribers(applicationName);
			

			while (true)
			{
				Console.Clear();
				Console.WriteLine("Hit 1 to send message one, or hit escape to exit.");
				var key = Console.ReadKey(true);

				switch (key.Key)
				{
					case ConsoleKey.D1:
						{
							pubActor.PublishMessageOneAsync().GetAwaiter().GetResult();
							Console.WriteLine("Sent message one!");
						}
						break;

					case ConsoleKey.Escape:
						return;
				}

			}

		}
		private static void RegisterSubscribers(string applicationName)
		{
			for (int i = 0; i < 10; i++)
			{
				var actorId = new ActorId("SubActor" + i.ToString("0000"));

				ISubscribingActor subActor = null;
				while (subActor == null)
				{
					try
					{
						subActor = ActorProxy.Create<ISubscribingActor>(actorId, applicationName, nameof(ISubscribingActor));
						subActor.RegisterAsync().GetAwaiter().GetResult();
					}
					catch
					{
						Thread.Sleep(200);
					}
				}
			}
		}
        static void Main(string[] args)
        {
            var actorId = new ActorId("MultipleActorDemo");
            var grumpyProxy = ActorProxy.Create<ITalkingActor>(actorId, new Uri("fabric:/MultipleActors/GrumpyActorService"));
            var happyProxy = ActorProxy.Create<ITalkingActor>(actorId, new Uri("fabric:/MultipleActors/HappyActorService"));

            int value;
            do
            {
                Console.WriteLine("\n\nPress 1 for Synchronicity demo and 2 for Reentrancy demo:");
                value = Convert.ToInt32(Console.ReadLine());
                switch (value)
                {
                    case 1:
                        RunHappyMultipleAsync(happyProxy).Wait();
                        break;
                    case 2:
                        RunHappyGrumpyAsync(grumpyProxy, happyProxy).Wait();
                        break;
                }
            } while (value > 0 && value < 3);
            Console.WriteLine("\n\n----- Press any key to exit! -----");
            Console.ReadLine();
        }
 void Detach(IMail m, ActorId sendTo)
 {
     lock (actors)
         actors.Remove(sendTo);
 }
 internal void AttachConsole(ActorId sendTo)
 {
     lock (actors)
         actors.Add(sendTo);
 }
 public BaseMinerActor(ActorService actorService, ActorId actorId)
     : base(actorService, actorId)
 {
 }
Exemple #30
0
 public GenericStorage(ActorService actorService, ActorId actorId)
     : base(actorService, actorId)
 {
 }
Exemple #31
0
 /// <summary>
 /// Initializes a new instance of ChatActorService
 /// </summary>
 /// <param name="actorService">The Microsoft.ServiceFabric.Actors.Runtime.ActorService that will host this actor instance.</param>
 /// <param name="actorId">The Microsoft.ServiceFabric.Actors.ActorId for this actor instance.</param>
 public ChatActor(ActorService actorService, ActorId actorId)
     : base(actorService, actorId)
 {
 }
Exemple #32
0
 /// <summary>
 /// Initializes a new instance of POCActor
 /// </summary>
 /// <param name="actorService">The Microsoft.ServiceFabric.Actors.Runtime.ActorService that will host this actor instance.</param>
 /// <param name="actorId">The Microsoft.ServiceFabric.Actors.ActorId for this actor instance.</param>
 public POCActor(ActorService actorService, ActorId actorId, IMediator mediator)
     : base(actorService, actorId)
 {
     this.Mediator = mediator;
 }
Exemple #33
0
 protected DocumentActor(ActorService actorService, ActorId actorId, ILogger logger) : base(actorService, actorId)
 {
     this._logger = logger;
 }
Exemple #34
0
 public DoctorActor(ActorService actorService, ActorId actorId)
     : base(actorService, actorId)
 {
 }
 public InternalsVisibleActor(ActorService actorService, ActorId actorId) : base(actorService, actorId)
 {
 }
 /// <summary>
 /// Initializes a new instance of ShapeActor.
 /// </summary>
 /// <param name="actorService">The Microsoft.ServiceFabric.Actors.Runtime.ActorService that will host this actor instance.</param>
 /// <param name="actorId">The Microsoft.ServiceFabric.Actors.ActorId for this actor instance.</param>
 public ShapeActor(ActorService actorService, ActorId actorId)
     : base(actorService, actorId)
 {
 }
 /// <summary>
 /// This method is called whenever an actor is activated.
 /// An actor is activated the first time any of its methods are invoked.
 /// </summary>
 public ActorServiceSample(ActorService actorService, ActorId actorId) : base(actorService, actorId)
 {
 }
 public E(ActorId id)
     : base()
 {
     this.Id = id;
 }
 public NLMSAlgorithmActor(ActorService actorService, ActorId actorId)
     : base(actorService, actorId)
 {
 }
 public TankGameSessionList(ActorService actorService, ActorId actorId)
     : base(actorService, actorId)
 {
 }
Exemple #41
0
 /// <summary>
 /// Initializes a new instance of PID
 /// </summary>
 /// <param name="actorService">The Microsoft.ServiceFabric.Actors.Runtime.ActorService that will host this actor instance.</param>
 /// <param name="actorId">The Microsoft.ServiceFabric.Actors.ActorId for this actor instance.</param>
 public PID(ActorService actorService, ActorId actorId)
     : base(actorService, actorId)
 {
 }
 public E2(ActorId id)
 {
     this.Id = id;
 }
Exemple #43
0
        public async Task <PipelineRunnerActorDocument> CreateNewSiteRegistrationAsync(ActorId id, byte[] model, CancellationToken token)
        {
            var doc = new PipelineRunnerActorDocument {
                Id = id.GetGuidId(), Data = model
            };

            await SaveDocumentAsync(id, new DocumentWrapper { Document = doc }, token);

            return(doc);
        }
Exemple #44
0
 /// <summary>
 ///     Initializes a new instance of ObservableActorBase
 /// </summary>
 /// <param name="actorService">The Microsoft.ServiceFabric.Actors.Runtime.ActorService that will host this actor instance.</param>
 /// <param name="actorId">The Microsoft.ServiceFabric.Actors.ActorId for this actor instance.</param>
 protected ObservableActorBase(ActorService actorService, ActorId actorId)
     : base(actorService, actorId)
 {
 }
 public SetupEvent(ActorId id)
 {
     this.Id = id;
 }
 private IReliableMessagingServer GetActor()
 {
     return(ActorProxy.Create <IReliableMessagingServer>(
                ActorId.CreateRandom(),
                new Uri("fabric:/ReliableMessaging/ReliableMessagingServerActorService")));
 }
Exemple #47
0
 /// <summary>
 /// Initializes a new instance of Actor
 /// </summary>
 /// <param name="actorService">The Microsoft.ServiceFabric.Actors.Runtime.ActorService that will host this actor instance.</param>
 /// <param name="actorId">The Microsoft.ServiceFabric.Actors.ActorId for this actor instance.</param>
 public BottleFillerActor(ActorService actorService, ActorId actorId)
     : base(actorService, actorId)
 {
 }
Exemple #48
0
 public MissingActorEventArgs(Type actorType, ActorId id)
 {
     ActorType = actorType;
     Id        = id;
 }
Exemple #49
0
 public CustomerOrderActor(ActorService actorService, ActorId actorId)
     : base(actorService, actorId)
 {
 }
 public InvoiceAnalytics(ActorService actorService, ActorId actorId) : base(actorService, actorId)
 {
 }
 /// <summary>
 ///     Initializes a new instance of ActorService1
 /// </summary>
 /// <param name="actorService">The Microsoft.ServiceFabric.Actors.Runtime.ActorService that will host this actor instance.</param>
 /// <param name="actorId">The Microsoft.ServiceFabric.Actors.ActorId for this actor instance.</param>
 public ActorService1(ActorService actorService, ActorId actorId)
     : base(actorService, actorId)
 {
 }
Exemple #52
0
 public TerminateReq(ActorId sender)
 {
     this.Sender = sender;
 }
 public OnActivateActor(ActorService actorService, ActorId actorId) : base(actorService, actorId)
 {
 }
Exemple #54
0
            private void InitOnEntry(Event e)
            {
                ActorId id = (e as E2).Mid;

                this.SendEvent(id, UnitEvent.Instance);
            }
 void Attach(IMail m, ActorId sendTo)
 {
     AttachConsole(sendTo);
 }
Exemple #56
0
 public E2(ActorId id)
 {
     this.Mid = id;
 }
 void ScreenUpdate(IMail m, Screen screen, CursorPosition position)
 {
     console.Screen = screen;
     console.CursorPosition = position;
     remote = m.As<RpcMail>().From.As<ActorId>();
 }
Exemple #58
0
 public PipelineRunnerActor(ActorService actorService, ActorId actorId, ILogger logger) : base(actorService, actorId, logger)
 {
 }
 public static void Execute(IActorRuntime runtime)
 {
     runtime.RegisterMonitor <LivenessMonitor>();
     ActorId driver = runtime.CreateActor(typeof(FailoverDriver), new FailoverDriver.ConfigEvent(RunForever));
 }
 /// <summary>
 /// Initializes a new instance.
 /// </summary>
 /// <param name="actorService"></param>
 /// <param name="actorId"></param>
 protected ActivityActorBase(ActorService actorService, ActorId actorId) :
     base(actorService, actorId)
 {
 }