public async Task DeleteActorByID(
     [FromQuery] int id)
 {
     var actorid           = new ActorId(id);
     var actorServiceProxy = ActorServiceProxy.Create(new Uri("fabric:/ServiceFabricActor/FabricActorServiceActorService"), actorid);
     await actorServiceProxy.DeleteActorAsync(actorid, new CancellationToken());
 }
        private async Task <long> GetCountAsync(string serviceName)
        {
            string serviceUri = _serviceContext.CodePackageActivationContext.ApplicationName + "/" + serviceName;

            ServicePartitionList partitions = await _fabricClient.QueryManager.GetPartitionListAsync(new Uri(serviceUri));

            long count = 0;

            foreach (Partition partition in partitions)
            {
                long          partitionKey      = ((Int64RangePartitionInformation)partition.PartitionInformation).LowKey;
                IActorService actorServiceProxy = ActorServiceProxy.Create(new Uri(serviceUri), partitionKey);

                ContinuationToken continuationToken = null;

                do
                {
                    PagedResult <ActorInformation> page = await actorServiceProxy.GetActorsAsync(continuationToken, CancellationToken.None);

                    count += page.Items.Where(x => x.IsActive).LongCount();

                    continuationToken = page.ContinuationToken;
                }while (continuationToken != null);
            }

            return(count);
        }
Пример #3
0
        public void TestRemotingActors_NoSerializationError()
        {
            FabricClient         fabricClient  = new FabricClient("localhost:19000");
            ServicePartitionList partitionList = fabricClient.QueryManager.GetPartitionListAsync(new Uri("fabric:/Codit.Core.Application/DeviceActorService")).Result;

            ContinuationToken continuationToken  = null;
            var cancellationTokenSource          = new CancellationTokenSource();
            List <ActorInformation> activeActors = new List <ActorInformation>();

            foreach (var partition in partitionList)
            {
                var           key = partition.PartitionInformation as Int64RangePartitionInformation;
                IActorService actorServiceProxy = ActorServiceProxy.Create <IMyService>(new Uri("fabric:/Codit.Core.Application/DeviceActorService"), key.LowKey);

                do
                {
                    PagedResult <ActorInformation> page = actorServiceProxy.GetActorsAsync(continuationToken, cancellationTokenSource.Token).Result;
                    activeActors.AddRange(page.Items.Where(x => x.IsActive));
                    continuationToken = page.ContinuationToken;
                }while (continuationToken != null);
            }

            foreach (var actor in activeActors)
            {
                Assert.NotNull(actor.ActorId.ToString());
            }
        }
 /// <summary>
 /// Schedule a task on the thread pool to delete the actor with a specific Id. Override if needed
 /// </summary>
 /// <param name="cancellationToken"></param>
 protected virtual void DisposeActor(ActorId actorId, Uri actorServiceUri, CancellationToken cancellationToken)
 {
     Task.Run(async() =>
     {
         var serviceProxy = ActorServiceProxy.Create(actorServiceUri, actorId);
         await serviceProxy.DeleteActorAsync(actorId, cancellationToken);
     }, cancellationToken);
 }
Пример #5
0
        public async void Delete(string vehicleId)
        {
            var actorId = new ActorId($"SimulatedCar:{vehicleId}");
            var proxy   = ActorProxy.Create <ICarActor>(actorId);
            await proxy.StopAsync(CancellationToken.None);

            var serviceProxy = ActorServiceProxy.Create(new Uri("fabric:/CarActorSF/CarActorService"), actorId);
            await serviceProxy.DeleteActorAsync(actorId, CancellationToken.None);
        }
