Ejemplo n.º 1
0
        public async Task <string> TKStatelessSet(int partition, string name, int value)
        {
            var          start = DateTime.Now;
            ITKStateless proxy = null;

            //For single partitions
            if (partition == -1)
            {
                proxy = ServiceProxy.Create <ITKStateless>(new Uri("fabric:/TK_2016MainSFFunctions/TKStateless")
                                                           );
            }
            else
            {
                proxy = ServiceProxy.Create <ITKStateless>(new Uri("fabric:/TK_2016MainSFFunctions/TKStateless")
                                                           , new Microsoft.ServiceFabric.Services.Client.ServicePartitionKey(partition));
            }
            var v = await proxy.SetAsync(name, value);

            var stop = DateTime.Now;

            return($"Partition: {partition}, {(DateTime.Now - start).TotalMilliseconds}, {v}");
        }
Ejemplo n.º 2
0
        public async Task <string> Get()
        {
            //We need to provide two sets of info to the service proxy. The name of the service as registered
            //wit SF and the partition key, which is set to 0 currently because we only have one partition.
            //partitioning info found here https://docs.microsoft.com/en-us/azure/service-fabric/service-fabric-concepts-partitioning
            ISnowProvider snow =
                ServiceProxy.Create <ISnowProvider>(new Uri("fabric:/GoodVibesSurfing/GetSnowConditions"),
                                                    new ServicePartitionKey(0));

            try
            {
                var taskResult = await RetryPattern.DoTaskWithRetry(snow.GetSnowConditionsAsync);

                //due to some nested task garbaggio we're going to wait for this again. The reason is that our delegate is running a task
                //which runs a task... so the await for some reason isn't sufficient
                taskResult.Wait();

                var conditions = taskResult.Result;
                //Dictionary<string, long> conditions = await snow.GetSnowConditionsAsync();
                return(JsonConvert.SerializeObject(conditions));
            }
            catch (AggregateException ex)
            {
                if (ex.InnerExceptions.Any(x => x is TimeoutException) || ex.GetBaseException() is TimeoutException)
                {
                    //need to tell the user that we timed out after retry
                }
            }
            catch (Exception ex)
            {
                if (ex is TimeoutException || ex.InnerException is TimeoutException)
                {
                    //implement retry pattern
                }
            }

            throw new ApplicationException();
        }
Ejemplo n.º 3
0
        public async Task <IActionResult> Get()
        {
            try
            {
                string serviceUri = $"{this.serviceContext.CodePackageActivationContext.ApplicationName}/{this.configSettings.RequestsServiceName}";

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

                if (partitions == null || partitions.Count == 0)
                {
                    return(new ContentResult {
                        StatusCode = 404, Content = "There's no available replica. Please check service status."
                    });
                }

                ServicePartitionKey key = new ServicePartitionKey(((Int64RangePartitionInformation)(partitions[0].PartitionInformation)).LowKey);

                IRequestManager service = ServiceProxy.Create <IRequestManager>(new Uri(serviceUri), key);

                await service.Matchmake(new CancellationToken());

                ServiceEventSource.Current.Message($"Matchmaked performed!");

                return(this.Ok());
            }
            catch (FabricNotPrimaryException)
            {
                return(new ContentResult {
                    StatusCode = 410, Content = "The primary replica has moved. Please re-resolve the service."
                });
            }
            catch (/*FabricException*/ Exception e)
            {
                return(new ContentResult {
                    StatusCode = 503, Content = $"The service was unable to process the request. Please try again. Exception: {e}"
                });
            }
        }
        private async Task RegisterGatewayServiceAsync(string backAddress, GatewayOptions gw)
        {
            // IGatewayServiceManagerActor gateway = ActorProxy.Create<IGatewayServiceManagerActor>(new ActorId("*"), "S-Innovations.ServiceFabric.GatewayApplication", "GatewayServiceManagerActorService");
            var partitionKey = gw.Key ?? Context.CodePackageActivationContext.GetServiceManifestName();

            var gateway = ServiceProxy.Create <IGatewayManagementService>(
                new Uri("fabric:/S-Innovations.ServiceFabric.GatewayApplication/GatewayManagementService"), partitionKey.ToPartitionHashFunction());


            await gateway.RegisterGatewayServiceAsync(new GatewayServiceRegistrationData
            {
                Key                  = partitionKey, // $"{partitionKey}-{Context.NodeContext.IPAddressOrFQDN}",
                IPAddressOrFQDN      = Context.NodeContext.IPAddressOrFQDN,
                ServerName           = gw.ServerName,
                ReverseProxyLocation = gw.ReverseProxyLocation ?? "/",
                Ssl                  = gw.Ssl,
                BackendPath          = backAddress,
                ServiceName          = Context.ServiceName,
                ServiceVersion       = Context.CodePackageActivationContext.GetServiceManifestVersion(),
                CacheOptions         = gw.CacheOptions,
                Properties           = gw.Properties
            });
        }
