public static IDepartmentAppService CreateDepartmentAppService()
        {
            var builder = new ServiceUriBuilder(AppName_EnterpriseContact, ServiceName_EnterpriseContactService);

            return(proxyFactory.CreateServiceProxy <IDepartmentAppService>(
                       builder.ToUri(), listenerName: ListenerName_DepartmentAppService));
        }
Beispiel #2
0
        public async Task <List <User> > GetUsersAsync(CancellationToken cancellationToken)
        {
            var userStoreProxy   = _serviceProxyFactory.CreateServiceProxy <IUserStore>(_userStoreServiceUri);
            var usersInPartition = await userStoreProxy.GetUsersAsync(cancellationToken);

            return(usersInPartition);
        }
Beispiel #3
0
        public static IConversationCtrlAppService CreateConversationCtrlAppService()
        {
            var builder = new ServiceUriBuilder(AppName_InstantMessage, ServiceName_ConversationCtrlStateService);

            return(proxyFactory.CreateServiceProxy <IConversationCtrlAppService>(
                       builder.ToUri()));
        }
        public static IClientAppService CreateClientAppService()
        {
            var builder = new ServiceUriBuilder(AppName_ConfigMgmt, ServiceName_SystemConfigStateService);

            return(proxyFactory.CreateServiceProxy <IClientAppService>(
                       builder.ToUri(), listenerName: ListenerName_ClientAppService));
        }
Beispiel #5
0
        private async Task CallValidationService(ServiceCoreRequest value)
        {
            IValidationService proxy = proxyFactory.CreateServiceProxy <IValidationService>(
                new Uri(
                    string.Concat(Context.CodePackageActivationContext.ApplicationName, "/Microsoft.IoT.ServiceFabric.Validation")),
                new ServicePartitionKey(0L),
                TargetReplicaSelector.PrimaryReplica);

            using (MeasureTime measure = new MeasureTime())
            {
                ServiceResponse <ValidationServiceResponse> response = await proxy.ValidateMessage(value);

                response.IsSuccess = response != null;

                telemetry.TrackEvent(
                    "Core-Validation-Call",
                    new Dictionary <string, string>()
                {
                    { "Id", value.Id }
                },
                    new Dictionary <string, double>()
                {
                    { "CoreElapsed", measure.Elapsed.TotalMilliseconds }
                });
            }
        }
        private async Task SaveResultsToDataService(string correlationId, IEnumerable <string> results)
        {
            var fundingCalcResultsService = _serviceProxyFactory.CreateServiceProxy <IFundingCalcResults>(
                _validationResultsServiceUri,
                new ServicePartitionKey(0), TargetReplicaSelector.PrimaryReplica, "dataServiceRemotingListener");

            await fundingCalcResultsService.SaveFCResultsAsync(correlationId, results);
        }
        public long Add(int a, int b)
        {
            var calculatorClient = proxyFactory.CreateServiceProxy <ICalculatorService>(
                new Uri("fabric:/CalculatorApplication/CalculatorService"),
                targetReplicaSelector: Microsoft.ServiceFabric.Services.Communication.Client.TargetReplicaSelector.RandomInstance);

            return(calculatorClient.Add(1, 2).Result);
        }
Beispiel #8
0
        public async Task <string> GetTest()
        {
            ServiceEventSource.Current.ServiceMessage(serviceContext, $"GetTest()");
            var    chessClient = proxyFactory.CreateServiceProxy <IChessFabrickStatefulService>(chessStatefulUri, new ServicePartitionKey(new Random().Next(0, 4)));
            string message     = await chessClient.HelloChessAsync();

            await Clients.All.SendAsync("Test", message);

            return("Test");
        }