Пример #6
0
 public WebFront(StatelessServiceContext context)
     : base(context)
 {
     this.LoadLiveCounterSettings();
     this.counter = new LivenessCounter <string>(expirationIntervalInSeconds, fuzzIntervalInSeconds);
     nodeName     = context.NodeContext.NodeName;
     serviceUri   = ActorNameFormat.GetFabricServiceUri(typeof(IContainerAggregatorActor));
     proxy        = ActorServiceProxy.Create <IContainerAggregator>(serviceUri, 0);
     reportTimer  = new Timer(this.Report, null, TimeSpan.FromSeconds(reportIntervalInSeconds), TimeSpan.FromSeconds(reportIntervalInSeconds));
 }
        private async Task <KeyValuePair <string, string> > GetRandomIdsAsync()
        {
            ServiceUriBuilder serviceUri = new ServiceUriBuilder(this.GetSetting(DeviceServiceName));
            Uri fabricServiceName        = serviceUri.ToUri();

            CancellationTokenSource cts        = new CancellationTokenSource(TimeSpan.FromMinutes(5));
            CancellationToken       token      = cts.Token;
            FabricClient            fc         = new FabricClient();
            ServicePartitionList    partitions = await fc.QueryManager.GetPartitionListAsync(fabricServiceName);

            string doctorId = null;

            while (!token.IsCancellationRequested && doctorId == null)
            {
                try
                {
                    foreach (Partition p in partitions)
                    {
                        long partitionKey = ((Int64RangePartitionInformation)p.PartitionInformation).LowKey;
                        token.ThrowIfCancellationRequested();
                        ContinuationToken queryContinuationToken = null;
                        IActorService     proxy = ActorServiceProxy.Create(fabricServiceName, partitionKey);
                        PagedResult <ActorInformation> result = await proxy.GetActorsAsync(queryContinuationToken, token);

                        foreach (ActorInformation info in result.Items)
                        {
                            token.ThrowIfCancellationRequested();

                            ActorId      deviceActorId = info.ActorId;
                            IDeviceActor deviceActor   = ActorProxy.Create <IDeviceActor>(deviceActorId, fabricServiceName);

                            try
                            {
                                doctorId = (await deviceActor.GetAssociatedDoctorAsync()).ToString();

                                return(new KeyValuePair <string, string>(deviceActorId.ToString(), doctorId));
                            }
                            catch (Exception e)
                            {
                                ServiceEventSource.Current.Message("Exception when obtaining actor ID. No State? " + e.ToString());
                                continue;
                            }
                        }
                        //otherwise we will bounce around other partitions until we find an actor
                    }
                }
                catch (Exception e)
                {
                    ServiceEventSource.Current.Message("Exception when obtaining actor ID: " + e.ToString());
                    continue;
                }
            }

            throw new InvalidOperationException("Couldn't find actor within timeout");
        }
        public List <PartitionActors> Get()
        {
            Int64 highKey        = 9223372036854775807;
            Int64 lowKey         = -9223372036854775808;
            int   partitionCount = 10;
            Int64 partitionRange = highKey / partitionCount - lowKey / partitionCount; // number of elements per interval of range
            int   actorCount     = 0;

            CancellationToken cancellationToken = default(CancellationToken);

            List <PartitionActors>  partitionActors      = new List <PartitionActors>();
            List <ActorInformation> actorInformationList = new List <ActorInformation>();

            for (int i = 0; i < partitionCount; i++)
            {
                // this generates a key in each of the partitions
                var partitionKeyInPartition = lowKey + i * partitionRange + 10;

                // note proxy to actor service, not a specific actor
                var actorProxy = ActorServiceProxy.Create(new Uri("fabric:/SFActors.BankAccounts/BankAccountActorService"), partitionKeyInPartition);

                // get all the actors in the partition
                ContinuationToken continuationToken = null;
                do
                {
                    PagedResult <ActorInformation> page = actorProxy.GetActorsAsync(continuationToken, cancellationToken).GetAwaiter().GetResult();
                    actorInformationList.AddRange(page.Items);
                    continuationToken = page.ContinuationToken;
                } while (continuationToken != null);

                // find the partition id for the current partition key
                ServicePartitionKey      partitionKey             = new ServicePartitionKey(partitionKeyInPartition);
                ServicePartitionResolver servicePartitionResolver = ServicePartitionResolver.GetDefault();
                ResolvedServicePartition partition = servicePartitionResolver.ResolveAsync(new Uri("fabric:/SFActors.BankAccounts/BankAccountActorService"), partitionKey, cancellationToken).GetAwaiter().GetResult();

                // prepare the result
                if (actorInformationList.Count > 0)
                {
                    PartitionActors pa = new PartitionActors
                    {
                        PartitionId       = partition.Info.Id,
                        ActorsInPartition = actorInformationList.Select(x => x.ActorId.GetStringId()).ToList()
                    };
                    partitionActors.Add(pa);

                    actorCount += actorInformationList.Count;
                    actorInformationList.Clear();
                }
            }

            ServiceEventSource.Current.Message("@AccountsController. {0} actors in {1} partitions", actorCount, partitionActors.Count);

            return(partitionActors);
        }
