private static NumCountingSvcClient GetNumCountingSvcClient()
        {
            ServicePartitionResolver serviceResolver = new ServicePartitionResolver(() => new FabricClient() { });

            // Binding for WCF
            NetTcpBinding binding = CreateClientConnectionBinding();

            return new NumCountingSvcClient(
                new WcfCommunicationClientFactory<INumberCounter>(serviceResolver, binding, null, null),
                ServiceName);
        }
        private static void Main(string[] args)
        {
            if (args.Length > 0)
            {
                string endpoint = args[0];
                Console.WriteLine("Conencting to cluster: " + endpoint);
                ServicePartitionResolver resolver = new ServicePartitionResolver(endpoint);
                ServicePartitionResolver.SetDefault(resolver);
            }

            RunAsync().Wait();

            Console.ReadLine();
        }
        private static NumCountingSvcClient GetNumCountingSvcClient()
        {
            var clusterEndpoint = ConfigurationManager.AppSettings["clusterEndpoint"];
            ServicePartitionResolver serviceResolver = new ServicePartitionResolver(() => new FabricClient(clusterEndpoint) { });

            // Binding for WCF
            var binding = CreateClientConnectionBinding();

            //Singleton
            //return new NumCountingSvcClient(
            //    new WcfCommunicationClientFactory<INumberCounter>(serviceResolver, binding, null, null),
            //    ServiceName);
            //Named partition
            return new NumCountingSvcClient(
                new WcfCommunicationClientFactory<INumberCounter>(serviceResolver, binding, null, null),
                ServiceName, "Tenant_A");
        }
        private async Task RewriteRequestUriAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var resolver = new ServicePartitionResolver(() => new FabricClient());

            //
            // Resolve service endpoint
            //
            ResolvedServiceEndpoint endpoint = null;
            if (_computePartitionKeyAsLong != null)
            {
                var partition = await resolver.ResolveAsync(_serviceName, _computePartitionKeyAsLong(request), cancellationToken);
                endpoint = partition.Endpoints.First(p => p.Role == ServiceEndpointRole.StatefulPrimary);
            }
            else if (_computePartitionKeyAsString != null)
            {
                var partition = await resolver.ResolveAsync(_serviceName, _computePartitionKeyAsString(request), cancellationToken);
                endpoint = partition.Endpoints.First(p => p.Role == ServiceEndpointRole.StatefulPrimary);
            }
            else
            {
                var partition = await resolver.ResolveAsync(_serviceName, cancellationToken);
                endpoint = partition.Endpoints.First(p => p.Role == ServiceEndpointRole.Stateless);
            }

            //
            // Parse the endpoint
            //
            dynamic address = JsonConvert.DeserializeObject(endpoint.Address);
            string urlString = address.Endpoints[""];
            Uri url = new Uri(urlString, UriKind.Absolute);

            //
            // Rewrite request URL
            //
            var builder = new UriBuilder(request.RequestUri)
            {
                Scheme = url.Scheme,
                Host = url.Host,
                Port = url.Port
            };

            request.RequestUri = builder.Uri;
        }
Пример #5
0
        private static void Main(string[] args)
        {
            //
            // Create a service resolver for resolving the endpoints of the calculator service.
            //
            ServicePartitionResolver serviceResolver = new ServicePartitionResolver(() => new FabricClient());

            //
            // Create the binding.
            //
            NetTcpBinding binding = CreateClientConnectionBinding();

            //
            // Create a client for communicating with the calc service which has been created with
            // Singleton partition scheme.
            //
            Client calcClient = new Client(
                new WcfCommunicationClientFactory<ICalculator>(serviceResolver, binding, null),
                ServiceName);

            //
            // Register for connection events
            //
            calcClient.Factory.ClientConnected += ClientConnected;
            calcClient.Factory.ClientDisconnected += ClientDisconnected;

            long count = 0;
            while (true)
            {
                if (calcClient.AddAsync(2, 3).Result.Equals(5))
                {
                    count++;
                }
                if ((count%500) == 0)
                {
                    Console.SetCursorPosition(0, Console.CursorTop);
                    Console.Write(@"                    ");
                    Console.SetCursorPosition(0, Console.CursorTop);
                    Console.Write(count);
                }
            }
        }
        private static void Main(string[] args)
        {
            if (args.Length > 0)
            {
                string endpoint = args[0];
                Console.WriteLine("Conencting to cluster: " + endpoint);
                ServicePartitionResolver resolver = new ServicePartitionResolver(endpoint);
                ServicePartitionResolver.SetDefault(resolver);
            }

            Items = new List<InventoryItemId>();
            for (int i = 0; i < MaxNumberOfItems; i++)
            {
                Items.Add(new InventoryItemId());
            }

            Timer timer = new Timer(new TimerCallback(GenerateData), null, 0, GenerateDataIntervalInMsec);
            Console.ReadLine();
            timer.Dispose();
        }
Пример #7
0
        private async Task uploadTranscript(string fileName, string text, string user)
        {
            string connectionString            = "[Storage Account Connection String]";
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);
            CloudBlobClient     blobClient     = storageAccount.CreateCloudBlobClient();
            CloudBlobContainer  container      = blobClient.GetContainerReference("transcripts");
            CloudBlockBlob      blockBlob      = container.GetBlockBlobReference(fileName + "transcript.txt");

            using (var stream = new MemoryStream(Encoding.Default.GetBytes(text), false))
            {
                await blockBlob.UploadFromStreamAsync(stream);
            }

            Binding binding = WcfUtility.CreateTcpClientBinding();
            IServicePartitionResolver partitionResolver = ServicePartitionResolver.GetDefault();
            var wcfClientFactory = new WcfCommunicationClientFactory <IStateAggregator>(
                clientBinding: binding,
                servicePartitionResolver: partitionResolver
                );
            var jobClient = new ServicePartitionClient <WcfCommunicationClient <IStateAggregator> >(
                wcfClientFactory,
                new Uri("fabric:/AudioTranscriptionApp/StateAggregator"));
            await jobClient.InvokeWithRetryAsync(client => client.Channel.ReportCompletion(fileName, blockBlob.Uri.AbsoluteUri, user));
        }
Пример #8
0
        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
                long partitionKey = 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");
        }
