public async Task <IServiceRemotingClient> GetClientAsync(Uri serviceUri, ServicePartitionKey partitionKey, TargetReplicaSelector targetReplicaSelector, string listenerName, OperationRetrySettings retrySettings, CancellationToken cancellationToken) { IServiceRemotingClient inner = await _inner.GetClientAsync( serviceUri, partitionKey, targetReplicaSelector, listenerName, retrySettings, cancellationToken); return(new CorrelatingServiceRemotingClient(L.G <TServiceInterface>(), inner, _raiseSummary, _remoteServiceName)); }
/// <inheritdoc /> public Task <IServiceRemotingClient> GetClientAsync(ResolvedServicePartition previousRsp, TargetReplicaSelector targetReplicaSelector, string listenerName, OperationRetrySettings retrySettings, CancellationToken cancellationToken) { ServicePartitionKey partitionKey; switch (previousRsp.Info.Kind) { case ServicePartitionKind.Singleton: partitionKey = new ServicePartitionKey(); break; case ServicePartitionKind.Int64Range: partitionKey = new ServicePartitionKey(((Int64RangePartitionInformation)previousRsp.Info).LowKey); break; case ServicePartitionKind.Named: partitionKey = new ServicePartitionKey(((NamedPartitionInformation)previousRsp.Info).Name); break; default: throw new ArgumentOutOfRangeException(); } return(GetClientAsync(previousRsp.ServiceName, partitionKey, targetReplicaSelector, listenerName, retrySettings, cancellationToken)); }
public async Task <IServiceRemotingClient> GetClientAsync(Uri serviceUri, ServicePartitionKey partitionKey, TargetReplicaSelector targetReplicaSelector, string listenerName, OperationRetrySettings retrySettings, CancellationToken cancellationToken) { var client = await _innerClientFactory.GetClientAsync(serviceUri, partitionKey, targetReplicaSelector, listenerName, retrySettings, cancellationToken); return(new FabricTransportServiceRemotingClient(client, serviceUri, _logger, _serviceMethodDispatcher)); }
private static void SendTestMessageToTopic(Uri uri, string topicName, bool serviceSupportsPartitions, bool requireSessions = false) { //the name of your application and the name of the Service, the default partition resolver and the topic name //to create a communication client factory: var resolver = ServicePartitionResolver.GetDefault(); var factory = new ServiceBusTopicCommunicationClientFactory(resolver, null); ServicePartitionClient <ServiceBusTopicCommunicationClient> servicePartitionClient; if (serviceSupportsPartitions) { //determine the partition and create a communication proxy var partitionKey = new ServicePartitionKey(0L); servicePartitionClient = new ServicePartitionClient <ServiceBusTopicCommunicationClient>(factory, uri, partitionKey); } else { servicePartitionClient = new ServicePartitionClient <ServiceBusTopicCommunicationClient>(factory, uri); } //use the proxy to send a message to the Service servicePartitionClient.InvokeWithRetry(c => c.SendMessage(CreateMessage(requireSessions))); Console.WriteLine($"Message sent to topic '{topicName}'"); }
public HttpCommunicationServicePartitionClient( FabricClient fabricClient, Uri application, Uri serviceUri, ServicePartitionKey partitionKey = null, TargetReplicaSelector targetReplicaSelector = TargetReplicaSelector.Default, string listenerName = null, OperationRetrySettings retrySettings = null) : base(new HttpCommunicationClientFactory(new ServicePartitionResolver(() => fabricClient)), serviceUri, partitionKey, targetReplicaSelector, listenerName, retrySettings) { this.fabricClient = fabricClient; this.application = application; }
private static async Task <IMyStatefulService> CreateProxyAsync(long partitionKey) { IMyStatefulService proxy = null; while (proxy == null) { try { var servicePartitionKey = new ServicePartitionKey(partitionKey); proxy = ServiceProxy.Create <IMyStatefulService>(ServiceUri, servicePartitionKey, TargetReplicaSelector.Default, BackupRestoreService.BackupRestoreServiceEndpointName); var result = await proxy.ListBackups(); if (result != null) { break; } } catch { proxy = null; Console.Write("."); await Task.Delay(200); } } return(proxy); }
private async Task QueryServicePartitions(List <BackupEnabledServiceReference> backupEnabledServices, Application app, Service service, Guid?partitionId) { string token; do { var partitions = await _fabricClient.QueryManager.GetPartitionListAsync(service.ServiceName, partitionId).ConfigureAwait(true); foreach (var partition in partitions) { ServicePartitionKey key; switch (partition.PartitionInformation.Kind) { //only int64 partitions are supported at this time case ServicePartitionKind.Int64Range: var longKey = (Int64RangePartitionInformation)partition.PartitionInformation; key = new ServicePartitionKey(longKey.LowKey); break; default: continue; } var resolved = await _servicePartitionResolver.ResolveAsync(service.ServiceName, key, CancellationToken.None).ConfigureAwait(true); foreach (var endpoint in resolved.Endpoints.Where(e => !string.IsNullOrWhiteSpace(e.Address))) { QueryPartitionEndpoints(backupEnabledServices, app, service, partition, endpoint); } } token = partitions.ContinuationToken; } while (token != null); }
public async Task <IActionResult> RemoveInventory(Guid itemId, InventoryItemType selectedItemType) { var partitionKey = new ServicePartitionKey((int)selectedItemType); var partitionClient = new ServicePartitionClient <HttpCommunicationClient>(_clientFactory, _serviceUri, partitionKey); var item = await partitionClient.InvokeWithRetryAsync(async (client) => { var response = await client.HttpClient.GetAsync(new Uri($"{client.BaseUri}/api/inventory/{itemId}")); if (!response.IsSuccessStatusCode) { throw new InvalidOperationException($"Error - {response.StatusCode}: {response.ReasonPhrase}"); } var responseContent = await response.Content.ReadAsStringAsync(); return(JsonConvert.DeserializeObject <InventoryItem>(responseContent)); }, CancellationToken.None); var viewModel = new InventoryQuantityViewModel { ItemId = item.ItemId, ItemType = item.ItemType, Display = $"{item.Name} ({item.ItemType})", IsAdd = false, Quantity = 1 }; return(View("UpdateInventoryQuantity", viewModel)); }
/// <inheritdoc /> public override Task PublishAsync(MessageWrapper message) { if (string.IsNullOrWhiteSpace(RoutingKey) || ShouldDeliverMessage(message)) { ServicePartitionKey partitionKey; switch (ServiceReference.PartitionKind) { case ServicePartitionKind.Singleton: partitionKey = ServicePartitionKey.Singleton; break; case ServicePartitionKind.Int64Range: partitionKey = new ServicePartitionKey(ServiceReference.PartitionKey); break; case ServicePartitionKind.Named: partitionKey = new ServicePartitionKey(ServiceReference.PartitionName); break; default: throw new ArgumentOutOfRangeException(); } var client = ServiceProxyFactoryLazy.Value.CreateServiceProxy <ISubscriberService>(ServiceReference.ServiceUri, partitionKey); return(client.ReceiveMessageAsync(message)); } return(Task.FromResult(true)); }
private async Task <ServicePartitionKey> GetSearchPartitionKeyAsync(string searchTerm) { char firstLetterOfSearchTerm = searchTerm.First(); var cancelToken = new CancellationTokenSource(); if (Char.IsLetter(firstLetterOfSearchTerm)) { var partitionKey = new ServicePartitionKey(Char.ToUpper(firstLetterOfSearchTerm) - 'A'); var partition = await this._servicePartitionResolver.ResolveAsync(_searchServiceUri, partitionKey, cancelToken.Token); Debug.WriteLine("Partition key: '{0}'" + "generated from the first letter '{1}' of input value '{2}'." + "Processing service partition ID: {3}", partitionKey, firstLetterOfSearchTerm, searchTerm, partition.Info.Id ); cancelToken.Cancel(false); return(partitionKey); } throw new Exception("Invalid argument!"); }
public async Task <IServiceRemotingClient> GetClientAsync(Uri serviceUri, ServicePartitionKey partitionKey, TargetReplicaSelector targetReplicaSelector, string listenerName, OperationRetrySettings retrySettings, CancellationToken cancellationToken) { IServiceRemotingClient innerClient = await _innerClientFactory .GetClientAsync(serviceUri, partitionKey, targetReplicaSelector, listenerName, retrySettings, cancellationToken).ConfigureAwait(false); return(new CorrelatingServiceRemotingClient(innerClient, serviceUri, _methodNameProvider)); }
public ValidationServiceClient( ICommunicationClientFactory <WcfCommunicationClient <IValidationServiceStateful> > communicationClientFactory, Uri serviceUri, ServicePartitionKey partitionKey = null, TargetReplicaSelector targetReplicaSelector = TargetReplicaSelector.Default, string listenerName = null, OperationRetrySettings retrySettings = null) : base(communicationClientFactory, serviceUri, partitionKey, targetReplicaSelector, listenerName, retrySettings) { }
public CounterController() { var serviceUri = new Uri("fabric:/CounterApp/CounterService"); var partitionKey = new ServicePartitionKey(0); _queryCounter = ServiceProxy.Create <IQueryCounter>(serviceUri, partitionKey); _incrementCounter = ServiceProxy.Create <IIncrementCounter>(serviceUri, partitionKey); }
public static I ForMicroservice<I>(ServicePartitionKey partitionKey = null) where I : class, IService { Debug.Assert( typeof(I).Namespace.Contains(Constant.Manager), $"Invalid microservice call. Use only the {Constant.Manager} interface to access a microservice."); return ForService<I>(Addressing.Microservice<I>(), partitionKey); }
private async Task ProcessInputRequest(HttpListenerContext context, CancellationToken cancelRequest) { String output = null; try { string lastname = context.Request.QueryString["lastname"]; // The partitioning scheme of the processing service is a range of integers from 0 - 25. // This generates a partition key within that range by converting the first letter of the input name // into its numerica position in the alphabet. char firstLetterOfLastName = lastname.First(); ServicePartitionKey partitionKey = new ServicePartitionKey(Char.ToUpper(firstLetterOfLastName) - 'A'); // This contacts the Service Fabric Naming Services to get the addresses of the replicas of the processing service // for the partition with the partition key generated above. // Note that this gets the most current addresses of the partition's replicas, // however it is possible that the replicas have moved between the time this call is made and the time that the address is actually used // a few lines below. // For a complete solution, a retry mechanism is required. // For more information, see http://aka.ms/servicefabricservicecommunication ResolvedServicePartition partition = await this.servicePartitionResolver.ResolveAsync(alphabetServiceUri, partitionKey, cancelRequest); ResolvedServiceEndpoint ep = partition.GetEndpoint(); JObject addresses = JObject.Parse(ep.Address); string primaryReplicaAddress = (string)addresses["Endpoints"].First(); UriBuilder primaryReplicaUriBuilder = new UriBuilder(primaryReplicaAddress); primaryReplicaUriBuilder.Query = "lastname=" + lastname; string result = await this.httpClient.GetStringAsync(primaryReplicaUriBuilder.Uri); output = String.Format( "Result: {0}. <p>Partition key: '{1}' generated from the first letter '{2}' of input value '{3}'. <br>Processing service partition ID: {4}. <br>Processing service replica address: {5}", result, partitionKey, firstLetterOfLastName, lastname, partition.Info.Id, primaryReplicaAddress); } catch (Exception ex) { output = ex.Message; } using (HttpListenerResponse response = context.Response) { if (output != null) { response.ContentType = "text/html"; byte[] outBytes = Encoding.UTF8.GetBytes(output); response.OutputStream.Write(outBytes, 0, outBytes.Length); } } }
public static TServiceInterface CreateServiceProxy <TServiceInterface>( Uri serviceUri, ServicePartitionKey partitionKey = null, TargetReplicaSelector targetReplicaSelector = TargetReplicaSelector.Default, string listenerName = null) where TServiceInterface : IService { return(DefaultServiceProxyFactory.CreateServiceProxy <TServiceInterface>(serviceUri, partitionKey, targetReplicaSelector, listenerName)); }
public static TServiceInterface CreateService <TServiceInterface>(Uri serviceUri) where TServiceInterface : IService { CustomContextDataDto dto = CustomServiceContext.GetContext(); ServiceProxyFactory factory = new ServiceProxyFactory(CreateServiceRemotingClientFactory); ServicePartitionKey key = new ServicePartitionKey(GetLongHashCode(dto == null ? string.Empty : dto.ID)); var serviceProxy = factory.CreateServiceProxy <TServiceInterface>(serviceUri, key); return(serviceProxy); }
private static IRoadService ApplyIncorrectPartitioningStrategy(string town) { var serviceUri = new Uri($"fabric:/ServiceFabricApplication/RoadService"); var proxyFactory = new ServiceProxyFactory(_ => new FabricTransportServiceRemotingClientFactory()); var partitionKey = new ServicePartitionKey(town.Length + 400); var roadService = proxyFactory.CreateServiceProxy <IRoadService>(serviceUri, partitionKey); return(roadService); }
public GatewayService(StatelessServiceContext context) : base(context) { this.state = GatewayState.Created; this.myInfo = CreateMyInfo(context); this.heartbeatInterval = GetHeartbeatDuration(context.CodePackageActivationContext); this.monitorServiceAddress = GetMonitorServiceAddress(context.CodePackageActivationContext); this.monitorServicePartitionKey = new ServicePartitionKey(this.myInfo.Id.Name); }
protected override async Task PushToTargetAsync(IEnumerable <ResourceUsageRecord> records, Guid batchId, CancellationToken cancellationToken) { // PartionKey is between Int.Min and Int.Max var partitionKey = new ServicePartitionKey(batchId.GetHashCode()); var client = this.proxyFactory.CreateServiceProxy <IBillingService>(BillingServiceUri, partitionKey, TargetReplicaSelector.PrimaryReplica); await client.ReportBillingUsageAsync(records.ToList(), cancellationToken); EmailProviderEventSource.Current.Info(EmailProviderEventSource.EmptyTrackingId, this, nameof(this.PushUsageInnerLoopAsync), OperationStates.Succeeded, $"Pushed {records.Count()} record(s) to Billing Service"); }
public CalculatorClient( Uri serviceUri, ServicePartitionKey partitionKey) : base( communicationClientFactory, serviceUri, partitionKey) { }
private async Task <List <Contracts.Models.Booking> > ListPartitionAsync(ServicePartitionKey partitionKey) { var result = await partitionClientFactory.CreatePartitionClient(partitionKey).InvokeWithRetryAsync(async client => { var api = await client.CreateApiClient(); return(await api.ListBookingsWithHttpMessagesAsync()); }); return(mapper.MapFrom(result.Body)); }
public static IFullTextSearchService GetFullTextSearchService(ServiceContext context) { string applicationName = context .CodePackageActivationContext.ApplicationName; Uri uri = new Uri($"{applicationName}/FullTextSearchService"); ServicePartitionKey partitionKey = new ServicePartitionKey(0); return(ServiceProxy.Create <IFullTextSearchService>(uri, partitionKey)); }
private static IVotingDataService GetRemotingClient() { if (client == null) { var resolver = ServicePartitionResolver.GetDefault(); var partKey = new ServicePartitionKey(1); var partition = resolver.ResolveAsync(new Uri(REMOTING_URI), partKey, new CancellationToken()); client = ServiceProxy.Create <IVotingDataService>(new Uri(REMOTING_URI), partKey); } return(client); }
/// <summary> /// Resolves a partition of the specified service containing one or more communication listeners and returns a client to communicate /// to the endpoint corresponding to the given listenerName. /// The endpoint of the service is of the form - {"Endpoints":{"Listener1":"Endpoint1","Listener2":"Endpoint2" ...}} /// </summary> /// <param name="serviceUri">Uri of the service to resolve</param> /// <param name="partitionKey">Key that identifies the partition to resolve</param> /// <param name="targetReplicaSelector">Specifies which replica in the partition identified by the partition key, the client should connect to</param> /// <param name="listenerName">Specifies which listener in the endpoint of the chosen replica, to which the client should connect to</param> /// <param name="retrySettings">Specifies the retry policy that should be used for exceptions that occur when creating the client.</param> /// <param name="cancellationToken">Cancellation token</param> /// <returns> /// A <see cref="System.Threading.Tasks.Task">Task</see> that represents outstanding operation. The result of the Task is /// the CommunicationClient(<see cref="ICommunicationClient" />) object. /// </returns> public async Task <IServiceRemotingClient> GetClientAsync(Uri serviceUri, ServicePartitionKey partitionKey, TargetReplicaSelector targetReplicaSelector, string listenerName, OperationRetrySettings retrySettings, CancellationToken cancellationToken) { return(await this.clientFactoryImpl.GetClientAsync(serviceUri, partitionKey, targetReplicaSelector, listenerName, retrySettings, cancellationToken)); }
public MockActorProxy( ActorId actorId, Uri serviceUri, ServicePartitionKey partitionKey, TargetReplicaSelector replicaSelector, string listenerName, ICommunicationClientFactory <IServiceRemotingClient> factory) { ActorId = actorId; ActorServicePartitionClient = new MockActorServicePartitionClient(actorId, serviceUri, partitionKey, replicaSelector, listenerName, factory); }
private async Task GetNextInLine() { try { WriteTimedDebug("GetNextInLine"); Random random = new Random(); PosDeviceModes posDeviceMode = random.Next(0, 2) == 0 ? PosDeviceModes.ConsumerScans : PosDeviceModes.PosDeviceScans; posDeviceMode = PosDeviceModes.PosDeviceScans; if (posDeviceMode == PosDeviceModes.ConsumerScans) { await CreateCheckoutSessionAsync(); } int partitionIndex = random.Next(0, 4); ServicePartitionKey servicePartitionKey = new ServicePartitionKey(partitionIndex); ILineService proxy = ServiceProxy.Create <ILineService>(LineServiceUri, servicePartitionKey); List <ApiLicenseDisplay> codes = await StateManager.GetStateAsync <List <ApiLicenseDisplay> >(AppApiLicensesKey); string appApiLicenseCode = codes.First().Code; Guid consumerId = await proxy.GetNextConsumerInLineAsync(appApiLicenseCode); await StateManager.SetStateAsync(CurrentConsumerIdKey, consumerId); ActorId consumerActorId = new ActorId(consumerId); IConsumerSimulationActor consumerActor = ActorProxy.Create <IConsumerSimulationActor>(consumerActorId, ConsumerServiceUri); await consumerActor.BeginTransaction(this.Id.GetGuidId(), posDeviceMode); if (posDeviceMode == PosDeviceModes.ConsumerScans) { await _Machine.FireAsync(PosDeviceSimulationTriggerType.WaitForConsumerToCheckout); } else { await _Machine.FireAsync(PosDeviceSimulationTriggerType.WaitForConsumerToPresentQr); } } catch (Exception ex) { WriteTimedDebug(ex); await _Machine.FireAsync(PosDeviceSimulationTriggerType.GoIdle); } }
public async Task <IServiceRemotingClient> GetClientAsync(Uri serviceUri, ServicePartitionKey partitionKey, TargetReplicaSelector targetReplicaSelector, string listenerName, OperationRetrySettings retrySettings, CancellationToken cancellationToken) { var client = await serviceRemotingClientFactory.GetClientAsync(serviceUri, partitionKey, targetReplicaSelector, listenerName, retrySettings, cancellationToken); return(new ServiceRemotingClientWrapper(client, traceId)); }
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); }
public static I ForMicroservice <I>(ServiceProxyFactory serviceProxyFactory, ServicePartitionKey partitionKey = null) where I : class, IService { if (serviceProxyFactory == null) { throw new ArgumentNullException(nameof(serviceProxyFactory), "Invalid microservice call. Must supply service proxy factory."); } Debug.Assert( typeof(I).Namespace.Contains(Constant.Manager), $"Invalid microservice call. Use only the {Constant.Manager} interface to access a microservice."); return(ForService <I>(serviceProxyFactory, Addressing.Microservice <I>(), partitionKey)); }
public HttpServiceUriBuilder SetPartitionKey(ServicePartitionKey partitionKey) { this.PartitionKey = partitionKey; return this; }
private static void SendTestMessageToQueue(Uri uri, string queueName, bool serviceSupportsPartitions) { //the name of your application and the name of the Service, the default partition resolver and the topic name //to create a communication client factory: var factory = new ServiceBusQueueCommunicationClientFactory(ServicePartitionResolver.GetDefault(), queueName); ServicePartitionClient<ServiceBusQueueCommunicationClient> servicePartitionClient; if (serviceSupportsPartitions) { //determine the partition and create a communication proxy var partitionKey = new ServicePartitionKey(0L); servicePartitionClient = new ServicePartitionClient<ServiceBusQueueCommunicationClient>(factory, uri, partitionKey); } else { servicePartitionClient = new ServicePartitionClient<ServiceBusQueueCommunicationClient>(factory, uri); } //use the proxy to send a message to the Service servicePartitionClient.InvokeWithRetry(c => c.SendMessage(CreateMessage())); Console.WriteLine("Message sent to queue"); }