Пример #9
0
        /// <summary>
        /// This is the entry point of the service host process.
        /// </summary>
        private static void Main()
        {
            try
            {
                // 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

                var builder = new ContainerBuilder();

                // Register a type that be injected into the actor service.
                builder.Register(c => new Logger()).As <ILogger>();

                // Register the interceptors for managing lifetime scope disposal.
                builder.RegisterModule <AutofacServiceFabricModule>();

                // Register all actors in the specified assemblies.
                builder.RegisterActors(Assembly.GetExecutingAssembly());

                // Register a single actor.
                //builder.RegisterActor<DemoActor>();

                using (var container = builder.Build())
                {
                    // Register an actor service factory with the ActorRuntime.
                    container.RegisterActorServiceFactory <DemoActor>();

                    Task.Run(() =>
                    {
                        Task.Delay(TimeSpan.FromSeconds(15));

                        // Invoke the actor to create an instance.
                        var actorId    = ActorId.CreateRandom();
                        var actorProxy = ActorProxy.Create <IDemoActor>(actorId);
                        var count      = actorProxy.GetCountAsync(new CancellationToken()).GetAwaiter().GetResult();

                        Debug.WriteLine($"Actor {actorId} has count {count}");

                        // Delete the actor to trigger deactive.
                        var actorServiceProxy = ActorServiceProxy.Create(
                            new Uri("fabric:/AutofacServiceFabricDemo/DemoActorService"), actorId);

                        actorServiceProxy.DeleteActorAsync(actorId, new CancellationToken()).GetAwaiter().GetResult();
                    });

                    Thread.Sleep(Timeout.Infinite);
                }
            }
            catch (Exception e)
            {
                ActorEventSource.Current.ActorHostInitializationFailed(e.ToString());
                throw;
            }
        }
        public async Task DeleteActorById([FromQuery] int id)
        {
            var actorId = new ActorId(id);                                                                                                        // we're creating new Actor's Id

            var actorServiceProxy = ActorServiceProxy.Create(new Uri("fabric:/ProductActorAplication/ProductActorServiceActorService"), actorId); // we're connecting to actor service, not actor itself

            await actorServiceProxy.DeleteActorAsync(actorId, new CancellationToken());                                                           // allows us to delete actor and state

            // note: common use of this is when for example service proxy is on timer (e.g. one a day/week)
            // so we iterate through all actors and we delete the ones which meets conditions of being certain time old
        }
Пример #11
0
        public async Task DeleteWorkerAsync(Guid uuid, CancellationToken cancellationToken)
        {
            var actorId      = new ActorId(uuid);
            var actorService = ActorServiceProxy.Create(workerServiceUri, actorId);
            var page         = await actorService.GetActorsAsync(null, cancellationToken);

            if (page.Items.Any(x => x.ActorId == actorId && x.IsActive))
            {
                await actorService.DeleteActorAsync(actorId, cancellationToken);
            }
        }