Пример #9
0
        public async static Task Run()
        {
            Binding binding = WcfUtility.CreateTcpClientBinding();
            // Create a partition resolver
            IServicePartitionResolver partitionResolver = ServicePartitionResolver.GetDefault();
            //var partitionResolver = new ServicePartitionResolver("dctsfpoc.westeurope.cloudapp.azure.com:19080",
            //    "dctsfpoc.westeurope.cloudapp.azure.com:20188", "dctsfpoc.westeurope.cloudapp.azure.com:19000");
            // create a  WcfCommunicationClientFactory object.
            var wcfClientFactory = new WcfCommunicationClientFactory <IReferenceDataService>
                                       (clientBinding: binding, servicePartitionResolver: partitionResolver);

            //
            // Create a client for communicating with the ICalculator service that has been created with the
            // Singleton partition scheme.
            //
            var dataServiceCommunicationClient = new WcfCommunicationClient(
                wcfClientFactory,
                new Uri("fabric:/DCT.ILR.Processing.POC/DCT.ILR.Data"),
                new ServicePartitionKey(1)
                );


            var resolved = partitionResolver.ResolveAsync(new Uri("fabric:/DCT.ILR.Processing.POC/DCT.ILR.Data"),
                                                          new ServicePartitionKey(1), TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(10), CancellationToken.None).Result;

            //foreach (var endpoint in resolved.Endpoints)
            //{
            //    Console.WriteLine($"Discovered Service Endpoint:'{endpoint.Address}");
            //}
            // ListEndpoints(partitionResolver);
            //
            // Call the service to perform the operation.
            //
            try
            {
                var correlationId = Guid.NewGuid();

                //var processTimes = validationServiceCommunicationClient.InvokeWithRetryAsync(
                //        client => client.Channel.GetResults(correlationId)).Result;

                Console.WriteLine("1. Insert ULns values, 2. Just get results ");
                var keyValue = Console.ReadKey();
                if (keyValue.KeyChar != 50)
                {
                    await dataServiceCommunicationClient.InvokeWithRetryAsync(
                        client => client.Channel.InsertULNs());
                }

                var ulns = new List <long>()
                {
                    1000000027,
                    1000000035,
                    1000000043,
                    1000000051,
                    1000000078,
                    1000000272,
                    1000000280,
                    1000000299,
                    1000000302,
                    1000000310,
                    1000000477,
                    1000000485,
                    1000000493,
                    1000000647,
                    1000000655,
                    1000000671,
                    1000000779,
                    1000000787,
                    1000000795,
                    1000000841
                };

                var value1 = new JumpSharding().GetShard("1000000795", 10);
                var value2 = new JumpSharding().GetShard("1000000795", 10);


                var validUlns = await dataServiceCommunicationClient.InvokeWithRetryAsync(
                    client => client.Channel.GetULNs(ulns));



                Console.WriteLine("1. Insert LARS values, 2. Just get results ");
                keyValue = Console.ReadKey();
                if (keyValue.KeyChar != 50)
                {
                    await dataServiceCommunicationClient.InvokeWithRetryAsync(
                        client => client.Channel.InsertLARSData());
                }
                var learnAimRefs = new List <string>()
                {
                    "00100309",
                    "00100325",
                    "00100432",
                    "00100525",
                    "00100533",
                    "00100567",
                    "00100572",
                    "00100573",
                    "00228740",
                    "00228761",
                    "00228762",
                    "00228763",
                    "00228764",
                    "00228787",
                    "00228789",
                    "00228790",
                    "00230643",
                    "00230644",
                    "00230645",
                    "00230646",
                    "00230648",
                    "00230680",
                    "00230684",
                    "00230698",
                    "00230699",
                    "00230703",
                    "00230704",
                    "00230712",
                    "00230713",
                    "00230718",
                    "00230722",
                    "00230761",
                    "00230764",
                    "00243034",
                    "00243035",
                    "00243042",
                    "00243043",
                    "00243045",
                    "00243046",
                    "00243047",
                    "00243054",
                    "00243057",
                    "00243060",
                    "00243064",
                    "00243066",
                    "00243067",
                    "00243068",
                    "00243071",
                    "00243072",
                    "00243073",
                    "00243075",
                    "00243076",
                    "00243077",
                    "00243078",
                    "00243114",
                    "J6018531",
                    "J6018545",
                    "J6018576",
                    "J6018593",
                    "J6018626",
                    "J6018643",
                    "J6018657",
                    "J6018707",
                    "J6018710",
                    "J6018724",
                    "J6018741",
                    "J6018755",
                    "J6018769",
                    "J6018772",
                    "J6018805",
                    "J6018836",
                    "J6018853",
                    "J6018867",
                    "L5068787",
                    "L5068904",
                    "L5070183",
                    "L5070197",
                    "L5070202",
                    "L5070233",
                    "L5070247",
                    "L5070250",
                    "L5070264",
                    "L5070281",
                    "L5070295",
                    "L5070300",
                    "Z0005494",
                    "Z0005495",
                    "Z0005496",
                    "Z0005497",
                    "Z0005498",
                    "Z0005499",
                    "Z0005500",
                    "Z0005501",
                    "Z0005502",
                    "Z0005503",
                    "Z0005504",
                    "Z0005505",
                    "Z0005506",
                    "Z0005507",
                    "Z0005508",
                    "Z0005509",
                    "Z0005510",
                    "Z0005511",
                    "Z0005512",
                };
                var tasksList = new List <Task>();

                foreach (var item in learnAimRefs)
                {
                    tasksList.Add(dataServiceCommunicationClient.InvokeWithRetryAsync(
                                      client => client.Channel.GetLARSLearningDeliveriesAsync(new List <string>()
                    {
                        item
                    })));
                }

                try
                {
                    await Task.WhenAll(tasksList.ToArray());

                    Console.WriteLine("failed tasks: " + tasksList.Count(x => x.IsFaulted));
                    //foreach (var task in tasksList)
                    //{
                    //    Console.WriteLine(task.Result);
                    //}
                }
                catch (Exception iex)
                {
                    Console.WriteLine(iex.ToString());
                }

                Console.WriteLine("");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                Console.ReadLine();
            }
        }
Пример #10
0
        private async Task <SprocAddressStruct> GetOrCreateSproServiceInstanceAsync(string messageSessionType, string messageUserName)
        {
            var urlPath = $"SPROC_{messageSessionType}_{messageUserName}";

            var url          = new ServiceUriBuilder(urlPath).ToUri();
            var fabricClient = new FabricClient();

            ServiceDescription service = null;

            try
            {
                service = await fabricClient.ServiceManager.GetServiceDescriptionAsync(url);
            }
            catch (Exception ex)
            {
                // nothing to do -> exception mean no service with the requested namename
                service = null;
            }
            if (service == null)
            {
                StatelessServiceDescription newGeneratorDescription = new StatelessServiceDescription()
                {
                    ApplicationName            = new Uri(this.Context.CodePackageActivationContext.ApplicationName),
                    ServiceName                = url,
                    InstanceCount              = 1,
                    ServiceTypeName            = "com.mega.SproGuestExeType",
                    PartitionSchemeDescription = new SingletonPartitionSchemeDescription()
                };

                await fabricClient.ServiceManager.CreateServiceAsync(newGeneratorDescription).ConfigureAwait(false);

                service = await fabricClient.ServiceManager.GetServiceDescriptionAsync(url);


                var healthState = HealthState.Unknown;
                var count       = 0;
                while (healthState != HealthState.Ok)
                {
                    if (count++ >= 10)
                    {
                        throw new TimeoutException("Time out waiting for " + url);
                    }

                    var serviceList = await fabricClient.QueryManager.GetServiceListAsync(new Uri(this.Context.CodePackageActivationContext.ApplicationName));

                    healthState = serviceList.Single(services => services.ServiceName == url).HealthState;

                    if (healthState != HealthState.Ok)
                    {
                        await Task.Delay(TimeSpan.FromSeconds(2));
                    }
                }
            }

            ServicePartitionResolver resolver  = ServicePartitionResolver.GetDefault();
            ResolvedServicePartition partition = await resolver.ResolveAsync(service.ServiceName,
                                                                             new ServicePartitionKey(), CancellationToken.None);

            var s = partition.Endpoints.First();
            // s.Address == {"Endpoints":{"com.mega.SproGuestExeTypeEndpoint":"localhost:33039"}}

            // HACK : exytraction fqdn : should using json deserialization instead of this bad hack
            int start = s.Address.IndexOf(":\"") + 2;
            int stop  = s.Address.IndexOf("\"", start);
            var fqdn  = s.Address.Substring(start, stop - start);

            var parts = fqdn.Split(':');

            return(new SprocAddressStruct {
                ServiceName = service.ServiceName, Ip = parts[0], Port = Convert.ToInt32(parts[1])
            });
        }
 /// <summary>
 /// Creates instance of <see cref="FabricPartitionEndpointResolver"/>.
 /// </summary>
 /// <param name="serviceUri">Fabric service uri</param>
 /// <param name="instanceIdHasher">Instance id hasher</param>
 public FabricPartitionEndpointResolver(Uri serviceUri, IPartitionHashing <string> instanceIdHasher)
 {
     this.serviceUri        = serviceUri ?? throw new ArgumentNullException(nameof(serviceUri));
     this.instanceIdHasher  = instanceIdHasher ?? throw new ArgumentNullException(nameof(instanceIdHasher));
     this.partitionResolver = ServicePartitionResolver.GetDefault();
 }
