protected override async Task RunAsync(CancellationToken cancellationToken)
        {
            ConfigurationSettings configSettings = FabricRuntime.GetActivationContext().GetConfigurationPackageObject("Config").Settings;
            KeyedCollection <string, ConfigurationProperty> serviceParameters = configSettings.Sections["HealthMetrics.BandCreationService.Settings"].Parameters;

            this.NumberOfCreationThreads            = int.Parse(serviceParameters["NumberOfCreationThreads"].Value);
            this.MaxBandsToCreatePerServiceInstance = int.Parse(serviceParameters["MaxBandsToCreatePerServiceInstance"].Value);
            this.ActorServiceUri     = new ServiceUriBuilder(serviceParameters["BandActorServiceName"].Value).ToUri();
            this.DoctorServiceUri    = new ServiceUriBuilder(serviceParameters["DoctorActorServiceName"].Value).ToUri();
            this.GenerateKnownPeople = bool.Parse(serviceParameters["GenerateKnownPeople"].Value);

            string             dataPath = FabricRuntime.GetActivationContext().GetDataPackageObject("Data").Path;
            BandActorGenerator bag      = new BandActorGenerator(configSettings, dataPath);

            bag.Prepare();

            ServicePrimer primer = new ServicePrimer();
            await primer.WaitForStatefulService(this.ActorServiceUri, cancellationToken);

            List <Task> tasks = new List <Task>();

            if (this.GenerateKnownPeople)
            {
                bool verify = bool.Parse(serviceParameters["VerifyKnownPeople"].Value);
                tasks.Add(Task.Run(() => this.CreateKnownActors(bag, configSettings, cancellationToken, verify)));
            }

            for (int i = 0; i < this.NumberOfCreationThreads; i++)
            {
                tasks.Add(Task.Run(() => this.CreateBandActorTask(bag, cancellationToken), cancellationToken));
            }

            ServiceEventSource.Current.ServiceMessage(this, "Band Creation has begun.");
            await Task.WhenAll(tasks);

            ServiceEventSource.Current.ServiceMessage(this, "Band Creation has completed.");
        }
示例#2
0
        protected override async Task RunAsync(CancellationToken cancellationToken)
        {
            ConfigurationPackage configPackage = this.Context.CodePackageActivationContext.GetConfigurationPackageObject("Config");

            this.UpdateConfigSettings(configPackage.Settings);

            this.Context.CodePackageActivationContext.ConfigurationPackageModifiedEvent
                += this.CodePackageActivationContext_ConfigurationPackageModifiedEvent;

            this.indexCalculator = new HealthIndexCalculator(this.Context);

            ServicePrimer primer = new ServicePrimer();
            await primer.WaitForStatefulService(this.nationalServiceInstanceUri);

            IReliableDictionary <int, string> countyNamesDictionary =
                await this.StateManager.GetOrAddAsync <IReliableDictionary <int, string> >(CountyNameDictionaryName);

            ServiceEventSource.Current.ServiceMessage(this, "CountyService starting data processing.");
            while (!cancellationToken.IsCancellationRequested)
            {
                try
                {
                    //every ten seconds, grab the counties and send them to national
                    await Task.Delay(this.interval, cancellationToken);

                    ServicePartitionClient <HttpCommunicationClient> servicePartitionClient =
                        new ServicePartitionClient <HttpCommunicationClient>(
                            this.clientFactory,
                            this.nationalServiceInstanceUri);

                    IList <KeyValuePair <int, string> > countyNames = new List <KeyValuePair <int, string> >();

                    using (ITransaction tx = this.StateManager.CreateTransaction())
                    {
                        IAsyncEnumerator <KeyValuePair <int, string> > enumerator = (await countyNamesDictionary.CreateEnumerableAsync(tx)).GetAsyncEnumerator();

                        while (await enumerator.MoveNextAsync(cancellationToken))
                        {
                            countyNames.Add(enumerator.Current);
                        }
                    }

                    foreach (KeyValuePair <int, string> county in countyNames)
                    {
                        IReliableDictionary <Guid, CountyDoctorStats> countyHealth =
                            await
                            this.StateManager.GetOrAddAsync <IReliableDictionary <Guid, CountyDoctorStats> >(
                                string.Format(CountyHealthDictionaryName, county.Key));

                        int totalDoctorCount       = 0;
                        int totalPatientCount      = 0;
                        int totalHealthReportCount = 0;
                        int avgHealth = 0;

                        using (ITransaction tx = this.StateManager.CreateTransaction())
                        {
                            IAsyncEnumerable <KeyValuePair <Guid, CountyDoctorStats> > healthRecords = await countyHealth.CreateEnumerableAsync(tx);

                            IAsyncEnumerator <KeyValuePair <Guid, CountyDoctorStats> > enumerator = healthRecords.GetAsyncEnumerator();

                            IList <KeyValuePair <Guid, CountyDoctorStats> > records = new List <KeyValuePair <Guid, CountyDoctorStats> >();

                            while (await enumerator.MoveNextAsync(cancellationToken))
                            {
                                records.Add(enumerator.Current);
                            }

                            avgHealth = this.indexCalculator.ComputeAverageIndex(records.Select(x => x.Value.AverageHealthIndex));

                            foreach (KeyValuePair <Guid, CountyDoctorStats> item in records)
                            {
                                totalDoctorCount++;
                                totalPatientCount      += item.Value.PatientCount;
                                totalHealthReportCount += item.Value.HealthReportCount;
                            }
                        }

                        CountyStatsViewModel payload = new CountyStatsViewModel(totalDoctorCount, totalPatientCount, totalHealthReportCount, avgHealth);

                        await servicePartitionClient.InvokeWithRetryAsync(
                            client =>
                        {
                            Uri serviceAddress = new Uri(client.BaseAddress, string.Format("national/health/{0}", county.Key));

                            HttpWebRequest request   = WebRequest.CreateHttp(serviceAddress);
                            request.Method           = "POST";
                            request.ContentType      = "application/json";
                            request.Timeout          = (int)client.OperationTimeout.TotalMilliseconds;
                            request.ReadWriteTimeout = (int)client.ReadWriteTimeout.TotalMilliseconds;

                            using (Stream requestStream = request.GetRequestStream())
                            {
                                using (BufferedStream buffer = new BufferedStream(requestStream))
                                {
                                    using (StreamWriter writer = new StreamWriter(buffer))
                                    {
                                        JsonSerializer serializer = new JsonSerializer();
                                        serializer.Serialize(writer, payload);
                                        buffer.Flush();
                                    }

                                    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                                    {
                                        ServiceEventSource.Current.ServiceMessage(this, "County Data Sent {0}", serviceAddress);
                                        return(Task.FromResult(true));
                                    }
                                }
                            }
                        },
                            cancellationToken);
                    }
                }
                catch (TaskCanceledException)
                {
                    throw;
                }
                catch (Exception exception)
                {
                    ServiceEventSource.Current.ServiceMessage(
                        this,
                        "CountyService encountered an exception trying to send data to National Service: {0}",
                        exception.ToString());
                    continue;
                }
            }
        }