Ejemplo n.º 5
0
        public override async Task Dispatch(Event @event)
        {
            List <QueryModelBuilder> handlers;

            if (_handlers.TryGetValue(@event.GetType(), out handlers))
            {
                await Task.WhenAll(
                    handlers.Select(b =>
                {
                    var builderType = b.GetType();
                    var queryModelBuilderService = ServiceProxy.Create <IQueryModelBuilderService>(
                        $"{builderType.FullName}, {builderType.Assembly.GetName().Name}",
                        new Uri("fabric:/CQRSMicroservices.ServiceFabric.Application/QueryModelBuilderService"
                                ));
                    return(queryModelBuilderService.Handle(@event.ToJson()));
                })
                    );
            }
            else
            {
                throw new NotImplementedException($"No handler for eventtype {@event.GetType().FullName}");
            }
        }
Ejemplo n.º 6
0
        public async Task <IHttpActionResult> Get()
        {
            ServiceUriBuilder builder        = new ServiceUriBuilder("ClusterService");
            IClusterService   clusterService = ServiceProxy.Create <IClusterService>(builder.ToUri(), new ServicePartitionKey(1));

            IEnumerable <ClusterView> clusters = await clusterService.GetClusterListAsync();

            return(this.Ok(
                       clusters.Select(
                           x => new
            {
                ClusterId = x.ClusterId,
                Name = this.GetClusterName(x.ClusterId),
                ApplicationCount = x.ApplicationCount,
                ServiceCount = x.ServiceCount,
                Capacity = this.GetUserCapacity(x.UserCount, x.MaxUsers),
                UserCount = x.UserCount,
                MaxUsers = x.MaxUsers,
                TimeRemaining = x.TimeRemaining > TimeSpan.Zero
                            ? String.Format("{0:hh\\:mm\\:ss}", x.TimeRemaining)
                            : "expired"
            })));
        }