Пример #12
0
 public ServiceDiscovery()
 {
     resolver = ServicePartitionResolver.GetDefault();
 }
Пример #13
0
        /// <summary>
        /// This is the main entry point for your service replica.
        /// This method executes when this replica of your service becomes primary and has write status.
        /// </summary>
        /// <param name="cancellationToken">Canceled when Service Fabric needs to shut down this service replica.</param>
        protected override async Task RunAsync(CancellationToken cancellationToken)
        {
            string eventHubConnectionString = "Event hub compatible endpoint - Azure portal -> IoT Hub -> Build-in endpoints ";

            // These Reliable Dictionaries are used to keep track of our position in IoT Hub.
            // If this service fails over, this will allow it to pick up where it left off in the event stream.
            IReliableDictionary <string, string> offsetDictionary =
                await this.StateManager.GetOrAddAsync <IReliableDictionary <string, string> >(OffsetDictionaryName);

            IReliableDictionary <string, long> epochDictionary =
                await this.StateManager.GetOrAddAsync <IReliableDictionary <string, long> >(EpochDictionaryName);

            // Each partition of this service corresponds to a partition in IoT Hub.
            // IoT Hub partitions are numbered 0..n-1, up to n = 32.
            // This service needs to use an identical partitioning scheme.
            // The low key of every partition corresponds to an IoT Hub partition.
            Int64RangePartitionInformation partitionInfo = (Int64RangePartitionInformation)this.Partition.PartitionInfo;
            long servicePartitionKey = partitionInfo.LowKey;

            PartitionReceiver partitionReceiver = null;

            try
            {
                // Get the partition receiver for reading message from specific consumer group and partition
                // Consumer group is set to $Default
                partitionReceiver = await this.ConnectToIoTHubAsync(consumerGroup : PartitionReceiver.DefaultConsumerGroupName,
                                                                    connectionString : eventHubConnectionString,
                                                                    servicePartitionKey : servicePartitionKey,
                                                                    epochDictionary : epochDictionary,
                                                                    offsetDictionary : offsetDictionary);

                int offsetIteration = 0;

                while (true)
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    try
                    {
                        // Reading event data list from partition receiver with max message count parameter
                        IEnumerable <EventData> eventDataList = await partitionReceiver.ReceiveAsync(MaxMessageCount);

                        if (eventDataList == null)
                        {
                            continue;
                        }

                        using (var eventData = eventDataList.FirstOrDefault())
                        {
                            string deviceId = (string)eventData.SystemProperties["iothub-connection-device-id"];
                            string data     = Encoding.UTF8.GetString(eventData.Body);
                            ServiceEventSource.Current.ServiceMessage(
                                this.Context,
                                "Reading data from device {0} with data {1}",
                                deviceId,
                                data);

                            var message = new Message(eventData.Body.Array);

                            //TODO: Avoid hardcoded values, place in app settings
                            Uri statelessServiceUri             = new Uri("fabric:/ServiceFabric.IoTSample/IoTSample.CalculationStatelessService");
                            var statelessServiceFactory         = new ServiceBusCommunicationClientFactory(ServicePartitionResolver.GetDefault(), "name of the queue");
                            var statelessServicePartitionClient = new ServicePartitionClient <ServiceBusCommunicationClient>(statelessServiceFactory, statelessServiceUri);
                            await statelessServicePartitionClient.InvokeWithRetryAsync(c => c.SendMessageAsync(message));

                            //TODO: Avoid hardcoded values, place in app settings
                            Uri statefulServiceUri             = new Uri("fabric:/ServiceFabric.IoTSample/IoTSample.ProcessingStatefulService");
                            var statefulServiceFactory         = new ServiceBusCommunicationClientFactory(ServicePartitionResolver.GetDefault(), "name of the queue");
                            var partitionKey                   = new ServicePartitionKey(0L);
                            var statefulServicePartitionClient = new ServicePartitionClient <ServiceBusCommunicationClient>(statefulServiceFactory, statefulServiceUri, partitionKey);
                            await statefulServicePartitionClient.InvokeWithRetryAsync(c => c.SendMessageAsync(message.Clone()));


                            if (++offsetIteration % OffsetInterval == 0)
                            {
                                ServiceEventSource.Current.ServiceMessage(
                                    this.Context,
                                    "Saving offset {0}",
                                    eventData.SystemProperties.Offset);

                                using (ITransaction tx = this.StateManager.CreateTransaction())
                                {
                                    await offsetDictionary.SetAsync(tx, "offset", eventData.SystemProperties.Offset);

                                    await tx.CommitAsync();
                                }

                                offsetIteration = 0;
                            }
                        }
                    }
                    catch (TimeoutException te)
                    {
                        // transient error. Retry.
                        ServiceEventSource.Current.ServiceMessage(this.Context, $"TimeoutException in RunAsync: {te.ToString()}");
                    }
                    catch (FabricTransientException fte)
                    {
                        // transient error. Retry.
                        ServiceEventSource.Current.ServiceMessage(this.Context, $"FabricTransientException in RunAsync: {fte.ToString()}");
                    }
                    catch (FabricNotPrimaryException)
                    {
                        // not primary any more, time to quit.
                        return;
                    }
                    catch (Exception ex)
                    {
                        ServiceEventSource.Current.ServiceMessage(this.Context, ex.ToString());

                        throw;
                    }
                }
            }
            finally
            {
                if (partitionReceiver != null)
                {
                    await partitionReceiver.CloseAsync();
                }
            }
        }
