public AlertSummary GetAlertSummary(int[] facilityKeys) { if (facilityKeys == null) { throw new ArgumentNullException(nameof(facilityKeys)); } if (facilityKeys.Length == 0) { throw new ArgumentException("Array should have at lease one element", nameof(facilityKeys)); } using (log.Activity(m => m($"Getting AlertSummary for {nameof(facilityKeys)}[{string.Join(",", facilityKeys)}]"))) { var query = HttpUtility.ParseQueryString(string.Empty); query["FacilityKeys"] = string.Join(",", facilityKeys); var queryString = query.ToString(); var requestUri = "v1/AlertSummary" + (queryString == string.Empty ? string.Empty : "?") + queryString; var client = httpClientResolver.Resolve(); client.BaseAddress = options.Value.BaseAddress; client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var token = this.accessTokenResolver.Resolve(); if (!string.IsNullOrWhiteSpace(token)) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); } var result = client.GetAsync(requestUri).Result; result.EnsureSuccessStatusCode(); var value = result.Content.ReadAsAsync <AlertSummary>().Result; return(value); } }
public IQueryable <Access> Select(string expand = null, string filter = null) { using (log.Activity(m => m($"Selecting {nameof(Access)} with expand[{expand}] and filter[{filter}] by {Thread.CurrentPrincipal?.Identity?.Name}"))) { var entities = null as IQueryable <Access>; using (log.Activity(m => m("Create Query"))) { entities = context.Accesses .AsNoTracking() .Expand(expand); //TODO: KB: It must be one dynamic linq or odata or typed filter if (!string.IsNullOrWhiteSpace(filter)) { var principalNames = filter.Split(',').ToList(); entities = entities .Where(item => principalNames.Contains(item.Principal.Name)); } } using (log.Activity(m => m("Authorization"))) { try { entities = security.ValidateSelect(entities, expand); } catch (UnauthorizedAccessException) { log.Warn($"Authorization Denied"); throw; } catch (Exception e) { log.Error($"Authorization Error", e); throw; } } var values = null as IQueryable <Access>; using (log.Activity(m => m("Filtering"))) { try { values = entities.Filters(expand).AsQueryable(); } catch (Exception e) { log.Error($"Filtering Error", e); throw; } } log.Info(m => m($"Selected {nameof(Access)}[{string.Join(",", values.Select(item => $"{item.PrincipalId}|{item.RealmId}|{item.PermissionId}"))}] with [{expand}] by {Thread.CurrentPrincipal?.Identity?.Name}")); return(values); } }
public IQueryable <Facility.Facility> Select(string expand = null) { using (log.Activity(m => m($"Selecting {nameof(Facility.Facility)} with [{expand}] by {Thread.CurrentPrincipal?.Identity?.Name}"))) { var entities = null as IQueryable <Facility.Facility>; using (log.Activity(m => m("Create Query"))) { entities = this.context.Facilities .AsNoTracking() .Expand(expand); //entities = new List<Facility.Facility> { new Facility.Facility { Id = 1, Name = "Name 1" }, new Facility.Facility { Id = 2, Name = "Name 2" } }.AsQueryable(); } using (log.Activity(m => m("Authorization"))) { try { //entities = security.ValidateSelect(entities, expand); entities = entities; } catch (UnauthorizedAccessException) { log.Warn($"Authorization Denied"); throw; } catch (Exception e) { log.Error($"Authorization Error", e); throw; } } var values = null as IQueryable <Facility.Facility>; using (log.Activity(m => m("Filtering"))) { try { values = entities.Filters(expand).AsQueryable(); } catch (Exception e) { log.Error($"Filtering Error", e); throw; } } log.Info(m => m($"Selected {nameof(Facility.Facility)}[{string.Join(",", values.Select(item => item.Id))}] with [{expand}] by {Thread.CurrentPrincipal?.Identity?.Name}")); return(values); } }
public MedicalOrderSearchResult Search(MedicalOrderSearchQuery request) { using (log.Activity(m => m($"Searching"))) { var query = HttpUtility.ParseQueryString(string.Empty); var queryString = query.ToString(); var requestUri = "fhir/MedicationOrder/_search/" + (queryString == string.Empty ? string.Empty : "?") + queryString; var client = httpClientResolver.Resolve(); client.BaseAddress = options.Value.BaseAddress; client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var token = this.accessTokenResolver.Resolve(); if (!string.IsNullOrWhiteSpace(token)) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); } var result = client.PostAsJsonAsync(requestUri, request).Result; //Compensate 404 instead of enpty reply if (result.StatusCode == System.Net.HttpStatusCode.NotFound) { return(new MedicalOrderSearchResult { resourceType = "Bundle", type = "searchset", entry = Enumerable.Empty <MedicalOrderSearchResult.Entry>().ToList() }); } result.EnsureSuccessStatusCode(); var value = result.Content.ReadAsAsync <MedicalOrderSearchResult>().Result; return(value); } }
public ConfigurationService(ILog log, IContext context) { this.log = log ?? throw new ArgumentNullException(nameof(log)); this.context = context ?? throw new ArgumentNullException(nameof(context)); if ((ConfigurationManager.AppSettings["ConfigurationService.Validate"] ?? ConfigurationManager.AppSettings["configuration.validate-on-load"]) == "true") { using (log.Activity(m => m($"Validating"))) { try { GetSecondaryDataServiceOptions(); GetHsvIntegrationServiceOptions(); GetOrderServiceOptions(); GetSqlServerCacheOptions(); GetGlobalPreferencesServiceOptions(); GetInfusionServiceUpdaterOptions(); GetConfigurationContextUpdaterOptions(); GetSilentProvisioningServiceOptions(); GetAttentionNoticeStatusesTrackerOptions(); GetIdentityServerBearerTokenAuthenticationOptions(); } catch (Exception e) { log.Error(m => m($"Validating failure", e)); throw; } } } }
public void Configuration(IAppBuilder app) { log.Info("Services Owin Startup started."); try { using (log.Activity(m => m($"Configuring Identity"))) { app.UseCors(CorsOptions.AllowAll); JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary <string, string>(); //app.UseCookieAuthentication(new CookieAuthenticationOptions //{ // AuthenticationType = "Cookies" //}); //TODO: Fild how to resolve it app.UseIdentityServerBearerTokenAuthentication(Services.ConfigurationService.IdentityServerBearerTokenAuthenticationOptions.Value); } using (log.Activity(m => m($"Configuring WebApi"))) { app.UseWebApi(WebApiConfig.Register()); } using (log.Activity(m => m($"Configuring Shutdown"))) { var context = new OwinContext(app.Properties); var token = context.Get <CancellationToken>("host.OnAppDisposing"); if (token != CancellationToken.None) { token.Register(() => { this.OnAppDisposing(app); }); } } log.Info("BD.MedView.Services Startup succeded."); } catch (Exception ex) { log.Fatal("Error occured in BD.MedView.Services Startup.", ex); } }
public string Get(string key) { if (key == null) { throw new ArgumentNullException(nameof(key)); } using (log.Activity(m => m($"Reading Cache[{key}] by {Thread.CurrentPrincipal?.Identity?.Name}"))) { using (log.Activity(m => m("Authorization"))) { try { security.ValidateGet(key); } catch (UnauthorizedAccessException) { log.Warn($"Authorization Denied"); throw; } catch (Exception e) { log.Error($"Authorization Error", e); throw; } } var value = context.GetString(key); //TODO: KB: Should we throw key not found or null? We cannot put null back - so it should be key-not-found. Problem in IDistributed Cache: must have TryGet log.Info(m => m($"Read Cache[{key}] by {Thread.CurrentPrincipal?.Identity?.Name}")); return(value); } }
void IObserver <EntityEvent <Authorization.Principal> > .OnNext(EntityEvent <Authorization.Principal> value) { using (log.Activity(m => m($"Processing {nameof(EntityEvent<Authorization.Principal>)} event"))) { if (value.OldValue == null && value.NewValue != null) { OnCreated(value.NewValue); } else if (value.OldValue == null && value.NewValue != null) { OnUpdated(value.NewValue, value.OldValue); } else if (value.OldValue != null && value.NewValue == null) { OnDeleted(value.OldValue); } else { log.Trace(m => m($"{nameof(EntityEvent<Authorization.Principal>)} event is ignored")); } } }
public static void Main() { using (Log.Activity("Demonstrate using a logging Stream decorator")) { var stream = File.OpenRead("loremipsum.txt"); var loggingStream = new LoggingStreamDecorator(stream); using (var reader = new StreamReader(loggingStream)) { reader.ReadToEnd(); } } Console.ReadLine(); }
public IHttpActionResult Post([FromBody] SecondaryData model) { using (log.Activity(m => m($"Executing Post by {Thread.CurrentPrincipal?.Identity?.Name}"))) { using (log.Activity(m => m($"Validating Input"))) { if (!ModelState.IsValid) { log.Trace(m => m("Validation failed")); return(BadRequest(ModelState)); } } using (log.Activity(m => m($"Executing Service Call"))) { try { service.Process(model); } catch (UnauthorizedAccessException e) { log.Warn(m => m("Authorization failed", e)); return(StatusCode(HttpStatusCode.Forbidden)); } catch (Exception e) { log.Error(m => m("Process failed", e)); return(InternalServerError(e)); } } var value = null as object; using (log.Activity(m => m($"Formatting Result"))) { try { value = new { PageInfoList = new { PageInfo = model.PageInfoList.PageInfo //Filter elements without alerts .Where(item => item.MedMinedAlert != null) .Select(item => new { item.Id, item.MedMinedAlert }).ToArray() } }; } catch (Exception e) { log.Error(m => m("Formatting failed", e)); return(InternalServerError(e)); } } log.Info(m => m($"Executing Post by {Thread.CurrentPrincipal?.Identity?.Name} succeeded")); return(Ok(value)); } }
public IQueryable <UserPreference> Select(string expand = null) { using (log.Activity(m => m($"Selecting {nameof(UserPreference)} with [{expand}] by {Thread.CurrentPrincipal?.Identity?.Name}"))) { var entities = null as IQueryable <UserPreference>; using (log.Activity(m => m("Create Query"))) { entities = context.UserPreferences .AsNoTracking() .Expand(expand); } using (log.Activity(m => m("Authorization"))) { try { entities = security.ValidateSelect(entities, expand); } catch (UnauthorizedAccessException) { log.Warn($"Authorization Denied"); throw; } catch (Exception e) { log.Error($"Authorization Error", e); throw; } } var values = null as IQueryable <UserPreference>; using (log.Activity(m => m("Filtering"))) { try { values = entities.Filters(expand).AsQueryable(); } catch (Exception e) { log.Error($"Filtering Error", e); throw; } } log.Info(m => m($"Selected {nameof(UserPreference)}[{string.Join(",", values.Select(item => item.Id))}] with [{expand}] by {Thread.CurrentPrincipal?.Identity?.Name}")); return(values); } }
public void Process(SecondaryData value) { value = value ?? throw new ArgumentNullException(nameof(value)); using (log.Activity(m => m($"Process {nameof(SecondaryData)} by {Thread.CurrentPrincipal?.Identity?.Name}"))) { using (log.Activity(m => m("Preparing PageInfo and Cache"))) { try { var refreshCacheTask = Task.Run(() => Cache(value)); var enrichPageInfoTask = Task.Run(() => Enrich(value)); Task.WaitAll(refreshCacheTask, enrichPageInfoTask); } catch (Exception e) { log.Error($"Preparing PageInfo and Cache Error", e); throw; } } var pageInfoList = null as List <PageInfo>; using (log.Activity(m => m($"Filtering {nameof(PageInfo)} that cannot be matched"))) { pageInfoList = value.PageInfoList.PageInfo .Where(item => CanMatch(item)) .ToList(); log.Trace(m => m($"Ignored {nameof(PageInfo)} [{string.Join(",", value.PageInfoList.PageInfo.Except(pageInfoList).Select(item => item.MedMinedfacilityId))}]")); } var alertList = null as List <Alert>; using (log.Activity(m => m($"Get {nameof(Alert)} from Cache"))) { alertList = pageInfoList .Select(item => int.Parse(item.MedMinedfacilityId)) .Distinct() .SelectMany(item => GetAlertsFromCache(item) ?? Enumerable.Empty <Alert>()) .ToList(); log.Trace(m => m($"Found {nameof(Alert)} for {nameof(Alert.facility_id)} [{string.Join(",", alertList.Select(item => item.facility_id).Distinct())}]")); } using (log.Activity(m => m($"Matching {nameof(PageInfo)} to {nameof(Alert)}"))) { var pageInfoAlerts = pageInfoList.Join(alertList, (pageInfo) => pageInfo.MedMinedfacilityId, (alert) => alert.facility_id.ToString(), (pageInfo, alert) => Tuple.Create(pageInfo, alert)); foreach (var pageInfoAlert in pageInfoAlerts) { var pageInfo = pageInfoAlert.Item1; var alert = pageInfoAlert.Item2; var isMatched = default(bool); using (log.Activity(m => m($"Matching {nameof(PageInfo)}[{pageInfo.Id}] to {nameof(Alert)}[{alert.alert_id}]"))) { isMatched = Match(pageInfo, alert); log.Trace(m => m($"Match" + (isMatched ? " " : " not ") + $"found for {nameof(PageInfo)}[{pageInfo.Id}] to {nameof(Alert)}[{alert.alert_id}]")); } if (isMatched) { using (log.Activity(m => m($"Adding {nameof(Alert)}[{alert.alert_id}] to {nameof(PageInfo)}[{pageInfo.Id}].{nameof(PageInfo.MedMinedAlert)}"))) { Fill(pageInfo, alert); log.Trace(m => m($"Added {nameof(Alert)}[{alert.alert_id}] to {nameof(PageInfo)}[{pageInfo.Id}].{nameof(PageInfo.MedMinedAlert)}")); } } } } log.Info(m => m($"Processed {nameof(SecondaryData)} by {Thread.CurrentPrincipal?.Identity?.Name}")); } }
public IEnumerable <WidgetState> GetMappings() { using (log.Activity(m => m($"{nameof(GetMappings)} by {Thread.CurrentPrincipal?.Identity?.Name}"))) { using (log.Activity(m => m($"Read {nameof(WidgetState)}"))) { return(context.WidgetStates.Include(x => x.ProviderStates)); } } }
public void Provision(IPrincipal principal) { using (log.Activity(m => m($"Provisioning {Thread.CurrentPrincipal?.Identity?.Name}"))) { var userName = null as string; using (log.Activity(m => m($"Validate {Thread.CurrentPrincipal?.Identity?.Name}"))) { var identity = Thread.CurrentPrincipal.Identity as ClaimsIdentity; if (identity == null) { log.Info($"Identity is not ClaimsIdentity or null. Ignore Execution."); return; } userName = identity.Claims.FirstOrDefault(x => x.Type == "user_id")?.Value ?? identity.Name; if (userName == null) { log.Info($"UserName claim value is not found. Ignore Execution."); return; } var isSuperByClaim = IsSuperByClaim(identity); if (!isSuperByClaim) { log.Info($"Required claim value is not found. Ignore Execution."); return; } } using (log.Activity(m => m($"Impersonating Operation"))) { //TODO: KB: Do we need to secure operation that always must succeed? using (new Impersonate(new GenericPrincipal(new GenericIdentity(systemIdentityName), new string[0]))) { var relation = null as Role; using (log.Activity(m => m($"Read {nameof(Role)}[\"{roleName}\"]"))) { relation = context.Roles.Include(item => item.Realm).SingleOrDefault(item => item.Name == roleName); } if (relation == null) { log.Error($"{nameof(Role)}[\"{roleName}\"] is not found"); throw new KeyNotFoundException(); } var entity = null as Principal; using (log.Activity(m => m($"Read {nameof(Principal)}[\"{userName}\"]"))) { entity = context.Principals.Include(item => item.Roles.Select(r => r.Realm)).SingleOrDefault(item => item.Name == userName); } if (entity == null) { log.Info($"{nameof(Principal)}[\"{userName}\"] is not found."); using (log.Activity(m => m("Create Entity"))) { try { entity = context.Principals.Add(new Principal { Name = userName }); context.SaveChanges(); } //TODO: KB: Do this on index validation //throw new DuplicateKeyException(value.Name) catch (Exception e) { log.Error($"Update Error", e); throw; } } var newValue = entity.Filter(); using (log.Activity(m => m("Emit Event"))) { try { emitter.OnCreated(newValue); } catch (Exception e) { log.Error($"Emit Event Error", e); throw; } } } if (entity.Roles.Any(item => item.Id == relation.Id)) { log.Info($"{nameof(Principal)}[\"{userName}\"] already has role {nameof(Role)}[\"{roleName}\"]. Ignore Execution."); return; } using (log.Activity(m => m("Update Entity"))) { try { relation.Principals.Add(entity); context.SaveChanges(); } catch (Exception e) { log.Error($"Update Error", e); throw; } } using (log.Activity(m => m("Emit Event"))) { try { var leftValue = entity.Filter(); var rightValue = relation.Filter(); linkEmitter.OnAdded(leftValue, rightValue, item => item.Roles); } catch (Exception e) { log.Error($"Emit Event Error", e); throw; } } log.Info($"Provisioned {nameof(Role)}[\"{roleName}\"] to {nameof(Principal)}[\"{userName}\"].{nameof(Principal.Roles)} by {Thread.CurrentPrincipal?.Identity?.Name}"); } } } }
private SecondaryDataServiceOptions GetSecondaryDataServiceOptions() { using (log.Activity(m => m($"Executing {nameof(GetSecondaryDataServiceOptions)}"))) { var option = new SecondaryDataServiceOptions(); using (log.Activity(m => m($"Read {nameof(SecondaryDataServiceOptions.CacheAbsoluteExpiration)}"))) { //TODO: KB: Fix This var pattern = ConfigurationManager.AppSettings["SecondaryDataServiceOptions.CacheAbsoluteExpiration"] ?? ConfigurationManager.AppSettings["secondary-data.cache.absolute-expiration"]; option.CacheAbsoluteExpiration = string.IsNullOrWhiteSpace(pattern) ? (TimeSpan?)null : TimeSpan.Parse(pattern); } using (log.Activity(m => m($"Read {nameof(SecondaryDataServiceOptions.CacheSlidingExpiration)}"))) { //TODO: KB: Fix This var pattern = ConfigurationManager.AppSettings["SecondaryDataServiceOptions.CacheSlidingExpiration"] ?? ConfigurationManager.AppSettings["secondary-data.cache.sliding-expiration"]; option.CacheSlidingExpiration = string.IsNullOrWhiteSpace(pattern) ? (TimeSpan?)null : TimeSpan.Parse(pattern); } using (log.Activity(m => m($"Read {nameof(SecondaryDataServiceOptions.MaxLimit)}"))) { //TODO: KB: Fix This var pattern = ConfigurationManager.AppSettings["SecondaryDataServiceOptions.MaxLimit"] ?? ConfigurationManager.AppSettings["secondary-data.alerts.max-limit"]; option.MaxLimit = string.IsNullOrWhiteSpace(pattern) ? option.MaxLimit : int.Parse(pattern); } using (log.Activity(m => m($"Read {nameof(SecondaryDataServiceOptions.MaxDegreeOfParallelism)}"))) { //TODO: KB: Fix This var pattern = ConfigurationManager.AppSettings["SecondaryDataServiceOptions.MaxDegreeOfParallelism"] ?? ConfigurationManager.AppSettings["secondary-data.alerts.max-degree-of-parallelism"]; option.MaxDegreeOfParallelism = string.IsNullOrWhiteSpace(pattern) ? option.MaxDegreeOfParallelism : int.Parse(pattern); } using (log.Activity(m => m($"Read {nameof(SecondaryDataServiceOptions.Variance)}"))) { //We cannot use context here var connectionString = ConfigurationManager.ConnectionStrings["BD.MedView.Services.Models.CacheContext"]?.ConnectionString; if (!string.IsNullOrWhiteSpace(connectionString)) { try { using (var connection = new System.Data.SqlClient.SqlConnection(connectionString)) { connection.Open(); var command = new System.Data.SqlClient.SqlCommand("SELECT [Configurations] FROM [conf].[GlobalPreferences] WHERE [Name] = 'Infusion'", connection); using (var reader = command.ExecuteReader()) { if (reader.Read()) { var value = (string)reader[0]; option.Variance = JsonConvert.DeserializeAnonymousType(value, new { OrderServiceVariance = 0 }).OrderServiceVariance; } } } } catch (Exception e) { log.Error(m => m($"Read {nameof(SecondaryDataServiceOptions.Variance)} failure", e)); throw; } } } using (log.Activity(m => m($"Read {nameof(SecondaryDataServiceOptions.IdKindMapping)}"))) { //We cannot use context here var connectionString = ConfigurationManager.ConnectionStrings["BD.MedView.Services.Models.CacheContext"]?.ConnectionString; if (!string.IsNullOrWhiteSpace(connectionString)) { try { using (var connection = new System.Data.SqlClient.SqlConnection(connectionString)) { connection.Open(); var command = new System.Data.SqlClient.SqlCommand("SELECT [PatientIdKind],[FhirServiceValue] FROM [conf].[PatientIdKindFhirServiceMappings]", connection); using (var reader = command.ExecuteReader()) { while (reader.Read()) { var key = (string)reader[0]; var value = (string)reader[0]; option.IdKindMapping[key] = value; } } } } catch (Exception e) { log.Error(m => m($"Read {nameof(SecondaryDataServiceOptions.IdKindMapping)} failure", e)); throw; } } } return(option); } }
void IObserver <EntityEvent <AttentionNoticeStatus> > .OnNext(EntityEvent <AttentionNoticeStatus> value) { using (log.Activity(m => m($"Processing {nameof(EntityEvent<AttentionNoticeStatus>)} event"))) { if (value.OldValue == null && value.NewValue != null) { OnCreated(value.NewValue); } else if (value.OldValue != null && value.NewValue != null) { OnUpdated(value.NewValue, value.OldValue); } else if (value.OldValue != null && value.NewValue == null) { OnDeleted(value.OldValue); } else { log.Trace(m => m($"{nameof(EntityEvent<Facility.Facility>)} event is ignored")); } } }