public CountyService(StatefulServiceContext serviceContext, IReliableStateManagerReplica reliableStateManagerReplica) : base(serviceContext, reliableStateManagerReplica) { InitConfig(); this.StateManager.TryAddStateSerializer <CountyDoctorStats>(new CountyDoctorStatsSerializer()); this.indexCalculator = new HealthIndexCalculator(serviceContext); }
public async Task <BandDataViewModel> GetBandDataAsync() { try { ConditionalValue <BandActorState> BandActorStateResult = await this.StateManager.TryGetStateAsync <BandActorState>("BandActorState"); if (BandActorStateResult.HasValue) { BandActorState state = BandActorStateResult.Value; HealthIndexCalculator ic = this.indexCalculator; HealthIndex hi = state.HealthIndex; int healthIndex = ic.ComputeIndex(hi); return(new BandDataViewModel( state.DoctorId, this.Id.GetGuidId(), state.PatientName, state.CountyInfo, healthIndex, state.HeartRateHistory)); } } catch (Exception e) { throw new ArgumentException(string.Format("Exception inside band actor {0}|{1}|{2}", this.Id, this.Id.Kind, e)); } throw new ArgumentException(string.Format("No band actor state {0}|{1}|{2}", this.Id, this.Id.Kind)); }
public DoctorService(StatefulServiceContext context) : base(context) { this.indexCalculator = new HealthIndexCalculator(context); this.scr = new ServiceConfigReader("Config"); ServiceUriBuilder serviceUriBuilder = new ServiceUriBuilder(this.scr["DataAggregation.DoctorService.Settings"]["CountyServiceInstanceName"]); this.CountyServiceUri = serviceUriBuilder.ToUri(); this.StateManager.TryAddStateSerializer <DoctorCreationRecord>(new DoctorCreationRecordSerializer()); this.StateManager.TryAddStateSerializer <PatientRegistrationRecord>(new PatientRegistrationRecordSerializer()); }
protected override Task OnActivateAsync() { ConfigurationPackage configPackage = this.ActorService.Context.CodePackageActivationContext.GetConfigurationPackageObject("Config"); this.indexCalculator = new HealthIndexCalculator(this.ActorService.Context); this.UpdateConfigSettings(configPackage.Settings); this.ActorService.Context.CodePackageActivationContext.ConfigurationPackageModifiedEvent += this.CodePackageActivationContext_ConfigurationPackageModifiedEvent; ActorEventSource.Current.ActorMessage(this, "Band activated. ID: {0}", this.Id); return(Task.FromResult(true)); }
private async Task CreateKnownActors(BandActorGenerator bag, ConfigurationSettings settings, CancellationToken cancellationToken, bool verify) { CryptoRandom random = new CryptoRandom(); FabricClient fc = new FabricClient(); HealthIndexCalculator hic = new HealthIndexCalculator(this.Context); KeyedCollection <string, ConfigurationProperty> serviceParameters = settings.Sections["HealthMetrics.BandCreationService.Settings"].Parameters; while (!cancellationToken.IsCancellationRequested) { ActorId bandActorId; ActorId doctorActorId; int randomCountyId = -1; string doctorName = null; randomCountyId = int.Parse(serviceParameters["KnownCountyIdIndex"].Value); //(2968 is King, WA) || (2231 is Multnomah, OR) || (1870 is St. Lawrence, NY) doctorName = serviceParameters["KnownDoctorName"].Value; CountyRecord randomCountyRecord = bag.doctorsPerCounty.Keys.ElementAt(randomCountyId); BandInfo bandActorInfo = bag.GetRandomHealthStatus(randomCountyRecord, random); try { bandActorInfo.PersonName = serviceParameters["KnownPatientName"].Value; bandActorId = new ActorId(new Guid(serviceParameters["KnownPatientId"].Value)); bandActorInfo.DoctorId = new Guid(serviceParameters["KnownDoctorId"].Value); doctorActorId = new ActorId(bandActorInfo.DoctorId); bag.doctorsPerCounty[bag.doctorsPerCounty.Keys.ElementAt(randomCountyId)].Add(bandActorInfo.DoctorId); IDoctorActor docActor = ActorProxy.Create <IDoctorActor>(doctorActorId, this.DoctorServiceUri); await docActor.NewAsync(doctorName, randomCountyRecord); IBandActor bandActor = ActorProxy.Create <IBandActor>(bandActorId, this.ActorServiceUri); await bandActor.NewAsync(bandActorInfo); if (verify) { await VerifyActors(hic, bandActorId, doctorName, randomCountyRecord, bandActorInfo, docActor, bandActor); break; } await Task.Delay(TimeSpan.FromMinutes(1), cancellationToken); } catch (Exception e) { ServiceEventSource.Current.ServiceMessage(this, "Exception when creating actor {0}", e.ToString()); } } }
private static async Task VerifyActors( HealthIndexCalculator hic, ActorId bandActorId, string doctorName, CountyRecord randomCountyRecord, BandInfo bandActorInfo, IDoctorActor docActor, IBandActor bandActor) { while (true) { BandDataViewModel view = await bandActor.GetBandDataAsync(); if (view.PersonName == bandActorInfo.PersonName) { if (view.CountyInfo == bandActorInfo.CountyInfo) { if (view.DoctorId == bandActorInfo.DoctorId) { if (view.PersonId == bandActorId.GetGuidId()) { if (hic.ComputeIndex(bandActorInfo.HealthIndex) == view.HealthIndex) { break; } else { await bandActor.NewAsync(bandActorInfo); await Task.Delay(100); } } } } } } while (true) { Tuple <CountyRecord, string> info = await docActor.GetInfoAndNameAsync(); if (info.Item2 == String.Format("Dr. {0}", doctorName) && info.Item1 == randomCountyRecord) { break; } else { await docActor.NewAsync(doctorName, randomCountyRecord); await Task.Delay(100); } } }
public async Task <DeviceDataViewModel> GetDeviceDataAsync() { try { //check to see if the patient name is set //if not this actor object hasn't been initialized //and we can skip the rest of the checks ConditionalValue <string> PatientInfoResult = await this.StateManager.TryGetStateAsync <string>("PatientName"); if (PatientInfoResult.HasValue) { ConditionalValue <CountyRecord> CountyInfoResult = await this.StateManager.TryGetStateAsync <CountyRecord>("CountyInfo"); ConditionalValue <Guid> DoctorInfoResult = await this.StateManager.TryGetStateAsync <Guid>("DoctorId"); ConditionalValue <HealthIndex> HeatlthInfoResult = await this.StateManager.TryGetStateAsync <HealthIndex>("HealthIndex"); ConditionalValue <List <HeartRateRecord> > HeartRateRecords = await this.StateManager.TryGetStateAsync <List <HeartRateRecord> >("HeartRateRecords"); HealthIndexCalculator ic = this.indexCalculator; HealthIndex healthIndex = ic.ComputeIndex(HeatlthInfoResult.Value); return(new DeviceDataViewModel( DoctorInfoResult.Value, this.Id.GetGuidId(), PatientInfoResult.Value, CountyInfoResult.Value, healthIndex, HeartRateRecords.Value)); } } catch (Exception e) { throw new ArgumentException(string.Format("Exception inside band actor {0}|{1}|{2}", this.Id, this.Id.Kind, e)); } throw new ArgumentException(string.Format("No band actor state {0}|{1}", this.Id, this.Id.Kind)); }
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; } } }
public CountyDoctorsController(IReliableStateManager stateManager, HealthIndexCalculator indexCalculator) { this.stateManager = stateManager; this.indexCalculator = indexCalculator; }
/// <summary> /// Initializes a new instance of the DefaultController class. /// </summary> /// <param name="stateManager">Reliable object state manager.</param> public CountyHealthController(IReliableStateManager stateManager, HealthIndexCalculator indexCalculator) { this.stateManager = stateManager; this.indexCalculator = indexCalculator; RuntimeTypeModel.Default.MetadataTimeoutMilliseconds = 300000; }
public static void RegisterComponents(HttpConfiguration config, IReliableStateManager objectManager, HealthIndexCalculator indexCalculator) { UnityContainer container = new UnityContainer(); container.RegisterType <CountyHealthController>( new TransientLifetimeManager(), new InjectionConstructor(objectManager, indexCalculator)); container.RegisterType <CountyDoctorsController>( new TransientLifetimeManager(), new InjectionConstructor(objectManager, indexCalculator)); config.DependencyResolver = new UnityDependencyResolver(container); }
public Startup(IReliableStateManager objectManager, HealthIndexCalculator indexCalculator) { this.objectManager = objectManager; this.indexCalculator = indexCalculator; }
private static async Task VerifyActors( HealthIndexCalculator hic, ActorId bandActorId, string doctorName, CountyRecord randomCountyRecord, BandInfo bandActorInfo, IDoctorActor docActor, IBandActor bandActor, CancellationToken ct) { ServiceEventSource.Current.Message("Verifying Actor {0}", bandActorId); bool bandVerified = false; bool doctorVerified = false; int bandErrorCount = 0; int doctorErrorCount = 0; while (!ct.IsCancellationRequested && !bandVerified && !doctorVerified) { await Task.Delay(100); if (!bandVerified) { try { BandDataViewModel view = await bandActor.GetBandDataAsync(); if (view.PersonName == bandActorInfo.PersonName) { if (view.CountyInfo == bandActorInfo.CountyInfo) { if (view.DoctorId == bandActorInfo.DoctorId) { if (view.PersonId == bandActorId.GetGuidId()) { if (view.HealthIndexValue == bandActorInfo.HealthIndex) { bandVerified = true; ServiceEventSource.Current.Message("Band actor verified."); } else { await bandActor.NewAsync(bandActorInfo); } } } } } } catch (Exception e) { bandErrorCount++; ServiceEventSource.Current.Message("Exception Count {0} verifying band actor, retrying. {1}", bandErrorCount, e); } } else { ServiceEventSource.Current.Message("band already verified, skipping"); } if (!doctorVerified) { try { Tuple <CountyRecord, string> info = await docActor.GetInfoAndNameAsync(); if (info.Item2 == String.Format("Dr. {0}", doctorName) && info.Item1 == randomCountyRecord) { doctorVerified = true; ServiceEventSource.Current.Message("Doctor actor verified."); } else { await docActor.NewAsync(doctorName, randomCountyRecord); } } catch (Exception e) { doctorErrorCount++; ServiceEventSource.Current.Message("Exception Count {0} verifying doctor actor, retrying. {1}", doctorErrorCount, e); } } else { ServiceEventSource.Current.Message("doctor already verified, skipping"); } } }