Пример #14
0
        //private static readonly HttpCommunicationClientFactory communicationFactory;

        static HomeController()
        {
            serviceUri = new Uri(FabricRuntime.GetActivationContext().ApplicationName + "/APIBackEnd");

            resolver = ServicePartitionResolver.GetDefault();
        }
        /// <summary>
        /// Processing answers from Simulator - Process Controller
        /// </summary>
        public void ProcessPCAnwers(TimeSpan timeout, CancellationToken token)
        {
            while (!token.IsCancellationRequested)
            {
                bool           isSuccessful;
                IORequestBlock answer = IORequests.DequeueAnswer(out isSuccessful, timeout);

                if (isSuccessful)
                {
                    bool isChange = false;
                    RTU  rtu;
                    // sporno
                    //while (!Database.IsConfigurationRunning)

                    if ((rtu = dbContext.GetRTUByName(answer.ProcessControllerName)) != null)
                    {
                        switch (rtu.Protocol)
                        {
                        case IndustryProtocols.ModbusTCP:

                            ModbusHandler mdbHandler = new ModbusHandler();
                            try
                            {
                                mdbHandler.UnpackData(answer.RcvBuff, answer.RcvMsgLength);
                                switch (mdbHandler.Response.FunCode)
                                {
                                case FunctionCodes.ReadDiscreteInput:
                                {
                                    BitReadResponse response        = (BitReadResponse)mdbHandler.Response;
                                    var             responsePVCount = answer.Flags;

                                    ushort varAddr = answer.ReqAddress;
                                    for (int i = 0; i < responsePVCount; i++, varAddr++)
                                    {
                                        ProcessVariable pv;

                                        if (rtu.GetProcessVariableByAddress(varAddr, out pv))
                                        {
                                            Digital target = (Digital)pv;

                                            try
                                            {
                                                bool isOpened = response.BitValues[i];
                                                if (target.State != target.ValidStates[isOpened ? 1 : 0])
                                                {
                                                    isChange     = true;
                                                    target.State = target.ValidStates[isOpened ? 1 : 0];
                                                    Console.WriteLine(" CHANGE! Digital variable {0}, state: {1}", target.Name, target.State);

                                                    IServicePartitionResolver partitionResolverToDMS = ServicePartitionResolver.GetDefault();
                                                    var wcfClientFactoryToDMS = new WcfCommunicationClientFactory <IDMSToSCADAContract>
                                                                                    (clientBinding: BindingForTCP.CreateCustomNetTcp(), servicePartitionResolver: partitionResolverToDMS);

                                                    DmsClientSF dMSClient = new DmsClientSF(
                                                        wcfClientFactoryToDMS,
                                                        new Uri("fabric:/ServiceFabricOMS/DMStatelessService"),
                                                        ServicePartitionKey.Singleton,
                                                        listenerName: "DMSServiceForSCADA"
                                                        );
                                                    dMSClient.InvokeWithRetry(c => c.Channel.ChangeOnSCADADigital(target.Name, target.State));
                                                }
                                            }
                                            catch (Exception e)
                                            {
                                                Console.WriteLine("Digital variable {0}, state: INVALID", target.Name);
                                            }
                                        }
                                    }
                                    if (isChange)
                                    {
                                        ScadaModelParser parser = new ScadaModelParser();
                                        parser.SerializeScadaModel();
                                    }
                                }

                                break;

                                // analog input
                                case FunctionCodes.ReadInputRegisters:
                                {
                                    RegisterReadResponse response = (RegisterReadResponse)mdbHandler.Response;
                                    var responsePVCount           = answer.Flags;

                                    ushort varAddr = answer.ReqAddress;
                                    for (int i = 0; i < responsePVCount; i++, varAddr++)
                                    {
                                        ProcessVariable pv;

                                        if (rtu.GetProcessVariableByAddress(varAddr, out pv))
                                        {
                                            Analog target = (Analog)pv;

                                            try
                                            {
                                                ushort newRawAcqValue = response.RegValues[target.RelativeAddress];
                                                float  newAcqValue;
                                                AnalogProcessor.RawValueToEGU(target, newRawAcqValue, out newAcqValue);

                                                if (target.AcqValue != newAcqValue)
                                                {
                                                    isChange = true;

                                                    target.RawAcqValue = newRawAcqValue;
                                                    target.AcqValue    = newAcqValue;
                                                    Console.WriteLine(" CHANGE! Analog variable {0}, AcqValue: {1}", target.Name, target.AcqValue);

                                                    //to do: propagacija analogih promena(ako se secate Pavlica je prvo rekao da nam to ne treba da samo jednom zakucamo vrednost na pocetku) xD
                                                    IServicePartitionResolver partitionResolverToDMS = ServicePartitionResolver.GetDefault();
                                                    var wcfClientFactoryToDMS = new WcfCommunicationClientFactory <IDMSToSCADAContract>
                                                                                    (clientBinding: BindingForTCP.CreateCustomNetTcp(), servicePartitionResolver: partitionResolverToDMS);

                                                    DmsClientSF dMSClient = new DmsClientSF(
                                                        wcfClientFactoryToDMS,
                                                        new Uri("fabric:/ServiceFabricOMS/DMStatelessService"),
                                                        ServicePartitionKey.Singleton,
                                                        listenerName: "DMSServiceForSCADA"
                                                        );
                                                    dMSClient.InvokeWithRetry(c => c.Channel.ChangeOnSCADAAnalog(target.Name, target.AcqValue));
                                                }
                                            }
                                            catch
                                            {
                                                // Console.WriteLine("Digital variable {0}, state: INVALID", target.Name);
                                            }
                                        }
                                    }
                                    if (isChange)
                                    {
                                        ScadaModelParser parser = new ScadaModelParser();
                                        parser.SerializeScadaModel();
                                    }
                                }

                                break;
                                }
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine(e.Message);
                            }
                            break;
                        }
                    }
                }
            }

            Console.WriteLine("ProcessPCAnswers.shutdown=true");
            return;
        }
Пример #16
0
        private static async Task Run(string[] args)
        {
            // The Fabric URI of the service.
            var serviceName     = new Uri("fabric:/DistributedJournalApp/DistributedJournalService");
            var serviceResolver = new ServicePartitionResolver(() => new FabricClient());

            var clientFactory = new WcfCommunicationClientFactory <IKeyValueStore>(
                serviceResolver,
                ServiceBindings.TcpBinding);

            var client = new ServicePartitionClient <WcfCommunicationClient <IKeyValueStore> >(
                clientFactory,
                serviceName,
                partitionKey: 0L);

            Console.WriteLine("Calling set");
            await Set(client, "test", 38);

            Console.WriteLine("Set complete, calling get");
            Console.WriteLine($"Got {await Get(client, "test")}");

            var numTasks  = args.Length == 0 ? 1 : int.Parse(args[0]);
            var tasks     = new Task[numTasks];
            var iteration = (long)0;

            // Initialize.
            for (var i = 0; i < tasks.Length; ++i)
            {
                await Set(client, i.ToString(), iteration);
            }

            var timer  = Stopwatch.StartNew();
            var paused = false;

            while (true)
            {
                var total = iteration * tasks.Length;
                if (!paused)
                {
                    for (var i = 0; i < tasks.Length; ++i)
                    {
                        tasks[i] = CheckAndIncrement(client, i.ToString(), iteration);
                    }

                    await Task.WhenAll(tasks);

                    if (iteration % 8000 == 0 && iteration > 0)
                    {
                        Console.WriteLine();
                    }

                    if (iteration % 100 == 0)
                    {
                        WriteProgress(iteration, timer, total);
                    }

                    iteration++;
                }

                // Process user input.
                if (Console.KeyAvailable || paused)
                {
                    var consoleKey = Console.ReadKey();
                    switch (consoleKey.Key)
                    {
                    case ConsoleKey.Escape:
                        return;

                    case ConsoleKey.D:
                        // Output debug data.
                        var prefix = $"{iteration}_";
                        await client.InvokeWithRetry(_ => _.Channel.DumpDebugData(DebugDumpDirectory, prefix));

                        break;

                    case ConsoleKey.P:
                        // Toggle pause
                        paused = !paused;
                        break;

                    case ConsoleKey.S:
                        WriteProgress(iteration, timer, total);
                        break;
                    }
                }
            }
        }