Пример #12
0
        protected override async Task OnDeactivateAsync()
        {
            if (_updateTimer != null)
            {
                UnregisterTimer(_updateTimer);
            }

            await ActorServiceProxy.Create <IActorBaseService>(ServiceUri, Id).DeactivateAsync(Id);

            await base.OnDeactivateAsync();
        }
        private async Task <List <ActorInformation> > GetAllActors(Uri servicePath)
        {
            FabricClient.QueryClient query = new FabricClient().QueryManager;
            List <long> partitions         = new List <long>();
            string      continuation       = null;

            do
            {
                ServicePartitionList partitionList =
                    await query.GetPartitionListAsync(servicePath, continuation);

                foreach (Partition item in partitionList)
                {
                    ServicePartitionInformation info = item.PartitionInformation;
                    switch (info.Kind)
                    {
                    case ServicePartitionKind.Int64Range:
                        partitions.Add(((Int64RangePartitionInformation)info).LowKey);
                        break;

                    case ServicePartitionKind.Singleton:
                        partitions.Add(0L);
                        break;

                    default:
                        throw new InvalidOperationException(
                                  string.Format(
                                      "Unexpected partition kind.  Found {0}, expected either Int64Range or Singleton",
                                      info.Kind));
                    }
                }
                continuation = partitionList.ContinuationToken;
            } while (!string.IsNullOrEmpty(continuation));

            List <ActorInformation> activeActors = new List <ActorInformation>();

            foreach (long partitionId in partitions)
            {
                IActorService     actorServiceProxy = ActorServiceProxy.Create(servicePath, partitionId);
                ContinuationToken continuationToken = null;

                do
                {
                    PagedResult <ActorInformation> page =
                        await actorServiceProxy.GetActorsAsync(continuationToken, CancellationToken.None);

                    activeActors.AddRange(page.Items);
                    continuationToken = page.ContinuationToken;
                } while (continuationToken != null);
            }
            return(activeActors);
        }
Пример #14
0
        public async Task <IActionResult> DeleteMonitor(string serviceName)
        {
            if (string.IsNullOrWhiteSpace(serviceName))
            {
                return(BadRequest());
            }

            var n = new Uri("fabric:/" + serviceName);
            var p = ActorProxy.Create <IMonitorActor>(new ActorId(n.ToString()));
            var s = ActorServiceProxy.Create(p.GetActorReference().ServiceUri, p.GetActorId());
            await s.DeleteActorAsync(p.GetActorId(), CancellationToken.None);

            return(Ok());
        }
Пример #15
0
        /// <summary>
        /// This is the entry point of the service host process.
        /// </summary>
        private static void Main()
        {
            try
            {
                // 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

                // Start with the trusty old container builder.
                var builder = new ContainerBuilder();

                // Register any regular dependencies.
                builder.RegisterModule(new LoggerModule(ActorEventSource.Current.Message));

                // Register the Autofac magic for Service Fabric support.
                builder.RegisterServiceFabricSupport();

                // Register the actor service.
                builder.RegisterActor <DemoActor>();

                using (builder.Build())
                {
                    Task.Run(async() =>
                    {
                        // Invoke the actor to create an instance.
                        var actorId    = ActorId.CreateRandom();
                        var actorProxy = ActorProxy.Create <IDemoActor>(actorId);
                        var count      = actorProxy.GetCountAsync(new CancellationToken()).GetAwaiter().GetResult();

                        Debug.WriteLine($"Actor {actorId} has count {count}");

                        await Task.Delay(TimeSpan.FromSeconds(15));

                        // Delete the actor to trigger deactive.
                        var actorServiceProxy = ActorServiceProxy.Create(
                            new Uri("fabric:/AutofacServiceFabricDemo/DemoActorService"), actorId);

                        await actorServiceProxy.DeleteActorAsync(actorId, new CancellationToken());
                    });

                    Thread.Sleep(Timeout.Infinite);
                }
            }
            catch (Exception e)
            {
                ActorEventSource.Current.ActorHostInitializationFailed(e.ToString());
                throw;
            }
        }
        public async Task DestroyAsync(T actor, CancellationToken cancellationToken)
        {
            try
            {
                ActorId actorId = actor.GetActorId();

                IActorService myActorServiceProxy = ActorServiceProxy.Create(
                    new Uri($"{FabricRuntime.GetActivationContext().ApplicationName}/{_actorServiceName}"), actorId);

                await myActorServiceProxy.DeleteActorAsync(actorId, cancellationToken);
            }
            catch (Exception ex)
            {
            }
        }