Ejemplo n.º 7
0
        // POST api/analysis
        public async Task <HttpResponseMessage> Post()
        {
            //string partitionKey = Guid.NewGuid().ToString();
            Random ram          = new Random();
            int    partitionKey = ram.Next();

            byte[] image = await Request.Content.ReadAsByteArrayAsync();

            IYasudaAnalysis analysis = ServiceProxy.Create <IYasudaAnalysis>(
                new Uri("fabric:/Services/YasudaAnalysis"),
                new ServicePartitionKey(partitionKey));
            await analysis.StartAnalysis(partitionKey, image);

            var bodystr  = @"{""TaskId"":""" + partitionKey + @"""}";
            var bodycont = new StringContent(bodystr);

            bodycont.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            var resp = new HttpResponseMessage();

            resp.Content = bodycont;
            //resp.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            return(resp);
        }
Ejemplo n.º 8
0
        //Тест. Nunit вылетает, возможно плохо взаимодействует с fabric service
        private static void Main(string[] args)
        {
            var passport = new Passport()
            {
                Address          = "Звездная",
                Birthday         = new DateTime(1980, 4, 3),
                Firstname        = "Дарт",
                IssuedBy         = "Космос",
                IssuedDepartment = "Космический Альянс",
                IssuedOn         = new DateTime(1980, 4, 3),
                Lastname         = "Вейдер",
                Number           = "01",
                Secondname       = "",
                Series           = "01",
                Sex = SexType.Male
            };

            var calculatorClient = ServiceProxy.Create <IDataService>(new Uri("fabric:/DataServiceApplication/DataService"));

            calculatorClient.SavePassportAsync(passport).Wait();

            Console.WriteLine("No exceptions");
        }
        public async Task UpdateMultipleTimes()
        {
            ServicePartitionKey partitionKey;

            using (var client = new FabricClient())
            {
                var partitions = await client.QueryManager.GetPartitionListAsync(SetupApp.TestKeyValueStatefulUri);

                var partition = (Int64RangePartitionInformation)partitions.First().PartitionInformation;
                partitionKey = new ServicePartitionKey(partition.LowKey);

                while (true)
                {
                    var replicas = await client.QueryManager.GetReplicaListAsync(partition.Id).ConfigureAwait(false);

                    if (replicas.Count == 3 && replicas.All(r => r.HealthState == HealthState.Ok))
                    {
                        break;
                    }

                    await Task.Delay(TimeSpan.FromSeconds(1));
                }
            }

            var service = ServiceProxy.Create <ITestKeyValueStateful>(SetupApp.TestKeyValueStatefulUri, partitionKey);

            var spans = new List <TimeSpan>();

            for (var i = 0; i < 1000; i++)
            {
                spans.Add(await service.UpdateValue());
            }

            spans.Sort();
            Console.WriteLine($"Min time: {spans.First()}");
            Console.WriteLine($"Max time: {spans.Last()}");
        }
        public void ConfigureService([FromBody] JObject content, string primaryClusterAddress, string primaryHttpEndpointEncoded, string primaryThumbprint, string primaryCommonName,
                                     string secondaryClusterAddress, string secondaryHttpEndpointEncoded, string secondaryThumbprint, string secondaryCommonName)
        {
            string[] primaryClusterDetails   = primaryClusterAddress.Split(':');
            string[] secondaryClusterDetails = secondaryClusterAddress.Split(':');

            string primaryHttpEndpoint   = Utility.decodeHTTPString(primaryHttpEndpointEncoded);
            string secondaryHttpEndpoint = Utility.decodeHTTPString(secondaryHttpEndpointEncoded);

            ClusterDetails primaryCluster   = new ClusterDetails(primaryClusterDetails[0], primaryHttpEndpoint, primaryClusterAddress, primaryThumbprint, primaryCommonName);
            ClusterDetails secondaryCluster = new ClusterDetails(secondaryClusterDetails[0], secondaryHttpEndpoint, secondaryClusterAddress, secondaryThumbprint, secondaryCommonName);

            JArray serviceData  = (JArray)content["ServiceList"];
            JArray policiesData = (JArray)content["PoliciesList"];

            List <string> serviceDataObj             = JsonConvert.DeserializeObject <List <string> >(serviceData.ToString());
            List <PolicyStorageEntity> policicesList = JsonConvert.DeserializeObject <List <PolicyStorageEntity> >(policiesData.ToString());

            FabricClient         fabricClient  = new FabricClient();
            ServicePartitionList partitionList = fabricClient.QueryManager.GetPartitionListAsync(new Uri("fabric:/SFAppDRTool/RestoreService")).Result;

            foreach (Partition partition in partitionList)
            {
                var             int64PartitionInfo   = partition.PartitionInformation as Int64RangePartitionInformation;
                long            lowKey               = (long)int64PartitionInfo?.LowKey;
                IRestoreService restoreServiceClient = ServiceProxy.Create <IRestoreService>(new Uri("fabric:/SFAppDRTool/RestoreService"), new ServicePartitionKey(lowKey));
                try
                {
                    restoreServiceClient.ConfigureService(serviceDataObj[0], serviceDataObj[1], policicesList, primaryCluster, secondaryCluster);
                }
                catch (Exception ex)
                {
                    ServiceEventSource.Current.Message("Web Service: Exception configuring the service {0}", ex);
                    throw;
                }
            }
        }
Ejemplo n.º 11
0
        public Task Invoke(IDictionary <string, object> environment)
        {
            try
            {
                var    counterServiceProxy = ServiceProxy.Create <ICounterService>(new Uri("fabric:/CounterServiceApplication/CounterService"), new ServicePartitionKey(1));
                long   result        = counterServiceProxy.GetValueAsync().Result;
                string responseText  = "The value of counter is : " + result;
                byte[] responseBytes = Encoding.UTF8.GetBytes(responseText);

                // See http://owin.org/spec/owin-1.0.0.html for standard environment keys.
                var responseStream  = (Stream)environment["owin.ResponseBody"];
                var responseHeaders = (IDictionary <string, string[]>)environment["owin.ResponseHeaders"];

                responseHeaders["Content-Length"] = new string[] { responseBytes.Length.ToString(CultureInfo.InvariantCulture) };
                responseHeaders["Content-Type"]   = new string[] { "text/plain" };

                return(responseStream.WriteAsync(responseBytes, 0, responseBytes.Length));
            }
            catch (Exception Ex)
            {
                ServiceEventSource.Current.Message("Invoke failed with Exception: {0}", Ex);
                throw;
            }
        }
Ejemplo n.º 12
0
        internal static async Task <IGatewayMonitor> GetGatewaySupervisorServiceAsync(string nodeId, bool createIfnotExist)
        {
            var appName              = "fabric:/DeviceMonitorApp";
            var serviceName          = $"{appName}/{nodeId}";
            var fabricClient         = new FabricClient();
            var serviceAlreadyExists = false;

            try
            {
                var services = await fabricClient.QueryManager.GetServiceListAsync(new Uri(appName));

                serviceAlreadyExists = services.Select(s => s.ServiceName).Contains(new Uri(serviceName));
            }
            catch (FabricElementNotFoundException) { }

            if (!serviceAlreadyExists && createIfnotExist)
            {
                StatefulServiceDescription serviceDescription = new StatefulServiceDescription();
                serviceDescription.ApplicationName            = new Uri(appName);
                serviceDescription.PartitionSchemeDescription = new SingletonPartitionSchemeDescription();
                serviceDescription.ServiceName          = new Uri(serviceName);
                serviceDescription.ServiceTypeName      = "GatewayMonitorServiceType";
                serviceDescription.HasPersistedState    = true;
                serviceDescription.MinReplicaSetSize    = 3;
                serviceDescription.TargetReplicaSetSize = 3;
                await fabricClient.ServiceManager.CreateServiceAsync(serviceDescription);

                //TODO:Call GetService and then get partition instead of delay
                await Task.Delay(TimeSpan.FromSeconds(30));
            }
            else if (!serviceAlreadyExists)
            {
                throw new  ArgumentException("Invalid Arguments");
            }
            return(ServiceProxy.Create <IGatewayMonitor>(new Uri(serviceName)));
        }
        /// <summary>
        /// Drains the queue of completed restock requests sends them to InventoryService.
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        protected override async Task RunAsync(CancellationToken cancellationToken)
        {
            IReliableQueue <RestockRequest> completedRequests = await this.StateManager.GetOrAddAsync <IReliableQueue <RestockRequest> >(CompletedRequestsQueueName);

            while (!cancellationToken.IsCancellationRequested)
            {
                using (ITransaction tx = this.StateManager.CreateTransaction())
                {
                    ConditionalValue <RestockRequest> result = await completedRequests.TryDequeueAsync(tx, TxTimeout, cancellationToken);

                    if (result.HasValue)
                    {
                        ServiceUriBuilder builder          = new ServiceUriBuilder(InventoryServiceName);
                        IInventoryService inventoryService = ServiceProxy.Create <IInventoryService>(builder.ToUri(), result.Value.ItemId.GetPartitionKey());

                        await inventoryService.AddStockAsync(result.Value.ItemId, result.Value.Quantity);

                        ServiceEventSource.Current.ServiceMessage(
                            this,
                            "Adding stock to inventory service. ID: {0}. Quantity: {1}",
                            result.Value.ItemId,
                            result.Value.Quantity);
                    }

                    // This commits the dequeue operations.
                    // If the request to add the stock to the inventory service throws, this commit will not execute
                    // and the items will remain on the queue, so we can be sure that we didn't dequeue items
                    // that didn't get saved successfully in the inventory service.
                    // However there is a very small chance that the stock was added to the inventory service successfully,
                    // but service execution stopped before reaching this commit (machine crash, for example).
                    await tx.CommitAsync();
                }

                await Task.Delay(CompletedRequestsBatchInterval, cancellationToken);
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// This is the main entry point for your service instance.
        /// </summary>
        /// <param name="cancellationToken">Canceled when Service Fabric needs to shut down this service instance.</param>
        protected override async Task RunAsync(CancellationToken cancellationToken)
        {
            //await Task.Delay(TimeSpan.FromSeconds(45));

            var dataSource = ServiceProxy.Create <IQueue>(new Uri("fabric:/ElasticScaleDemo/DataSource"), new ServicePartitionKey(0));

            while (true)
            {
                cancellationToken.ThrowIfCancellationRequested();

                try
                {
                    var item = await dataSource.DequeueAsync();

                    ServiceEventSource.Current.Message("Dequeued: {item}");
                }
                catch (QueueEmptyException queueException)
                {
                    // no op
                }

                await Task.Delay(TimeSpan.FromSeconds(_timeToWorkInSeconds));
            }
        }
Ejemplo n.º 15
0
        public async Task <IEnumerable <InventoryItemView> > GetStore()
        {
            ServiceUriBuilder builder = new ServiceUriBuilder(InventoryServiceName);
            Uri serviceName           = builder.ToUri();

            List <InventoryItemView> itemList = new List <InventoryItemView>();

            ServicePartitionList partitions = await fc.QueryManager.GetPartitionListAsync(serviceName);

            foreach (Partition p in partitions)
            {
                long minKey = (p.PartitionInformation as Int64RangePartitionInformation).LowKey;
                IInventoryService inventoryServiceClient = ServiceProxy.Create <IInventoryService>(serviceName, new ServicePartitionKey(minKey));

                IEnumerable <InventoryItemView> result = await inventoryServiceClient.GetCustomerInventoryAsync(CancellationToken.None);

                if (result != null)
                {
                    itemList.AddRange(result);
                }
            }

            return(itemList);
        }
        /// <summary>
        /// Updates Windows Update Operation Result
        /// </summary>
        /// <param name="fabricClient">fabric client to carry out operations on service fabric</param>
        /// <param name="applicationUri">Application name of the Patch Orchestration Application</param>
        /// <param name="operationResult">Result of Windows Update operation <see cref="WindowsUpdateOperationResult"/></param>
        /// <param name="timeout">Timeout for the operation</param>
        /// <param name="cancellationToken">Cancellation token to cancel this async operation</param>
        /// <returns>A Task representing the asnyc operation, result of the task would be <see cref="NodeAgentSfUtilityExitCodes"/></returns>
        internal static async Task <NodeAgentSfUtilityExitCodes> UpdateWuOperationResult(
            FabricClient fabricClient,
            Uri applicationUri,
            WindowsUpdateOperationResult operationResult,
            TimeSpan timeout,
            CancellationToken cancellationToken)
        {
            try
            {
                IDataInterface coordinatorServiceDataClient = ServiceProxy.Create <IDataInterface>(new Uri(applicationUri + CoordinatorServiceSuffix));
                await
                coordinatorServiceDataClient.UpdateWuOperationResult(
                    operationResult,
                    timeout,
                    cancellationToken);

                return(NodeAgentSfUtilityExitCodes.Success);
            }
            catch (Exception e)
            {
                ServiceEventSource.Current.ErrorMessage(
                    String.Format("CoordinatorServiceHelper.UpdateWuOperationResult failed. Exception details {0}", e));
                if (e is FabricTransientException)
                {
                    return(NodeAgentSfUtilityExitCodes.RetryableException);
                }
                else if (e is FabricServiceNotFoundException)
                {
                    return(NodeAgentSfUtilityExitCodes.ServiceNotFound);
                }
                else
                {
                    return(NodeAgentSfUtilityExitCodes.Failure);
                }
            }
        }
        public async Task <string> DisconfigureService([FromBody] JObject content, String primaryCluster, String secondaryCluster)
        {
            bool successfullyRemoved = true;

            JArray        serviceData    = (JArray)content["ServiceList"];
            List <string> serviceDataObj = JsonConvert.DeserializeObject <List <string> >(serviceData.ToString());

            FabricClient         fabricClient  = new FabricClient();
            ServicePartitionList partitionList = fabricClient.QueryManager.GetPartitionListAsync(new Uri("fabric:/SFAppDRTool/RestoreService")).Result;

            foreach (Partition partition in partitionList)
            {
                var             int64PartitionInfo   = partition.PartitionInformation as Int64RangePartitionInformation;
                long            lowKey               = (long)int64PartitionInfo?.LowKey;
                IRestoreService restoreServiceClient = ServiceProxy.Create <IRestoreService>(new Uri("fabric:/SFAppDRTool/RestoreService"), new ServicePartitionKey(lowKey));
                try
                {
                    string serviceRemoved = await restoreServiceClient.DisconfigureService(serviceDataObj[0], primaryCluster, secondaryCluster);

                    if (serviceRemoved == null)
                    {
                        successfullyRemoved = false;
                    }
                }
                catch (Exception ex)
                {
                    ServiceEventSource.Current.Message("Web Service: Exception Disconfiguring Service {0}", ex);
                    throw;
                }
            }
            if (successfullyRemoved)
            {
                return(serviceDataObj[0]);
            }
            return(null);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// This is the main entry point for your service instance.
        /// </summary>
        /// <param name="cancellationToken">Canceled when Service Fabric needs to shut down this service instance.</param>
        protected override async Task RunAsync(CancellationToken cancellationToken)
        {
            long iterations = 0;

            //connection string for the queue
            var connectionString = "Endpoint=sb://themayor.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=<keyname>";
            var queueName        = "hackprocessdemo";

            var    client   = QueueClient.CreateFromConnectionString(connectionString, queueName);
            string nodeip   = this.Context.NodeContext.IPAddressOrFQDN;
            string nodename = this.Context.NodeContext.NodeName;

            //using an event message listener
            client.OnMessage(message =>
            {
                var bodyText = message.GetBody <string>();
                var msgId    = message.MessageId;

                bodyText       = "SF: " + nodeip + " - Nodename: " + nodename + " --- " + bodyText;
                var queuestore = ServiceProxy.Create <queueItemStorageSrv.IQueueStore>(new Uri("fabric:/queueworkerStateless/queueItemStorageSrv"),
                                                                                       new Microsoft.ServiceFabric.Services.Client.ServicePartitionKey(1));
                var successful = queuestore.SetQueueInformation(bodyText);
                if (successful.Result)
                {
                    ServiceEventSource.Current.ServiceMessage(this.Context, "{0} added message to storage", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                }
            });


            while (true)
            {
                cancellationToken.ThrowIfCancellationRequested();
                ServiceEventSource.Current.ServiceMessage(this.Context, "Working-{0} iteration-{1}", nodename, iterations);
                await Task.Delay(TimeSpan.FromSeconds(10), cancellationToken);
            }
        }
        static void TestMisc()
        {
            var proxy = ActorProxy.Create <IKing>(new ActorId("1"), "fabric:/MessyChessApplication", "King");

            proxy.SetInfoAsync(new ChessPieceInfo {
                ActorId = "1", PieceType = ChessPieceType.King, Team = 1, X = 1, Y = 1
            }).Wait();
            var king = proxy.GetInfoAsync().Result;

            Console.WriteLine(king.PieceType);

            Console.ReadLine();

            Random rand = new Random();

            while (true)
            {
                int x = 0;
                int y = 0;
                while (x < 8 && y < 8 || x >= 16 && y < 8 ||
                       x < 8 && y >= 16 || x >= 16 && y >= 16)
                {
                    x = rand.Next(0, 24);
                    y = rand.Next(0, 24);
                }
                string      partition  = ((y / 4) * 6 + (x / 4) + 1).ToString();
                IChessboard boardShard = ServiceProxy.Create <IChessboard>(new Uri("fabric:/MessyChessApplication/Chessboard"), new ServicePartitionKey(partition));
                boardShard.PutAPieceAsync(new ChessPieceInfo {
                    ActorId = "1", PieceType = ChessPieceType.King, Team = rand.Next(1, 5), X = x, Y = y
                }).Wait();
                IChessboardObserver board = ServiceProxy.Create <IChessboardObserver>(new Uri("fabric:/MessyChessApplication/ChessboardObserver"));
                var boardInfo             = board.GetBoard(new CancellationToken()).Result;
                PaintBoard(boardInfo);
                Thread.Sleep(10);
            }
        }
        public async Task <Job> NewJob(int time)
        {
            var j = new Job()
            {
                NodeName = "",
                Id       = Guid.NewGuid().ToString(),
                Status   = JobStatus.Waiting,
                InitData = time.ToString()
            };

            lock (jobs)
            {
                jobs.AddOrUpdate(j.Id, j, (o, n) => j);
            }

            var key = Fnv1aHashCode.Get64bitHashCode(j.Id);

            IJobWorker proxy = ServiceProxy.Create <IJobWorker>(new Uri("fabric:/Compute2/PartitionedComputeService"),
                                                                new ServicePartitionKey(key));

            proxy.Execute(j).ConfigureAwait(false);

            return(j);
        }
Ejemplo n.º 21
0
 public TServiceInterface Create <TServiceInterface>(string partitionKey, Uri serviceName) where TServiceInterface : IService
 {
     return(ServiceProxy.Create <TServiceInterface>(serviceName, new Microsoft.ServiceFabric.Services.Client.ServicePartitionKey(partitionKey)));
 }
Ejemplo n.º 22
0
 public IGiftProcessingService Create()
 {
     return(ServiceProxy.Create <IGiftProcessingService>(FabricUri, new ServicePartitionKey(1)));
 }
Ejemplo n.º 23
0
 public TServiceInterface Create <TServiceInterface>(Uri serviceName) where TServiceInterface : IService
 {
     return(ServiceProxy.Create <TServiceInterface>(serviceName, new Microsoft.ServiceFabric.Services.Client.ServicePartitionKey(GetNextInt64Simple())));
 }
Ejemplo n.º 24
0
        /// <summary>
        /// Gets the proxy.
        /// </summary>
        /// <param name="region">The region.</param>
        /// <param name="key">The key.</param>
        /// <returns></returns>
        private IDistribuitedCache GetProxy(string region, string key = null)
        {
            var partitionKey = CalculatePartitionKey(region, key, this.numberOfPartitions);

            return(ServiceProxy.Create <IDistribuitedCache>(this.serviceUri, partitionKey));
        }
 private IProductCatalogService GetProductCatalogService()
 {
     return(ServiceProxy.Create <IProductCatalogService>(
                new Uri("fabric:/ECommerce/ECommerce.ProductCatalog"),
                new ServicePartitionKey(0)));
 }
Ejemplo n.º 26
0
 public ProductController()
 {
     _catalogService = ServiceProxy.Create <IProductCatalogService>(
         new Uri("fabric:/ECommerce/ECommerce.ProductCatalog"),
         new ServicePartitionKey(0));
 }
Ejemplo n.º 27
0
 public UsersController()
 {
     this._userService = ServiceProxy.Create <IUserService>(
         new Uri($"{ FabricRuntime.GetActivationContext().ApplicationName }/Blissmo.UserService"),
         new ServicePartitionKey(0));
 }
Ejemplo n.º 28
0
 public ProductsController()
 {
     this.productCatalogService = ServiceProxy.Create <IProductCatalogService>(
         new Uri("fabric:/ECommerce/ECommerce.ProductCatalog"),
         new Microsoft.ServiceFabric.Services.Client.ServicePartitionKey(0));
 }
Ejemplo n.º 29
0
 public OnlineForm(StatefulServiceContext context)
     : base(context)
 {
     _dbService = ServiceProxy.Create <IDBService>(new Uri("fabric:/ADC/ADC.Stateful.DBService"), new ServicePartitionKey(0));
 }
Ejemplo n.º 30
0
        public GameController()
        {
            ServicePartitionKey servicePartitionKey = new ServicePartitionKey(0);

            matchMaking = ServiceProxy.Create <IMatchMaking>(new Uri("fabric:/TicTacToe/MatchMaking"), servicePartitionKey);
        }