Пример #17
0
        private static async Task Run(string[] args)
        {
            // The Fabric URI of the service.
            var serviceName = new Uri("fabric:/DistributedJournalApp/DistributedJournalService");
            var serviceResolver = new ServicePartitionResolver(() => new FabricClient());

            var clientFactory = new WcfCommunicationClientFactory<IKeyValueStore>(
                serviceResolver,
                ServiceBindings.TcpBinding);

            var client = new ServicePartitionClient<WcfCommunicationClient<IKeyValueStore>>(
                clientFactory,
                serviceName,
                partitionKey: 0L);

            Console.WriteLine("Calling set");
            await Set(client, "test", 38);
            Console.WriteLine("Set complete, calling get");
            Console.WriteLine($"Got {await Get(client, "test")}");

            var numTasks = args.Length == 0 ? 1 : int.Parse(args[0]);
            var tasks = new Task[numTasks];
            var iteration = (long)0;

            // Initialize.
            for (var i = 0; i < tasks.Length; ++i)
            {
                await Set(client, i.ToString(), iteration);
            }

            var timer = Stopwatch.StartNew();
            var paused = false;
            while (true)
            {
                var total = iteration * tasks.Length;
                if (!paused)
                {
                    for (var i = 0; i < tasks.Length; ++i)
                    {
                        tasks[i] = CheckAndIncrement(client, i.ToString(), iteration);
                    }

                    await Task.WhenAll(tasks);

                    if (iteration % 8000 == 0 && iteration > 0)
                    {
                        Console.WriteLine();
                    }

                    if (iteration % 100 == 0)
                    {
                        WriteProgress(iteration, timer, total);
                    }
                    
                    iteration++;
                }

                // Process user input.
                if (Console.KeyAvailable || paused)
                {
                    var consoleKey = Console.ReadKey();
                    switch (consoleKey.Key)
                    {
                        case ConsoleKey.Escape:
                            return;
                        case ConsoleKey.D:
                            // Output debug data.
                            var prefix = $"{iteration}_";
                            await client.InvokeWithRetry(_ => _.Channel.DumpDebugData(DebugDumpDirectory, prefix));
                            break;
                        case ConsoleKey.P:
                            // Toggle pause
                            paused = !paused;
                            break;
                        case ConsoleKey.S:
                            WriteProgress(iteration, timer, total);
                            break;

                    }
                }
            }
        }
Пример #18
0
 public ServiceDiscoveryController(FabricClient fabricClient)
 {
     _servicePartitionResolver = ServicePartitionResolver.GetDefault();
     _fabricClient             = fabricClient ?? new FabricClient();
 }
Пример #19
0
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            // If the request is outside of the Fabric application, just pass through and do nothing
            if (!StringComparer.OrdinalIgnoreCase.Equals(request.RequestUri.Host, "fabric"))
            {
                return(await base.SendAsync(request, cancellationToken));
            }

            ResolvedServicePartition partition             = null;
            HttpServiceUriBuilder    uriBuilder            = new HttpServiceUriBuilder(request.RequestUri);
            var servicePartitionResolver                   = ServicePartitionResolver.GetDefault();
            NeedsResolveServiceEndpointException exception = null;
            int retries    = this.maxRetries;
            int retryDelay = this.initialRetryDelayMs;

            while (retries-- > 0)
            {
                cancellationToken.ThrowIfCancellationRequested();
                partition = partition != null ? await servicePartitionResolver.ResolveAsync(partition, cancellationToken)
                                              : await servicePartitionResolver.ResolveAsync(uriBuilder.ServiceName, uriBuilder.PartitionKey, cancellationToken);

                string serviceEndpointJson;
                switch (uriBuilder.Target)
                {
                case HttpServiceUriTarget.Primary:
                    serviceEndpointJson = partition.GetEndpoint().Address;
                    break;

                case HttpServiceUriTarget.Secondary:
                    serviceEndpointJson = this.GetRandomEndpointAddress(partition.Endpoints, 1);
                    break;

                case HttpServiceUriTarget.Any:
                default:
                    serviceEndpointJson = this.GetRandomEndpointAddress(partition.Endpoints, 0);
                    break;
                }
                string endpointUrl = JObject.Parse(serviceEndpointJson)["Endpoints"][uriBuilder.EndpointName].Value <string>();
                request.RequestUri = new Uri($"{endpointUrl.TrimEnd('/')}/{uriBuilder.ServicePathAndQuery.TrimStart('/')}", UriKind.Absolute);

                CancellationTokenSource cts = CancellationTokenSource.CreateLinkedTokenSource(new CancellationTokenSource(this.requestTimeoutMs).Token,
                                                                                              cancellationToken);
                try
                {
                    HttpResponseMessage response = await base.SendAsync(request, cts.Token);

                    return(response);
                }
                catch (NeedsResolveServiceEndpointException ex)
                {
                    exception = ex;
                    if (retries == 0)
                    {
                        break;
                    }
                }

                await Task.Delay(retryDelay);

                retryDelay += retryDelay;
            }

            if (exception.Response != null)
            {
                return(exception.Response);
            }
            else
            {
                throw exception.InnerException;
            }
        }
        public static async Task <IReadOnlyDictionary <String, String> > ResolveEndpointsAsync(this ServicePartitionResolver resolver, Uri namedService, ServicePartitionKey partitionKey, CancellationToken cancellationToken)
        {
            ResolvedServicePartition partition = await resolver.ResolveAsync(namedService, partitionKey, cancellationToken);

            return(DeserializeEndpoints(partition.GetEndpoint()));
        }
        public static async Task <String> ResolveEndpointAsync(this ServicePartitionResolver resolver, Uri namedService, ServicePartitionKey partitionKey, String endpointName, CancellationToken cancellationToken)
        {
            ResolvedServicePartition partition = await resolver.ResolveAsync(namedService, partitionKey, cancellationToken);

            return(DeserializeEndpoints(partition.GetEndpoint())[endpointName]);
        }
        private static async Task MainAsync()
        {
            Console.WriteLine("Waiting for services....");

            var proxyPartitionOne = await CreateProxyAsync(-1L);

            var proxyPartitionTwo = await CreateProxyAsync(1L);

            var proxy = proxyPartitionOne;

            Console.WriteLine("Waited for services..");


            while (true)
            {
                Console.WriteLine($"Press any key to continue");
                Console.ReadKey(true);
                Console.Clear();

                Console.WriteLine("Press 0 to select target partition");
                Console.WriteLine("Press 1 to get state");
                Console.WriteLine("Press 2 to set state");
                Console.WriteLine("Press 3 to create a backup");
                Console.WriteLine("Press 4 to restore a backup");
                Console.WriteLine("Press 5 to list all central backups");
                Console.WriteLine("Press 6 to list the current Service Partition Ids");
                Console.WriteLine("Press 7 to invoke full dataloss on one of the current Service's Partitions");
                Console.WriteLine("Other key to exit");

                var    key = Console.ReadKey(true);
                string input;

                switch (key.Key)
                {
                case ConsoleKey.D0:
                    Console.WriteLine("Type 1 for partition one, or 2 for partition two");
                    key = Console.ReadKey(true);
                    if (ConsoleKey.D2 == key.Key)
                    {
                        proxy = proxyPartitionTwo;
                        Console.WriteLine("Using partition two.");
                    }
                    else
                    {
                        proxy = proxyPartitionOne;
                        Console.WriteLine("Using partition one.");
                    }
                    break;

                case ConsoleKey.D1:
                    string state = await proxy.GetState();

                    Console.WriteLine($"State: '{state}'");
                    break;

                case ConsoleKey.D2:
                    Console.WriteLine("Enter string to store as state:");
                    input = Console.ReadLine();
                    await proxy.SetState(input ?? "");

                    Console.WriteLine($"State saved: '{input}'");
                    break;

                case ConsoleKey.D3:
                    Console.WriteLine("Type 1 for full backup or 2 for incremental backup (incremental requires full backup to exist)");
                    key = Console.ReadKey(true);
                    if (ConsoleKey.D1 == key.Key)
                    {
                        Console.WriteLine("Creating a full backup asynchronously...");
                        await proxy.BeginCreateBackup(BackupOption.Full);
                    }
                    else
                    {
                        Console.WriteLine("Creating an incremental backup asynchronously...");
                        await proxy.BeginCreateBackup(BackupOption.Incremental);
                    }

                    break;

                case ConsoleKey.D4:
                    Console.WriteLine($"Starting the restore of a backup");
                    Console.WriteLine($"Enter central backup id (guid):");
                    input = Console.ReadLine();

                    var  backups = (await proxy.ListAllBackups()).ToList();
                    Guid index;
                    if (Guid.TryParse(input, out index))
                    {
                        DataLossMode lossMode = DataLossMode.FullDataLoss;
                        Console.WriteLine("Type 1 for full data loss or 2 for partial data loss.");

                        key = Console.ReadKey(true);
                        if (ConsoleKey.D1 == key.Key)
                        {
                            Console.WriteLine("Restoring backup with full data loss asynchronously...");
                        }
                        else
                        {
                            Console.WriteLine("Restoring backup with partial data loss asynchronously...");
                            lossMode = DataLossMode.PartialDataLoss;
                        }

                        await proxy.BeginRestoreBackup(backups.Single(b => b.BackupId == index), lossMode);

                        Console.WriteLine($"Restore is active. This will take some time. Check progress in SF explorer.");
                    }

                    break;

                case ConsoleKey.D5:
                    Console.WriteLine($"List all central backups");
                    var list = await proxy.ListAllBackups();

                    Console.WriteLine($"Original partition\t\t\tBackup Id\t\t\t\tBackup Type\tTimestamp UTC");
                    Console.WriteLine(string.Join(Environment.NewLine, list.Select(data => $"{data.OriginalServicePartitionId}\t{data.BackupId}\t{data.BackupOption}\t\t{data.TimeStampUtc}")));
                    break;

                case ConsoleKey.D6:
                    var resolver = ServicePartitionResolver.GetDefault();
                    var resolved = await resolver.ResolveAsync(ServiceUri, new ServicePartitionKey(-1L), CancellationToken.None);

                    Console.WriteLine($"Partition key -1L resolves to partition {resolved.Info.Id}");
                    resolved = await resolver.ResolveAsync(ServiceUri, new ServicePartitionKey(1L), CancellationToken.None);

                    Console.WriteLine($"Partition key 1L resolves to partition {resolved.Info.Id}");

                    if (proxy == proxyPartitionOne)
                    {
                        Console.WriteLine("Using partition one (-1L)");
                    }
                    else
                    {
                        Console.WriteLine("Using partition two (1L)");
                    }
                    break;

                case ConsoleKey.D7:
                    Console.WriteLine("Enter partitionID");
                    string partitionString = Console.ReadLine();
                    if (Guid.TryParse(partitionString, out Guid partitionID))
                    {
                        var partitionSelector = PartitionSelector.PartitionIdOf(ServiceUri, partitionID);
                        await new FabricClient(FabricClientRole.Admin).TestManager.StartPartitionDataLossAsync(Guid.NewGuid(), partitionSelector, DataLossMode.FullDataLoss);
                    }
                    break;

                default:
                    return;
                }
            }
        }