Пример #17
0
        public static async Task <bool> DeleteActor <T>(this ActorId id, Uri serviceUri = null) where T : IActor
        {
            CancellationToken token = new CancellationToken();

            if (serviceUri == null)
            {
                serviceUri = ServiceUriHelper.Resolve <T>();
            }
            var            proxy             = id.Proxy <T>(serviceUri);
            ActorReference actorReference    = ActorReference.Get(proxy);
            var            actorServiceProxy = ActorServiceProxy.Create(actorReference.ServiceUri, id);
            await actorServiceProxy.DeleteActorAsync(id, token);

            return(await Task.FromResult(true));
        }
        public int DeleteAll(int bogus = 1)
        {
            IEnumerable <string> actorIds         = Get().SelectMany(x => x.ActorsInPartition);
            CancellationToken    cancelationToken = default(CancellationToken);
            int count = 0;

            foreach (string actorId in actorIds)
            {
                ActorId       actorToDelete       = new ActorId(actorId);
                IActorService myActorServiceProxy = ActorServiceProxy.Create(new Uri("fabric:/SFActors.BankAccounts/BankAccountActorService"), actorToDelete);
                myActorServiceProxy.DeleteActorAsync(actorToDelete, cancelationToken);
                count++;
            }

            return(count);
        }
        private async Task RunAsyncInternal(CancellationToken cancellationToken)
        {
            IRuntimeStore runtimeStoreClient = ServiceProxy.Create <IRuntimeStore>(new Uri("fabric:/Prototype/RuntimeStore"), new ServicePartitionKey(0));

            ServiceEventSource.Current.ServiceMessage(this.Context, "Service has woken up and executing now.");

            // Get the tenant id from Runtime store
            long actorId = await runtimeStoreClient.GetTenantInProgress();

            if (actorId == -1)
            {
                ServiceEventSource.Current.ServiceMessage(this.Context, "No tenant found to work on.");
                return;
            }

            ServiceEventSource.Current.ServiceMessage(this.Context, "Got tenant {0} to work on.", actorId);

            ITenantUpdateActor tenantUpdateActor = ActorProxy.Create <ITenantUpdateActor>(new ActorId(actorId), actorServicePath);
            string             currentState      = await tenantUpdateActor.GetWorkflowState();

            ServiceEventSource.Current.ServiceMessage(this.Context, "Current state of tenant {0} is {1}", actorId, currentState);

            if (currentState == "Completed")// any terminal
            {
                // Move tenant id in runtime store to Terminal Queue
                ServiceEventSource.Current.ServiceMessage(this.Context, "Moving the tenant to terminal state.");
                await runtimeStoreClient.TransitionTenantToTerminal(actorId, "Completed");

                // Delete actor
                ServiceEventSource.Current.ServiceMessage(this.Context, "Deleting the actor {0} in service.", actorId);
                ActorId       actorToDelete       = new ActorId(actorId);
                IActorService myActorServiceProxy = ActorServiceProxy.Create(actorServicePath, actorToDelete);
                await myActorServiceProxy.DeleteActorAsync(actorToDelete, cancellationToken);
            }
            else
            {
                // TODO Call Execute, mainly to make sure that it is doing work and if needed, move to alerted state

                /*ServiceEventSource.Current.ServiceMessage(this.Context, "Executing the actor {0} in service.", actorId);
                 * await tenantUpdateActor.Execute();*/

                // Re-put to the in-progress queue
                await runtimeStoreClient.AddTenantInProgress(actorId, "InProgress");
            }

            // If workflow running for long and still, not complete, set to terminal state
        }
        public async Task StopSimulation(string simulationName)
        {
            var fabricClient = new FabricClient();
            var deleteTasks  = new List <Task>();

            // Find all partitions for the device simulator actor application
            foreach (var partition in await fabricClient.QueryManager.GetPartitionListAsync(deviceActorApplicationUri))
            {
                var partitionInformation = ((Int64RangePartitionInformation)partition.PartitionInformation);

                // Get the rangs of possible partition key values in the partition
                var partitionKeyRange = CreateLongRange(partitionInformation.LowKey, partitionInformation.HighKey);

                foreach (var partitionKey in partitionKeyRange)
                {
                    // Get the actor service for this particular partition key
                    var actorService = ActorServiceProxy.Create(deviceActorApplicationUri, partitionKey);

                    var pagedResult = default(PagedResult <ActorInformation>);

                    // Page through all the actors in this partition and delete them concurrently
                    do
                    {
                        pagedResult = await actorService.GetActorsAsync(pagedResult?.ContinuationToken, CancellationToken.None);

                        foreach (var actorInformation in pagedResult.Items)
                        {
                            deleteTasks.Add(actorService.DeleteActorAsync(actorInformation.ActorId, CancellationToken.None));
                        }

                        // Wait for the actors in this page to be deleted
                        await Task.WhenAll(deleteTasks);
                    }while (pagedResult.ContinuationToken != null);
                }

                deleteTasks.Clear();
            }

            IEnumerable <long> CreateLongRange(long start, long end)
            {
                for (var i = start; i <= end; i++)
                {
                    yield return(i);
                }
            }
        }