Beispiel #9
0
        public async Task PerformMove()
        {
            ActorEventSource.Current.ActorMessage(this, $"PerformMove({gameId})");
            await Task.Delay(rand.Next(800, 1600));

            var chessClient = proxyFactory.CreateServiceProxy <IChessFabrickStatefulService>(chessStatefulUri, ChessFabrickUtils.GuidPartitionKey(gameId));
            var game        = await chessClient.ActiveGameStateAsync(gameId);

            while (true)
            {
                try
                {
                    var board = new Board();
                    board.PerformMoves(game.GameInfo.MoveHistory);
                    var move = GetRandomMove(board);
                    await chessClient.MovePieceAsync(gameId, ChessFabrickUtils.BOT_NAME, move.Item1, move.Item2);

                    return;
                }
                catch (Exception ex)
                {
                    ActorEventSource.Current.ActorMessage(this, $"PerformMoveException({gameId}): \n{ex}");
                }
            }
        }
        public static IAttachmentAppService CreateAttachmentAppService(string itemId)
        {
            var builder = new ServiceUriBuilder(AppName_Attachment, ServiceName_AttachmentStateService);

            return(proxyFactory.CreateServiceProxy <IAttachmentAppService>(builder.ToUri(),
                                                                           new ServicePartitionKey(HashUtil.getLongHashCode(itemId))));
        }
Beispiel #11
0
        public async Task OnGetAsync()
        {
            Message = "Your contact page.";

            var builder = new ServiceUriBuilder("SampleState");

            //use native serialization
            //var proxy = ServiceProxy.Create<ISampleRemotingService>(builder.ToUri());

            //use bson serialization
            var proxyFactory = new ServiceProxyFactory((c) =>
            {
                return(new FabricTransportServiceRemotingClientFactory(
                           serializationProvider: new BsonSerializationProvider()));
            });
            var proxy = proxyFactory.CreateServiceProxy <ISampleRemotingService>(builder.ToUri());

            Peoples = await proxy.GetPeoplesAsync(new FilterDto { Search = "abc", Page = 5 });

            var bus = Bus.Factory.CreateUsingRabbitMq(cfg =>
            {
                var host = cfg.Host(new Uri("rabbitmq://localhost"), h =>
                {
                    h.Username("guest");
                    h.Password("guest");
                });
            });
            await bus.Publish(new FilterDto { Search = "abc", Page = 5 });
        }
        public async Task CallAsync <TService>(string traceId, Uri uri, Expression <Func <TService, Task> > callMethod) where TService : IService
        {
            var proxyFactory = new ServiceProxyFactory(c => new ServiceRemotingClientFactoryWrapper(traceId,
                                                                                                    new WcfServiceRemotingClientFactory(callbackClient: c)));

            var service = proxyFactory.CreateServiceProxy <TService>(uri);
            var success = true;

            var stopwatch = Stopwatch.StartNew();
            var started   = DateTime.Now;

            try
            {
                await callMethod.Compile().Invoke(service);
            }
            catch (Exception exception)
            {
                success = false;
                logger.LogError(ServiceFabricEvent.Exception, exception, exception.Message);
                throw;
            }
            finally
            {
                stopwatch.Stop();
                logger.LogDependency(callMethod, started, stopwatch.Elapsed, success);
            }
        }
Beispiel #13
0
        public async Task <UserModel> Authenticate(string userName, string password)
        {
            var userClient = proxyFactory.CreateServiceProxy <IChessFabrickPlayersStatefulService>(userServiceUri, ChessFabrickUtils.NamePartitionKey(userName));
            var player     = await userClient.PlayerInfoAsync(userName);

            if (player == null)
            {
                throw new ArgumentException("Authentication failed.");
            }

            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(appSettings.Secret);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, player.Name)
                }),
                Expires            = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);

            var user = new UserModel {
                Player = player, Token = tokenHandler.WriteToken(token)
            };

            return(user);
        }