Пример #23
0
        public static async Task <ResolvedServicePartition> ResolvedServicePartition(HttpContext context,
                                                                                     IdentityModel identity, RouteInfo validRoute, ServicePartitionResolver resolver)
        {
            var partitionKey = identity.OrganizationPrefix;
            var resolvedKey  = PartitionResolver.Resolve(partitionKey);

            var servicePartitionKey = validRoute.IsPartitioned
                ? new ServicePartitionKey(resolvedKey)
                : ServicePartitionKey.Singleton;

            var resolved = await resolver
                           .ResolveAsync(new Uri(validRoute.ServiceUri), servicePartitionKey,
                                         context.RequestAborted)
                           .ConfigureAwait(false);

            return(resolved);
        }
 /// <summary>
 /// Creates a new instance, using the provided <see cref="ServicePartitionResolver"/> and Service Bus Topic name.
 /// </summary>
 /// <param name="resolver"></param>
 /// <param name="topicName"></param>
 public ServiceBusTopicCommunicationClientFactory(ServicePartitionResolver resolver, string topicName)
     : base(resolver)
 {
     _topicName = topicName;
 }
Пример #25
0
 public ServiceFabricClientBase(ServicePartitionResolver resolver, Uri address) : base(new WcfCommunicationClientFactory <I>(servicePartitionResolver: resolver), address, listenerName: typeof(I).Name)
 {
 }
 /// <summary>
 /// Creates a new instance, using the provided <see cref="ServicePartitionResolver"/> and Service Bus Queue name.
 /// </summary>
 /// <param name="resolver"></param>
 /// <param name="queueName"></param>
 public ServiceBusQueueCommunicationClientFactory(ServicePartitionResolver resolver, string queueName)
     : base(resolver)
 {
     _queueName = queueName;
 }
Пример #27
0
        /// <summary>
        /// Gets a ResolvedServiceEndpoing for the specified service and partition.
        /// </summary>
        /// <param name="service">ServiceName URI. </param>
        /// <param name="partition">Partition instance of the service.</param>
        /// <returns>ResolvedServiceEndpoint instance if found, otherwise null.</returns>
        internal async Task <ResolvedServiceEndpoint> GetServiceEndpointAsync(Uri service, Partition partition)
        {
            // Check passed parameters.
            if (null == service)
            {
                throw new ArgumentNullException(nameof(service));
            }
            if (null == partition)
            {
                throw new ArgumentNullException(nameof(partition));
            }

            ServiceEventSource.Current.Write(nameof(GetServiceEndpointAsync), $"Service: {service.AbsoluteUri} Partition: {partition}.");

            try
            {
                ServicePartitionKey key = null;

                // Get the partition key based on the partition type of the service.
                if (partition.PartitionInformation.Kind == ServicePartitionKind.Singleton)
                {
                    key = new ServicePartitionKey();
                }
                else if (partition.PartitionInformation.Kind == ServicePartitionKind.Int64Range)
                {
                    // Choose the LowKey as the partition value to look up.
                    key = new ServicePartitionKey(((Int64RangePartitionInformation)partition.PartitionInformation).LowKey);
                }
                else if (partition.PartitionInformation.Kind == ServicePartitionKind.Named)
                {
                    key = new ServicePartitionKey(((NamedPartitionInformation)partition.PartitionInformation).Name);
                }
                else
                {
                    string msg = $"Invalid PartitionKind '{Enum.GetName(typeof(ServicePartitionKind), partition.PartitionInformation.Kind)}'.";
                    ServiceEventSource.Current.Error(nameof(GetServiceEndpointAsync), msg);
                    throw new InvalidProgramException(msg);
                }

                // Resolve the partition, then enumerate the endpoints looking for the primary or stateless role.
                ResolvedServicePartition rsp = await ServicePartitionResolver.GetDefault().ResolveAsync(service, key, this._token);

                foreach (ResolvedServiceEndpoint ep in rsp.Endpoints)
                {
                    if ((ServiceEndpointRole.StatefulPrimary == ep.Role) || (ServiceEndpointRole.Stateless == ep.Role))
                    {
                        ServiceEventSource.Current.Write($"{nameof(GetServiceEndpointAsync)} returning {ep.Address}.");
                        return(ep);
                    }
                }

                //TODO: ServiceEventSource.Current.Trace($"{nameof(GetServiceEndpointAsync)} no endpoint was found, returning null.");
                ServiceEventSource.Current.Message($"{nameof(GetServiceEndpointAsync)} no endpoint was found, returning null.");
                return(null);
            }
            catch (Exception ex)
            {
                //TODO: ServiceEventSource.Current.Exception(ex.Message, ex.GetType().Name, nameof(GetServiceEndpointAsync));
                ServiceEventSource.Current.Message(ex.Message + ex.GetType().Name + nameof(GetServiceEndpointAsync));

                throw;
            }
        }
 /// <summary>
 /// Optional override to create listeners (like tcp, http) for this service instance.
 /// </summary>
 /// <returns>The collection of listeners.</returns>
 protected override IEnumerable <ServiceInstanceListener> CreateServiceInstanceListeners()
 {
     // TODO: If your service needs to handle user requests, return a list of ServiceReplicaListeners here.
     this.servicePartitionResolver = ServicePartitionResolver.GetDefault();
     return(new[] { new ServiceInstanceListener((initParams) => new HttpCommunicationListener(initParams, this.ProcessInputRequest)) });
 }