Пример #21
0
        private async Task <string> GetRandomIdsAsync()
        {
            ServiceUriBuilder serviceUri = new ServiceUriBuilder(this.GetSetting("BandActorServiceInstanceName"));
            Uri fabricServiceName        = serviceUri.ToUri();

            CancellationTokenSource cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));

            CancellationToken token = cts.Token;

            FabricClient         fc         = new FabricClient();
            ServicePartitionList partitions = await fc.QueryManager.GetPartitionListAsync(fabricServiceName);

            ActorId bandActorId = null;

            try
            {
                while (!token.IsCancellationRequested && bandActorId == null)
                {
                    foreach (Partition p in partitions)
                    {
                        long partitionKey = ((Int64RangePartitionInformation)p.PartitionInformation).LowKey;
                        token.ThrowIfCancellationRequested();
                        ContinuationToken queryContinuationToken = null;
                        IActorService     proxy = ActorServiceProxy.Create(fabricServiceName, partitionKey);
                        PagedResult <ActorInformation> result = await proxy.GetActorsAsync(queryContinuationToken, token);

                        foreach (ActorInformation info in result.Items)
                        {
                            bandActorId = info.ActorId;
                            break;
                        }
                        //otherwise we will bounce around other partitions until we find an actor
                    }
                }

                IBandActor        bandActor = ActorProxy.Create <IBandActor>(bandActorId, fabricServiceName);
                BandDataViewModel data      = await bandActor.GetBandDataAsync();

                return(string.Format("{0}|{1}", bandActorId, data.DoctorId));
            }
            catch
            {
                //no actors found within timeout
                throw;
            }
        }
        private async Task DestroyValidationDPActorAsync(IValidationDPActor validationDPActor, CancellationToken cancellationToken)
        {
            try
            {
                ActorId actorId = validationDPActor.GetActorId();

                IActorService myActorServiceProxy = ActorServiceProxy.Create(
                    new Uri($"{FabricRuntime.GetActivationContext().ApplicationName}/ValidationActorService"),
                    actorId);

                await myActorServiceProxy.DeleteActorAsync(actorId, cancellationToken);
            }
            catch (Exception ex)
            {
                _logger.LogError("Problem deleting actor", ex);
            }
        }
Пример #23
0
        private async Task DestroyActorSync <T>(T actor, string serviceName, CancellationToken cancellationToken)
            where T : IActor
        {
            try
            {
                ActorId actorId = actor.GetActorId();

                IActorService myActorServiceProxy = ActorServiceProxy.Create(
                    new Uri($"{FabricRuntime.GetActivationContext().ApplicationName}/{serviceName}"),
                    actorId);

                await myActorServiceProxy.DeleteActorAsync(actorId, cancellationToken);
            }
            catch (Exception ex)
            {
                _logger.LogError("Problem deleting actor", ex);
            }
        }