Beispiel #14
0
        private async void button_AddMathService_Click(object sender, EventArgs e)
        {
            int number1 = int.Parse(textBox_MathServiceNumber1.Text);
            int number2 = int.Parse(textBox_MathServiceNumber2.Text);

            //var uri = new Uri("fabric:/SampleSFV2/MathService");
            ServiceProxyFactory proxyFactory = new ServiceProxyFactory((c) =>
            {
                FabricTransportRemotingSettings settings = new FabricTransportRemotingSettings();
                return(new FabricTransportServiceRemotingClientFactory(settings));
            });

            try
            {
                IMathCalculator service = proxyFactory.CreateServiceProxy <IMathCalculator>(_mathServiceUri, listenerName: "MathCalculator_v2");

                int result = await service.Add(number1, number2);

                MessageBox.Show("Result= " + result);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
Beispiel #15
0
        private IMyBackend GetServiceClientWithTransportSettings()
        {
            var builder = new ServiceUriBuilder(BackendServiceName);

            //var x509Credentials = new X509Credentials
            //{
            //    FindType = X509FindType.FindByThumbprint,
            //    FindValue = "053a87f6c1e3d08ec7fc28522a2cf1921c9daa5e",
            //    StoreLocation = StoreLocation.LocalMachine,
            //    StoreName = "My",
            //    ProtectionLevel = ProtectionLevel.EncryptAndSign
            //};
            //x509Credentials.RemoteCommonNames.Add("jacksch.westus.cloudapp.azure.com");

            //var transportSettings = new FabricTransportSettings
            //{
            //    SecurityCredentials = x509Credentials,
            //    MaxMessageSize = 10000000
            //};

            var serviceProxyFactory = new ServiceProxyFactory((c) =>
                                                              new FabricTransportServiceRemotingClientFactory());

            return(serviceProxyFactory.CreateServiceProxy <IMyBackend>(builder.ToUri()));
        }
        public async Task <IServiceFabricCacheStoreService> GetCacheStoreProxy(string cacheKey)
        {
            // Try to locate a cache store if one is not configured
            if (_serviceUri == null)
            {
                _serviceUri = await LocateCacheStoreAsync();

                if (_serviceUri == null)
                {
                    throw new CacheStoreNotFoundException("Cache store not found in Service Fabric cluster.  Try setting the 'CacheStoreServiceUri' configuration option to the location of your cache store.");
                }
            }

            var partitionInformation = await GetPartitionInformationForCacheKey(cacheKey);

            return(_cacheStores.GetOrAdd(partitionInformation.Id, key => {
                var info = (Int64RangePartitionInformation)partitionInformation;
                var resolvedPartition = new ServicePartitionKey(info.LowKey);

                var proxyFactory = new ServiceProxyFactory((c) =>
                {
                    return new FabricTransportServiceRemotingClientFactory();
                });

                return proxyFactory.CreateServiceProxy <IServiceFabricCacheStoreService>(_serviceUri, resolvedPartition, Microsoft.ServiceFabric.Services.Communication.Client.TargetReplicaSelector.Default, _endpointName);
            }));
        }
Beispiel #17
0
        private async void button_AddNumbers_Click(object sender, EventArgs e)
        {
            //int number1 = int.Parse(textBox_Number1.Text);
            //int number2 = int.Parse(textBox_Number2.Text);

            //var uri = _evilMathServiceUri;

            int number1 = 10;
            int number2 = 100;

            Uri uri = new Uri("fabric:/SampleSFV2/EvilMathTeacherService");

            ServiceProxyFactory proxyFactory = new ServiceProxyFactory((c) =>
            {
                FabricTransportRemotingSettings settings = new FabricTransportRemotingSettings();
                return(new FabricTransportServiceRemotingClientFactory(settings));
            });

            try
            {
                IQuestionnaire service = proxyFactory.CreateServiceProxy <IQuestionnaire>(uri, listenerName: "Questionnaire_v2");
                int            result  = await service.AddTwoNumbers(number1, number2);

                MessageBox.Show("Result= " + result);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
Beispiel #18
0
        public ProductController()
        {
            var proxyFactory = new ServiceProxyFactory(c => new FabricTransportServiceRemotingClientFactory());

            _service = proxyFactory.CreateServiceProxy <IProductCatalogService>(
                new Uri("fabric:/ECommerce/ECommerce.ProductCatalog"), new ServicePartitionKey(0));
        }
Beispiel #19
0
        private IProductCatalogService GetProductCatalogService()
        {
            var proxyFactory = new ServiceProxyFactory(c => new FabricTransportServiceRemotingClientFactory());

            return(proxyFactory.CreateServiceProxy <IProductCatalogService>(new Uri("fabric:/ECommerce/ECommerce.ProductCatalog"),
                                                                            new ServicePartitionKey(0)));
        }
        public async Task <List <string> > GetAll(CancellationToken cancellationToken)
        {
            var address = new Uri($"{this._applicationName}/{MODULEMANAGERSERVICE}");
            var service = _proxyFactory.CreateServiceProxy <IModuleManager>(address);

            return(await service.GetModuleIds(cancellationToken));
        }
        public async Task <IActionResult> Start(string id)
        {
            try
            {
                var message = new ServiceMessage();
                message.CommChannel      = "Remoting";
                message.SessionId        = id;
                message.StampOne.Visited = true;
                message.StampOne.TimeNow = DateTime.UtcNow;

                //var storage = await _manager.GetOrAddAsync<IReliableDictionary<string, ServiceMessage>>("storage");
                //using (var tx = _manager.CreateTransaction())
                //{
                //    await storage.AddAsync(tx, message.MessageId, message);
                //    await tx.CommitAsync();
                //}

                var partitionKey = new ServicePartitionKey(1);
                var proxyFactory = new ServiceProxyFactory((c) =>
                {
                    //return new FabricTransportServiceRemotingClientFactory( serializationProvider: new ServiceRemotingJsonSerializationProvider());
                    return(new FabricTransportServiceRemotingClientFactory());
                });

                var service = proxyFactory.CreateServiceProxy <IServiceTwo>(new Uri(Endpoint), partitionKey, listenerName: "RemotingV2");
                //var service = ServiceProxy.Create<IServiceTwo>(new Uri(Endpoint), partitionKey);
                await service.VisitByRemotingAsync(message);

                return(Ok(new { id = id }));
            }
            catch (Exception e)
            {
                return(BadRequest(e.Message));
            }
        }
Beispiel #22
0
        public async Task <IEnumerable <Student> > Get(string subject)
        {
            var students = new List <Student>();

            Enum.TryParse(subject, out Subject subjectEnum);

            var partitions = await FabricClient.QueryManager.GetPartitionListAsync(_actorServiceUri);

            foreach (var p in partitions)
            {
                // ReSharper disable once PossibleNullReferenceException
                var minKey = (p.PartitionInformation as Int64RangePartitionInformation).LowKey;
                var proxy  = _serviceProxyFactory.CreateServiceProxy <IStudentActorService>(_actorServiceUri,
                                                                                            new ServicePartitionKey(minKey));

                var result = await proxy.GetStudentsBySubjectAsync(subjectEnum, CancellationToken.None);

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

            return(students);
        }
Beispiel #23
0
        public async Task <TService> ResolveServiceAsync <TService>(Uri location, ServicePartitionKey partition, TargetReplicaSelector selector, string listener, TimeSpan timeout, CancellationToken cancellation)
            where TService : ITestableService
        {
            return(await ResolveDependencyAsync(async() =>
            {
                if (_proxyFactory == null)
                {
                    throw new Exception("Proxy factory is not initialized");
                }

                Logger.LogInformation($"{typeof(TService).Name}: Creating proxy for service - {location}");
                var proxy = _proxyFactory.CreateServiceProxy <TService>(location, partition, selector, listener);
                Logger.LogInformation($"{typeof(TService).Name}: Proxy for service created");

                if (proxy == null)
                {
                    throw new Exception($"Proxy '{typeof(TService).Name}' was not resolved correctly");
                }

                var result = await proxy.TestAsync()
                             .ConfigureAwait(false);

                if (result == false)
                {
                    throw new Exception("Service was not initialized correctly");
                }

                Logger.LogInformation($"{typeof(TService).Name}: Proxy for service connected");
                return proxy;
            }, timeout, cancellation)
                   .ConfigureAwait(false));
        }
Beispiel #24
0
        public static IControlAppService CreateGroupFileControlAppService()
        {
            var builder = new ServiceUriBuilder(AppName_GroupFile, ServiceName_GroupFileService);

            return(proxyFactory.CreateServiceProxy <IControlAppService>(
                       builder.ToUri(), listenerName: ListenerName_ControlAppService));
        }
Beispiel #25
0
        public async Task <IEnumerable <ApiMovie> > Get(string text)
        {
            var partitionKey = await GetSearchPartitionKeyAsync(text);

            //var _searchService = ServiceProxy.Create<ISearchService>(
            //    _searchServiceUri,
            //    partitionKey);

            /* Remoting V2 does not support for complex type defaultly
             * Here overwriten serialize provider as json serialization to deserialize the response */
            var proxyFactory = new ServiceProxyFactory((c) =>
            {
                return(new FabricTransportServiceRemotingClientFactory(
                           serializationProvider: new ServiceRemotingJsonSerializationProvider()));
            });

            var _searchService = proxyFactory.CreateServiceProxy <ISearchService>(
                _searchServiceUri,
                partitionKey);

            var results = await _searchService.SearchMovies(new SearchParameters
            {
                Select     = new[] { "tmsId", "title", "longDescription" },
                SearchTerm = text
            });

            return(results?.Select(i => new ApiMovie()
            {
                Id = i.tmsId,
                Title = i.title,
                LongDescription = i.longDescription,
                ShortDescription = i.shortDescription
            }));
        }
        private static IRoadService GetRoadServiceProxy()
        {
            var serviceUri   = new Uri($"fabric:/ServiceFabricApplication/RoadServiceFacade");
            var proxyFactory = new ServiceProxyFactory(_ => new FabricTransportServiceRemotingClientFactory());

            return(proxyFactory.CreateServiceProxy <IRoadService>(serviceUri));
        }
Beispiel #27
0
        /// <inheritdoc/>
        public async Task CallAsync <TService>(
            CustomHeaders customHeaders,
            Uri uri,
            Expression <Func <TService, Task> > callMethod) where TService : IService
        {
            var proxyFactory = new ServiceProxyFactory(c => new ExtendedServiceRemotingClientFactory(new FabricTransportServiceRemotingClientFactory(remotingCallbackMessageHandler: c), customHeaders));
            var service      = proxyFactory.CreateServiceProxy <TService>(uri);
            var success      = true;

            var stopwatch = Stopwatch.StartNew();
            var started   = DateTime.Now;

            try
            {
                await callMethod.Compile().Invoke(service);
            }
            catch (Exception exception)
            {
                success = false;
                _logger.LogError(ServiceFabricEvent.Exception, exception, exception.Message);
                throw;
            }
            finally
            {
                stopwatch.Stop();
                _logger.LogDependency(callMethod, started, stopwatch.Elapsed, success);
            }
        }
Beispiel #28
0
        public async Task VisitByRemotingAsync(ServiceMessage message)
        {
            message.StampThree.Visited = true;
            message.StampThree.TimeNow = DateTime.UtcNow;

            var storage = await this.StateManager.GetOrAddAsync <IReliableDictionary <string, ServiceMessage> >("storage1");

            using (var tx = this.StateManager.CreateTransaction())
            {
                await storage.AddAsync(tx, message.MessageId, message);

                await tx.CommitAsync();
            }

            //var service = ServiceProxy.Create<IServiceFour>(new Uri(Service4Uri), new ServicePartitionKey(1));
            var proxyFactory = new ServiceProxyFactory((c) =>
            {
                //return new FabricTransportServiceRemotingClientFactory(serializationProvider: new ServiceRemotingJsonSerializationProvider());
                return(new FabricTransportServiceRemotingClientFactory());
            });
            var service = proxyFactory.CreateServiceProxy <IServiceFour>(new Uri(Service4Uri), new ServicePartitionKey(1), listenerName: "RemotingV2");


            await service.VisitByRemotingAsync(message);
        }
Beispiel #29
0
        private ICpuBurnerService GetBurner(long partition)
        {
            var proxyFactory = new ServiceProxyFactory(c => new FabricTransportServiceRemotingClientFactory());

            return(proxyFactory.CreateServiceProxy <ICpuBurnerService>(
                       new Uri("fabric:/Pluralsight.SfProd/Pluralsight.SfProd.CpuBurner"),
                       new ServicePartitionKey(partition)));
        }
        public TServiceInterface CreateServiceProxy <TServiceInterface>(Uri serviceUri, ServicePartitionKey partitionKey = null, TargetReplicaSelector targetReplicaSelector = TargetReplicaSelector.Default, string listenerName = null)
            where TServiceInterface : IService
        {
            TServiceInterface proxy = serviceProxyFactory.CreateServiceProxy <TServiceInterface>(serviceUri, partitionKey, targetReplicaSelector, listenerName);

            methodNameProvider.AddMethodsForProxyOrService(proxy.GetType().GetInterfaces(), typeof(IService));
            return(proxy);
        }