Пример #29
0
        static void Main(string[] args)
        {
            //ChannelFactory<IIMSContract> factoryToIMS = new ChannelFactory<IIMSContract>(new NetTcpBinding(), new EndpointAddress("net.tcp://localhost:6090/IncidentManagementSystemService"));
            //IIMSContract IMSClient = factoryToIMS.CreateChannel();

            ChannelFactory <IOMSClient> factoryToTMS = new ChannelFactory <IOMSClient>(new NetTcpBinding(), new EndpointAddress("net.tcp://localhost:6080/TransactionManagerService"));
            IOMSClient proxyToTransactionManager     = factoryToTMS.CreateChannel();

            while (true)
            {
                printMeni();
                string odg = Console.ReadLine();
                if (odg == "1")
                {
                    Console.WriteLine("MrID:");
                    string mrid = Console.ReadLine();
                    Console.WriteLine("State:");
                    string state = Console.ReadLine();
                    //proxyToTransactionManager.AddReport(mrid, DateTime.UtcNow, state);
                }
                else if (odg == "2")
                {
                    printMeni2();
                    string odg2 = Console.ReadLine();
                    List <ElementStateReport> reports = new List <ElementStateReport>(); // = IMSClient.GetAllReports();
                    if (odg2 == "1")
                    {
                        reports = proxyToTransactionManager.GetAllElementStateReports();
                    }
                    else if (odg2 == "2")
                    {
                        Console.WriteLine("Unesite MrID:");
                        string mrid2 = Console.ReadLine();
                        //  reports = proxyToTransactionManager.GetElementStateReportsForMrID(mrid2);
                    }
                    else if (odg2 == "3")
                    {
                        Console.WriteLine("Unesite vremenski interval u obliku godina-mjesec-dan sat:minut:sekund:");
                        Console.WriteLine("StartTime:");
                        string   startTime     = Console.ReadLine();
                        DateTime startDateTime = DateTime.Parse(startTime);
                        Console.WriteLine("EndTime:");
                        string   endTime     = Console.ReadLine();
                        DateTime endDateTime = DateTime.Parse(endTime);
                        reports = proxyToTransactionManager.GetElementStateReportsForSpecificTimeInterval(startDateTime, endDateTime);
                    }
                    else if (odg2 == "4")
                    {
                        Console.WriteLine("Unesite MrID:");
                        string mrid3 = Console.ReadLine();
                        Console.WriteLine("Unesite vremenski interval u obliku godina-mjesec-dan sat:minut:sekund:");
                        Console.WriteLine("StartTime:");
                        string   startTime2     = Console.ReadLine();
                        DateTime startDateTime2 = DateTime.Parse(startTime2);
                        Console.WriteLine("EndTime:");
                        string   endTime2     = Console.ReadLine();
                        DateTime endDateTime2 = DateTime.Parse(endTime2);
                        reports = proxyToTransactionManager.GetElementStateReportsForSpecificMrIDAndSpecificTimeInterval(mrid3, startDateTime2, endDateTime2);
                    }
                    else if (odg2 == "5")
                    {
                        List <Crew> crews = proxyToTransactionManager.GetCrews();
                        foreach (Crew cr in crews)
                        {
                            Console.WriteLine("Crew: " + cr.CrewName);
                        }
                    }
                    // reports = IMSClient.GetAllReports();
                    foreach (ElementStateReport ir in reports)
                    {
                        Console.WriteLine("MrID: " + ir.MrID + ", State:" + ir.State + ", DateTime: " + ir.Time.ToUniversalTime());
                    }
                }
                else if (odg == "3")
                {
                    Console.WriteLine("Unesite ime ekipe:");
                    string ekipa = Console.ReadLine();
                    Console.WriteLine("Unesite id ekipe:");
                    string id   = Console.ReadLine();
                    Crew   crew = new Crew();
                    crew.Id       = id;
                    crew.CrewName = ekipa;

                    proxyToTransactionManager.AddCrew(crew);
                }
                else if (odg == "4")
                {
                    NetTcpBinding binding = new NetTcpBinding();
                    // Create a partition resolver
                    IServicePartitionResolver partitionResolver = ServicePartitionResolver.GetDefault();
                    // create a  WcfCommunicationClientFactory object.
                    var wcfClientFactory = new WcfCommunicationClientFactory <IOMSClient>
                                               (clientBinding: binding, servicePartitionResolver: partitionResolver);

                    //
                    // Create a client for communicating with the ICalculator service that has been created with the
                    // Singleton partition scheme.
                    //
                    var ServiceCommunicationClient = new WCFIMSClient(
                        wcfClientFactory,
                        new Uri("fabric:/ServiceFabricOMS/TMStatelessService"),
                        ServicePartitionKey.Singleton);

                    Delta d = new Delta();
                    ServiceCommunicationClient.InvokeWithRetry(client => client.Channel.UpdateSystem(d));
                    Console.ReadLine();
                }
                else if (odg == "5")
                {
                    NetTcpBinding binding = new NetTcpBinding();
                    // Create a partition resolver
                    IServicePartitionResolver partitionResolver = ServicePartitionResolver.GetDefault();
                    // create a  WcfCommunicationClientFactory object.
                    var wcfClientFactory = new WcfCommunicationClientFactory <IIMSContract>
                                               (clientBinding: binding, servicePartitionResolver: partitionResolver);

                    //
                    // Create a client for communicating with the ICalculator service that has been created with the
                    // Singleton partition scheme.
                    //
                    var ServiceCommunicationClient = new IncidentClient(
                        wcfClientFactory,
                        new Uri("fabric:/ServiceFabricOMS/IMStatelessService"),
                        ServicePartitionKey.Singleton);

                    List <Crew> crews = ServiceCommunicationClient.InvokeWithRetry(client => client.Channel.GetCrews());
                    Console.WriteLine("Procitao:\n");
                    foreach (Crew c in crews)
                    {
                        Console.WriteLine("Crew name: " + c.CrewName + ", Crew Type: " + c.Type);
                    }
                    Console.ReadLine();
                }
                else
                {
                    break;
                }
            }
        }
Пример #30
0
        public SimulationSchedulerController(IHistoryRepository historyRepository)
        {
            this.HistoryRepository = historyRepository;

            _CommunicationFactory = new HttpCommunicationClientFactory(ServicePartitionResolver.GetDefault());
        }