Пример #24
0
        public async Task <List <car> > GetInventory()
        {
            List <car> list = new List <car>();

            IActorService actorServiceProxy = ActorServiceProxy.Create(new Uri("fabric:/SfWebAppDemo/CarActorService"), 1);

            ContinuationToken continuationToken = null;
            CancellationToken cancellationToken;
            List <ActorId>    actorIds = new List <ActorId>();

            do
            {
                PagedResult <ActorInformation> page = await actorServiceProxy.GetActorsAsync(continuationToken, cancellationToken);

                foreach (ActorInformation info in page.Items)
                {
                    actorIds.Add(info.ActorId);
                }
                continuationToken = page.ContinuationToken;
            }while (continuationToken != null);

            actorIds.ForEach((id) => {
                ICarActor carproxy = ActorProxy.Create <ICarActor>(id, new Uri("fabric:/SfWebAppDemo/CarActorService"));
                Task <string> t1   = carproxy.GetBrandAsync();
                Task <string> t2   = carproxy.GetModelAsync();
                Task <int> t3      = carproxy.GetYearAsync();
                Task <string> t4   = carproxy.GetColorAsync();
                Task.WaitAll(t1, t2, t3, t4);
                if (t1.IsCompleted && t2.IsCompleted && t3.IsCompleted && t4.IsCompleted)
                {
                    car car = new car()
                    {
                        brand = t1.Result, model = t2.Result, year = t3.Result, color = t4.Result
                    };
                    list.Add(car);
                }
                else
                {
                    // error
                }
            });

            return(list);
        }
Пример #25
0
 /// <summary>
 /// Schedule a task on the thread pool to delete the actor if-self. Override if needed
 /// </summary>
 /// <param name="cancellationToken"></param>
 protected virtual void DisposeSelf(CancellationToken cancellationToken)
 {
     try
     {
         var serviceUri = ActorService.Context.ServiceName;
         var actorId    = Id.ToString();
         Task.Run(async() =>
         {
             var deletingActorId = new ActorId(actorId);
             var serviceProxy    = ActorServiceProxy.Create(serviceUri, deletingActorId);
             await serviceProxy.DeleteActorAsync
                 (deletingActorId, cancellationToken);
         }, cancellationToken);
     }
     catch (Exception ex)
     {
         Logger.LogError(ex, $"[{CurrentActor}-DisposeSelf] Failed to dispose: " + ex.Message);
     }
 }
Пример #26
0
        public async Task <IActionResult> Get()
        {
            var activeActors      = new List <ActorData>();
            int partitioncount    = 0;
            var cancellationToken = new CancellationTokenSource();

            using (var fabricClient = new FabricClient())
            {
                var partitionList = await fabricClient.QueryManager.GetPartitionListAsync(new Uri("fabric:/IotDemoApp/IoTDeviceActorService"));

                partitioncount = partitionList.Count;
                var actorIds = new List <ulong>();

                foreach (var partition in partitionList)
                {
                    var key = partition.PartitionInformation as Int64RangePartitionInformation;
                    var actorServiceProxy = ActorServiceProxy.Create(new Uri("fabric:/IotDemoApp/IoTDeviceActorService"), key.LowKey);

                    ContinuationToken continuationToken = null;

                    do
                    {
                        var page = await actorServiceProxy.GetActorsAsync(continuationToken, cancellationToken.Token);

                        activeActors.AddRange(page.Items.Select(a => new ActorData {
                            Actor = a, Partition = key.LowKey
                        }));
                        continuationToken = page.ContinuationToken;
                    } while (continuationToken != null);
                }
            }

            foreach (var actor in activeActors)
            {
                var theActor = ActorProxy.Create <IIoTDeviceActor>(actor.Actor.ActorId, new Uri("fabric:/IotDemoApp/IoTDeviceActorService"));
                actor.LastMessage = await theActor.GetLastDeviceMessage(cancellationToken.Token);

                actor.NumberOfMessages = await theActor.GetNumberOfMessages(cancellationToken.Token);
            }

            return(Json(new { PartitionCount = partitioncount, ActorCount = activeActors.Count(), Actors = activeActors.OrderBy(a => a.Actor.ActorId) }));
        }
        public async Task OnGetAsync()
        {
            var builder = new ServiceUriBuilder("SampleActorService");
            var actorId = new ActorId(1);

            var actorService = ActorServiceProxy.Create <IActorServiceEx>(builder.ToUri(), actorId);

            try
            {
                var exists = await actorService.ActorExistsAsync(actorId);

                var actor = ActorProxy.Create <ISampleActor>(actorId, builder.ToUri());
                Count = await actor.GetCountAsync(default(CancellationToken));
            }
            catch (Exception ex)
            {
                Trace.TraceError(ex.ToString());
            }

            Message = "Your application description page.";
        }