Пример #31
0
 public ProcessorServiceCommunicationClientFactory(ServicePartitionResolver resolver = null)
     : base(resolver, new[] { new ProcessorServiceExceptionHandler() })
 {
 }
        /// <summary>
        /// http://fabric/app/service/#/partitionkey/any|primary|secondary/endpoint-name/api-path
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            ServicePartitionResolver resolver   = ServicePartitionResolver.GetDefault();
            ResolvedServicePartition partition  = null;
            HttpServiceUriBuilder    uriBuilder = new HttpServiceUriBuilder(request.RequestUri);

            int  retries        = MaxRetries;
            int  retryDelay     = InitialRetryDelayMs;
            bool resolveAddress = true;

            HttpResponseMessage lastResponse  = null;
            Exception           lastException = null;

            while (retries-- > 0)
            {
                lastResponse = null;
                cancellationToken.ThrowIfCancellationRequested();

                if (resolveAddress)
                {
                    partition = partition != null
                        ? await resolver.ResolveAsync(partition, cancellationToken)
                        : await resolver.ResolveAsync(uriBuilder.ServiceName, uriBuilder.PartitionKey, cancellationToken);

                    string serviceEndpointJson;

                    switch (uriBuilder.Target)
                    {
                    case HttpServiceUriTarget.Default:
                    case HttpServiceUriTarget.Primary:
                        serviceEndpointJson = partition.GetEndpoint().Address;
                        break;

                    case HttpServiceUriTarget.Secondary:
                        serviceEndpointJson = partition.Endpoints.ElementAt(this.random.Next(1, partition.Endpoints.Count)).Address;
                        break;

                    case HttpServiceUriTarget.Any:
                    default:
                        serviceEndpointJson = partition.Endpoints.ElementAt(this.random.Next(0, partition.Endpoints.Count)).Address;
                        break;
                    }

                    string endpointUrl = JObject.Parse(serviceEndpointJson)["Endpoints"][uriBuilder.EndpointName].Value <string>();

                    request.RequestUri = new Uri($"{endpointUrl.TrimEnd('/')}/{uriBuilder.ServicePathAndQuery.TrimStart('/')}", UriKind.Absolute);
                }

                try
                {
                    lastResponse = await base.SendAsync(request, cancellationToken);

                    if (lastResponse.StatusCode == HttpStatusCode.NotFound ||
                        lastResponse.StatusCode == HttpStatusCode.ServiceUnavailable)
                    {
                        resolveAddress = true;
                    }
                    else
                    {
                        return(lastResponse);
                    }
                }
                catch (TimeoutException te)
                {
                    lastException  = te;
                    resolveAddress = true;
                }
                catch (SocketException se)
                {
                    lastException  = se;
                    resolveAddress = true;
                }
                catch (HttpRequestException hre)
                {
                    lastException  = hre;
                    resolveAddress = true;
                }
                catch (Exception ex)
                {
                    lastException = ex;
                    WebException we = ex as WebException;

                    if (we == null)
                    {
                        we = ex.InnerException as WebException;
                    }

                    if (we != null)
                    {
                        HttpWebResponse errorResponse = we.Response as HttpWebResponse;

                        // the following assumes port sharing
                        // where a port is shared by multiple replicas within a host process using a single web host (e.g., http.sys).
                        if (we.Status == WebExceptionStatus.ProtocolError)
                        {
                            if (errorResponse.StatusCode == HttpStatusCode.NotFound ||
                                errorResponse.StatusCode == HttpStatusCode.ServiceUnavailable)
                            {
                                // This could either mean we requested an endpoint that does not exist in the service API (a user error)
                                // or the address that was resolved by fabric client is stale (transient runtime error) in which we should re-resolve.
                                resolveAddress = true;
                            }

                            // On any other HTTP status codes, re-throw the exception to the caller.
                            throw;
                        }

                        if (we.Status == WebExceptionStatus.Timeout ||
                            we.Status == WebExceptionStatus.RequestCanceled ||
                            we.Status == WebExceptionStatus.ConnectionClosed ||
                            we.Status == WebExceptionStatus.ConnectFailure)
                        {
                            resolveAddress = true;
                        }
                    }
                    else
                    {
                        throw;
                    }
                }

                await Task.Delay(retryDelay);

                retryDelay += retryDelay;
            }

            if (lastResponse != null)
            {
                return(lastResponse);
            }
            else
            {
                throw lastException;
            }
        }
        private async Task <IInsightRuntime> CreateRunTimeAsync(ClusterAnalysisConfiguration configuration, CancellationToken token)
        {
            this.logger.LogMessage("CreateRunTimeAsync:: Entering");

            IInsightRuntime runtime;
            var             isOneBox = await this.IsCurrentDeploymentOneboxAsync(token).ConfigureAwait(false);

            if (isOneBox)
            {
                var config = this.CreateOneBoxConfig(configuration);
                this.logger.LogMessage("OneBoxConfig: {0}", config);

                runtime = DefaultInsightRuntime.GetInstance(
                    ClusterAnalysisLogProvider.LogProvider,
                    PersistentStoreProvider.GetStateProvider(this.stateManager),
                    config,
                    new PerformanceSessionManager(ClusterAnalysisLogProvider.LogProvider, token),
                    new TaskRunner(ClusterAnalysisLogProvider.LogProvider, this.OnUnhandledExceptionInAnalysisAsync),
                    token);

                this.AddServiceToRuntime(runtime, typeof(FabricClient), this.fabricClient);
                this.AddServiceToRuntime(runtime, typeof(IClusterQuery), ClusterQuery.CreateClusterQueryInstance(runtime));
                this.AddServiceToRuntime(runtime, typeof(IResolveServiceEndpoint), new ResolveServiceEndpoint(ServicePartitionResolver.GetDefault()));

                var localStoreConnection = new LocalTraceStoreConnectionInformation(
                    runtime.GetCurrentConfig().RuntimeContext.FabricDataRoot,
                    runtime.GetCurrentConfig().RuntimeContext.FabricLogRoot,
                    runtime.GetCurrentConfig().RuntimeContext.FabricCodePath);

                this.AddServiceToRuntime(
                    runtime,
                    typeof(TraceStoreConnectionInformation),
                    localStoreConnection);
            }
            else
            {
                this.logger.LogMessage("CreateRunTimeAsync:: Only One-Box deployment supported currently");
                throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, "Cluster Analysis is only supported on One-Box deployment for Preview."));
            }

            return(runtime);
        }
 /// <summary>
 /// Creates a client connection for the specified fabric address (beginning with fabric:/)
 /// </summary>
 /// <param name="fabricAddress"></param>
 public FabricClientConnection(Uri fabricAddress)
     : this(fabricAddress, ServicePartitionResolver.GetDefault())
 {
 }
 public ProcessorServiceCommunicationClientFactory(ServicePartitionResolver resolver, TimeSpan operationTimeout, TimeSpan readWriteTimeout)
     : base(resolver, null, null)
 {
     this.OperationTimeout = operationTimeout;
     this.ReadWriteTimeout = readWriteTimeout;
 }
 /// <summary>
 /// Creates the default <see cref="HttpCommunicationClientFactory"/> instance.
 /// </summary>
 /// <returns></returns>
 static HttpCommunicationClientFactory CreateDefault()
 {
     return(new HttpCommunicationClientFactory(ServicePartitionResolver.GetDefault()));
 }
Пример #37
0
 /// <summary>
 /// Create an instance of <see cref="ResolveServiceEndpoint"/>
 /// </summary>
 /// <param name="resolver"></param>
 public ResolveServiceEndpoint(ServicePartitionResolver resolver)
 {
     this.partitionResolver = resolver;
 }