Пример #28
0
        private async void button2_Click(object sender, EventArgs e)
        {
            using (var client = new FabricClient())
            {
                var serviceName = new Uri(url2);
                var partitions  = await client.QueryManager.GetPartitionListAsync(serviceName);

                List <string> patitionInfo = new List <string>();

                foreach (var partition in partitions)
                {
                    //Debug.Assert(partition.PartitionInformation.Kind == ServicePartitionKind.Int64Range);
                    var partitionInformation = (Int64RangePartitionInformation)partition.PartitionInformation;
                    //var proxy = ServiceProxy.Create<IActor1>(serviceName, new ServicePartitionKey(partitionInformation.LowKey));
                    var actorServiceProxy = ActorServiceProxy.Create(new Uri(url2), partitionInformation.LowKey);

                    ContinuationToken continuationToken = null;

                    do
                    {
                        PagedResult <ActorInformation> page = await actorServiceProxy.GetActorsAsync(continuationToken, CancellationToken.None);

                        foreach (var actor in page.Items)
                        {
                            var msg = $"P: {partitionInformation.LowKey} - {actor.ActorId} - {actor.IsActive}";
                            //Console.WriteLine(msg);
                            patitionInfo.Add(msg);
                        }

                        //activeActors.AddRange(page.Items.Where(x => x.IsActive));

                        continuationToken = page.ContinuationToken;
                    }while (continuationToken != null);
                }

                this.textBox2.Lines = patitionInfo.ToArray();
            }
        }
Пример #29
0
        public static IEnumerable <Vehicle> GetVehicles()
        {
            ContinuationToken continuationToken = null;
            var vehicles          = new List <Vehicle>();
            var actorServiceProxy = ActorServiceProxy.Create(new Uri("fabric:/CarActorSF/CarActorService"), 0);
            var queriedActorCount = 0;

            do
            {
                var queryResult = actorServiceProxy.GetActorsAsync(continuationToken, CancellationToken.None).GetAwaiter().GetResult();
                foreach (var actorInformation in queryResult.Items)
                {
                    //var proxy = GetActorProxy(actorInformation.ActorId);
                    //vehicles.Add(await proxy.Get());
                    vehicles.Add(new Vehicle {
                        VehicleId = actorInformation.ActorId.GetStringId().Substring(13)
                    });
                }
                queriedActorCount += queryResult.Items.Count();
                continuationToken  = queryResult.ContinuationToken;
            } while (continuationToken != null);
            return(vehicles);
        }
Пример #30
0
        public async Task <List <ActorInformation> > ActorGetAll()
        {
            List <ActorInformation> activeActors = new List <ActorInformation>();
            var client     = new FabricClient();
            var partitions = await client.QueryManager.GetPartitionListAsync(new Uri("fabric:/TK_2016MainSFFunctions/TKActorService"));

            foreach (var partition in partitions)
            {
                IActorService actorServiceProxy = ActorServiceProxy.Create(
                    new Uri("fabric:/TK_2016MainSFFunctions/TKActorService"), ((Int64RangePartitionInformation)partition.PartitionInformation).LowKey);

                ContinuationToken continuationToken = null;

                do
                {
                    PagedResult <ActorInformation> page = await actorServiceProxy.GetActorsAsync(continuationToken, new System.Threading.CancellationToken());

                    activeActors.AddRange(page.Items /*.Where(x => x.IsActive)*/);
                    continuationToken = page.ContinuationToken;
                }while (continuationToken != null);
            }
            return(activeActors);
        }