예제 #1
0
        public virtual Boolean HasDssErrors(Boolean multipleCommittees)
        {
            Boolean hasErrors = HasDssInvalidMethod() || HasDssInvalidWeight(multipleCommittees);

            hasErrors = hasErrors || (!MethodSettings.UseManualWeights && (Criteria != null && Criteria.Any(c => c.Deleted == BaseStatusDeleted.None && c.HasDssErrors())));
            hasErrors = hasErrors || (Criteria != null && (Criteria.Any(c => c.Deleted == BaseStatusDeleted.None && (c.Type == CriterionType.RatingScale || c.Type == CriterionType.RatingScaleFuzzy)) &&
                                                           Criteria.Where(c => c.Deleted == BaseStatusDeleted.None && (c.Type == CriterionType.RatingScale || c.Type == CriterionType.RatingScaleFuzzy)).
                                                           Select(c => (DssCriterion)c).Any(c => c.HasDssFuzzyErrors(MethodSettings))));
            return(hasErrors);
            //return UseDss && (
            //    (!MethodSettings.InheritsFromFather && (MethodSettings.IdMethod<1 || MethodSettings.IdRatingSet <1 ))
            //    ||
            //    (MethodSettings.InheritsFromFather && (Call.IdDssMethod<1 || Call.IdDssRatingSet <1 )))
            //    ||
            //    (   WeightSettings.IdRatingValue <1
            //        || ((WeightSettings.RatingType & Core.Dss.Domain.RatingType.intermediateValues)>0) && WeightSettings.IdRatingValueEnd<1 )
            //        || ((WeightSettings.RatingType & Core.Dss.Domain.RatingType.extended)>0 && WeightSettings.IdRatingValueEnd<1)
            //    || (Criteria != null &&
            //        (
            //        Criteria.Any(c=> c.Deleted== BaseStatusDeleted.None && c.HasDssErrors())
            //        ||
            //        (Criteria.Any(c=>c.Deleted== BaseStatusDeleted.None && c.Type== CriterionType.RatingScale || c.Type== CriterionType.RatingScaleFuzzy)
            //        && Criteria.Where(c => c.Deleted == BaseStatusDeleted.None && c.Type == CriterionType.RatingScale || c.Type == CriterionType.RatingScaleFuzzy).
            //        Select(c => (DssCriterion)c).Any(c => c.HasDssFuzzyErrors(MethodSettings)))));
        }
예제 #2
0
    public void OnStageComplete()
    {
        foreach (NoteGrade grade in Enum.GetValues(typeof(NoteGrade)))
        {
            if (grade == NoteGrade.None)
            {
                continue;
            }
            gradeCounts[grade] = Stages.Sum(it => it?.GradeCounts[grade] ?? 0);
        }

        if (Criteria.Any(it => it.Judge(this) == CriterionState.Failed))
        {
            IsFailed = true;
        }
        else if (CurrentStageIndex < Stages.Length - 1)
        {
            // Refill health by 30% of lost health
            var maxHealth = Tier.Meta.maxHealth;
            Health += 0.3 * (maxHealth - Health);
            if (Health > maxHealth)
            {
                Health = maxHealth;
            }
        }

        if (CurrentStageIndex == Stages.Length - 1)
        {
            OnComplete();
        }
    }
예제 #3
0
        public async Task <IEntity[]> GetList()
        {
            if (!IsCacheable())
            {
                return(await LoadFromDatabase().ToArray());
            }

            if (Criteria.Any() || Context.Current.Database().AnyOpenTransaction())
            {
                return(await LoadFromDatabaseAndCache().ToArray());
            }

            var result = Cache.GetList(EntityType)?.Cast <IEntity>().ToArray();

            if (result != null)
            {
                await LoadIncludedAssociations(result);

                return(result);
            }

            result = await LoadFromDatabaseAndCache().ToArray();

            Cache.AddList(EntityType, result);

            return(result);
        }
예제 #4
0
        public override LdapObject GetUserBySid(string sid)
        {
            try
            {
                var ldapUniqueIdAttribute = ConfigurationManagerExtension.AppSettings["ldap.unique.id"];

                Criteria criteria;

                if (ldapUniqueIdAttribute == null)
                {
                    criteria = Criteria.Any(
                        Expression.Equal(LdapConstants.RfcLDAPAttributes.ENTRY_UUID, sid),
                        Expression.Equal(LdapConstants.RfcLDAPAttributes.NS_UNIQUE_ID, sid),
                        Expression.Equal(LdapConstants.RfcLDAPAttributes.GUID, sid),
                        Expression.Equal(LdapConstants.ADSchemaAttributes.OBJECT_SID, sid)
                        );
                }
                else
                {
                    criteria = Criteria.All(Expression.Equal(ldapUniqueIdAttribute, sid));
                }

                var searchfilter = string.Format("(&{0}{1})", Settings.UserFilter, criteria);

                var list = LDAPSearcher.Search(Settings.UserDN, NovellLdapSearcher.LdapScope.Sub, searchfilter, limit: 1);

                return(list.FirstOrDefault());
            }
            catch (Exception e)
            {
                Log.ErrorFormat("NovellLdapHelper->GetUserBySid(sid: '{0}') failed. Error: {1}", sid, e);
            }

            return(null);
        }
예제 #5
0
        private void OnRemoveGroup(CriteriaGroupViewModel group)
        {
            Criteria.Remove(group);

            if (Criteria.Any())
            {
                Criteria.Last().IsLastGroup = true;
            }
        }
예제 #6
0
        private void OnAddNewCriteriaGroup()
        {
            if (Criteria.Any())
            {
                Criteria.Last().IsLastGroup = false;
            }

            Criteria.Add(new CriteriaGroupViewModel
            {
                IsLastGroup = true
            });
        }
예제 #7
0
        public override void OnShow(Track currentTrack)
        {
            _tags      = new Lazy <List <string> >(() => _library.Artists.SelectMany(a => a.Tracks).SelectMany(t => t.Tags).Distinct().OrderBy(g => g).ToList());
            _groupings = new Lazy <List <string> >(() => _library.Artists.Select(a => a.Grouping).Distinct().OrderBy(g => g).ToList());
            _countries = new Lazy <List <string> >(() => _library.Artists.Select(a => a.City.Country).Distinct().OrderBy(g => g).ToList());
            _states    = new Lazy <List <string> >(() => _library.Artists.Select(a => a.City.State).Distinct().OrderBy(g => g).ToList());
            _cities    = new Lazy <List <string> >(() => _library.Artists.Select(a => a.City.Name).Distinct().OrderBy(g => g).ToList());

            if (Criteria.Any())
            {
                return;
            }

            OnClear();
        }
예제 #8
0
        public IEnumerable <GroupInfo> GetAndCheckCurrentGroups(LdapObject ldapUser, IEnumerable <GroupInfo> portalGroups)
        {
            var result = new List <GroupInfo>();

            try
            {
                var searchExpressions = new List <Expression>();
                if (portalGroups != null && portalGroups.Any())
                {
                    searchExpressions.AddRange(portalGroups.Select(g => Expression.Equal(LdapConstants.ADSchemaAttributes.OBJECT_SID, g.Sid)));
                }
                else
                {
                    return(result);
                }

                var criteria  = Criteria.Any(searchExpressions.ToArray());
                var foundList = LdapHelper.GetGroups(criteria);

                if (foundList.Any())
                {
                    var stillExistingGroups = portalGroups.Where(g => foundList.Any(fg => fg.Sid == g.Sid));

                    foreach (var group in stillExistingGroups)
                    {
                        if (GetGroupUsers(group).Any(u => u.Sid == ldapUser.Sid))
                        {
                            result.Add(group);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (ldapUser != null)
                {
                    _log.ErrorFormat("GetAndCheckCurrentGroups(login: '******' sid: '{1}') error {2}",
                                     ldapUser.DistinguishedName, ldapUser.Sid, ex);
                }
            }
            return(result);
        }
        public List <Tuple <UserInfo, LdapObject> > FindLdapUsers(string login)
        {
            var listResults = new List <Tuple <UserInfo, LdapObject> >();

            var ldapLogin = LdapLogin.ParseLogin(login);

            if (ldapLogin == null)
            {
                return(listResults);
            }

            if (!LdapHelper.IsConnected)
            {
                LdapHelper.Connect();
            }

            var exps = new List <Expression> {
                Expression.Equal(Settings.LoginAttribute, ldapLogin.Username)
            };

            if (!ldapLogin.Username.Equals(login) && ldapLogin.ToString().Equals(login))
            {
                exps.Add(Expression.Equal(Settings.LoginAttribute, login));
            }

            string email = null;

            if (!string.IsNullOrEmpty(Settings.MailAttribute) && !string.IsNullOrEmpty(ldapLogin.Domain) && login.Contains("@"))
            {
                email = ldapLogin.ToString();
                exps.Add(Expression.Equal(Settings.MailAttribute, email));
            }

            var searchTerm = exps.Count > 1 ? Criteria.Any(exps.ToArray()).ToString() : exps.First().ToString();

            var users = LdapHelper.GetUsers(searchTerm, !string.IsNullOrEmpty(email) ? -1 : 1)
                        .Where(user => user != null)
                        .ToLookup(lu =>
            {
                var ui = Constants.LostUser;

                try
                {
                    if (string.IsNullOrEmpty(_ldapDomain))
                    {
                        _ldapDomain = LdapUtils.DistinguishedNameToDomain(lu.DistinguishedName);
                    }

                    ui = lu.ToUserInfo(this, _log);
                }
                catch (Exception ex)
                {
                    _log.ErrorFormat("FindLdapUser->ToUserInfo() failed. Error: {0}", ex.ToString());
                }

                return(Tuple.Create(ui, lu));
            });

            if (!users.Any())
            {
                return(listResults);
            }

            foreach (var user in users)
            {
                var ui = user.Key.Item1;

                if (ui.Equals(Constants.LostUser))
                {
                    continue;
                }

                var ul = user.Key.Item2;

                var ldapLoginAttribute = ul.GetValue(Settings.LoginAttribute) as string;

                if (string.IsNullOrEmpty(ldapLoginAttribute))
                {
                    _log.WarnFormat("LDAP: DN: '{0}' Login Attribute '{1}' is empty", ul.DistinguishedName, Settings.LoginAttribute);
                    continue;
                }

                if (ldapLoginAttribute.Equals(login))
                {
                    listResults.Add(user.Key);
                    continue;
                }

                if (!string.IsNullOrEmpty(email))
                {
                    if (ui.Email.Equals(email, StringComparison.InvariantCultureIgnoreCase))
                    {
                        listResults.Add(user.Key);
                        continue;
                    }
                }

                if (LdapUtils.IsLoginAccepted(ldapLogin, ui, LDAPDomain))
                {
                    listResults.Add(user.Key);
                }
            }

            return(listResults);
        }
        private bool TryGetLdapUserGroups(LdapObject ldapUser, out List <LdapObject> ldapUserGroups)
        {
            ldapUserGroups = new List <LdapObject>();
            try
            {
                if (!Settings.GroupMembership)
                {
                    return(false);
                }

                if (ldapUser == null ||
                    string.IsNullOrEmpty(ldapUser.Sid))
                {
                    return(false);
                }

                if (!LdapHelper.IsConnected)
                {
                    LdapHelper.Connect();
                }

                var userGroups = ldapUser.GetAttributes(LdapConstants.ADSchemaAttributes.MEMBER_OF, _log)
                                 .Select(s => s.Replace("\\", string.Empty))
                                 .ToList();

                if (!userGroups.Any())
                {
                    userGroups = ldapUser.GetAttributes(GROUP_MEMBERSHIP, _log);
                }

                var searchExpressions = new List <Expression>();

                PrimaryGroupId = PrimaryGroupId ??
                                 ldapUser.GetValue(LdapConstants.ADSchemaAttributes.PRIMARY_GROUP_ID) as string;

                if (!string.IsNullOrEmpty(PrimaryGroupId))
                {
                    var userSid = ldapUser.Sid;
                    var index   = userSid.LastIndexOf("-", StringComparison.InvariantCultureIgnoreCase);

                    if (index > -1)
                    {
                        var primaryGroupSid = userSid.Substring(0, index + 1) + PrimaryGroupId;
                        searchExpressions.Add(Expression.Equal(ldapUser.SidAttribute, primaryGroupSid));
                    }
                }

                if (userGroups.Any())
                {
                    searchExpressions.AddRange(userGroups
                                               .Select(g => g.Substring(0, g.IndexOf(",", StringComparison.InvariantCultureIgnoreCase)))
                                               .Where(s => !string.IsNullOrEmpty(s))
                                               .Select(Expression.Parse)
                                               .Where(e => e != null));

                    var criteria = Criteria.Any(searchExpressions.ToArray());

                    var foundList = LdapHelper.GetGroups(criteria);

                    if (foundList.Any())
                    {
                        ldapUserGroups.AddRange(foundList);
                        return(true);
                    }
                }
                else
                {
                    var ldapGroups = LdapHelper.GetGroups();

                    ldapUserGroups.AddRange(
                        ldapGroups.Where(
                            ldapGroup =>
                            LdapHelper.UserExistsInGroup(ldapGroup, ldapUser, Settings)));

                    return(ldapUserGroups.Any());
                }
            }
            catch (Exception ex)
            {
                if (ldapUser != null)
                {
                    _log.ErrorFormat("IsUserExistInGroups(login: '******' sid: '{1}') error {2}",
                                     ldapUser.DistinguishedName, ldapUser.Sid, ex);
                }
            }

            return(false);
        }
예제 #11
0
        public override IEnumerable <System.Linq.Expressions.MemberBinding> InnerSelectBindings(Type selectType, System.Linq.Expressions.ParameterExpression sourceTypeParameter)
        {
            ParameterExpression pe_sourceQueryType = sourceTypeParameter;
            ParameterExpression pe_vitalsQueryType = Expression.Parameter(typeof(PCORIQueryBuilder.Model.Vital), "v");
            Expression          measuredOnSelector = Expression.Property(pe_vitalsQueryType, "MeasuredOn");

            BinaryExpression be_vitalsPatient = Expression.Equal(Expression.Property(pe_vitalsQueryType, "PatientID"), Expression.Property(pe_sourceQueryType, "ID"));

            //apply all the applicable criteria to the inner value select as well.
            List <Expression> predicates = new List <Expression>();

            if (Criteria.Any(c => c.Terms.Any(t => t.Type == ModelTermsFactory.ObservationPeriodID) || c.Criteria.Any(ci => ci.Terms.Any(t => t.Type == ModelTermsFactory.ObservationPeriodID))))
            {
                Expression prop_Encounter = Expression.Property(pe_vitalsQueryType, "Encounter");
                Expression proper_Encounter_AdmittedOn = Expression.Property(prop_Encounter, "AdmittedOn");

                BinaryExpression observationPeriodPredicate = null;

                var observationPeriodCriteria = Criteria.SelectMany(c => c.Terms.Where(t => t.Type == ModelTermsFactory.ObservationPeriodID)).Union(Criteria.SelectMany(c => c.Criteria.SelectMany(ci => ci.Terms.Where(t => t.Type == ModelTermsFactory.ObservationPeriodID))));
                foreach (var obpTerm in observationPeriodCriteria)
                {
                    BinaryExpression obp_predicate = null;
                    var obp_values = AdapterHelpers.ParseDateRangeValues(obpTerm);
                    if (obp_values.StartDate.HasValue && obp_values.EndDate.HasValue)
                    {
                        DateTime startDate = obp_values.StartDate.Value.Date;
                        DateTime endDate   = obp_values.EndDate.Value.Date;
                        obp_predicate = Expression.AndAlso(Expression.GreaterThanOrEqual(proper_Encounter_AdmittedOn, Expression.Constant(startDate)), Expression.LessThanOrEqual(proper_Encounter_AdmittedOn, Expression.Constant(endDate)));
                    }
                    else if (obp_values.StartDate.HasValue)
                    {
                        DateTime startDate = obp_values.StartDate.Value.Date;
                        obp_predicate = Expression.GreaterThanOrEqual(proper_Encounter_AdmittedOn, Expression.Constant(startDate));
                    }
                    else if (obp_values.EndDate.HasValue)
                    {
                        DateTime endDate = obp_values.EndDate.Value.Date;
                        obp_predicate = Expression.LessThanOrEqual(proper_Encounter_AdmittedOn, Expression.Constant(endDate));
                    }

                    if (obp_predicate == null)
                    {
                        continue;
                    }

                    if (observationPeriodPredicate == null)
                    {
                        observationPeriodPredicate = Expression.AndAlso(Expression.NotEqual(Expression.Property(pe_vitalsQueryType, "EncounterID"), Expression.Constant(null)), obp_predicate);
                    }
                    else
                    {
                        observationPeriodPredicate = Expression.AndAlso(observationPeriodPredicate, obp_predicate);
                    }
                }

                if (observationPeriodPredicate != null)
                {
                    predicates.Add(observationPeriodPredicate);
                }
            }

            if (Criteria.Any(c => c.Terms.Any(t => t.Type == ModelTermsFactory.HeightID) || c.Criteria.Any(ci => ci.Terms.Any(t => t.Type == ModelTermsFactory.HeightID))))
            {
                Expression heightExp = Expression.Property(pe_vitalsQueryType, "Height");
                predicates.Add(Expression.Equal(Expression.Property(heightExp, "HasValue"), Expression.Constant(true)));

                Expression heightSelector = Expression.Property(heightExp, "Value");

                var heightCriteria = Criteria.SelectMany(c => c.Terms.Where(t => t.Type == ModelTermsFactory.HeightID)).Union(Criteria.SelectMany(c => c.Criteria.SelectMany(ci => ci.Terms.Where(t => t.Type == ModelTermsFactory.HeightID))));
                foreach (var heightTerm in heightCriteria)
                {
                    var heightRange = AdapterHelpers.ParseHeightValues(heightTerm);
                    if (heightRange.MinHeight.HasValue)
                    {
                        double minHeight = heightRange.MinHeight.Value;
                        predicates.Add(
                            Expression.GreaterThanOrEqual(heightSelector, Expression.Constant(minHeight))
                            );
                    }
                    if (heightRange.MaxHeight.HasValue)
                    {
                        double maxHeight = heightRange.MaxHeight.Value;
                        predicates.Add(
                            Expression.LessThanOrEqual(heightSelector, Expression.Constant(maxHeight))
                            );
                    }
                }
            }

            if (Criteria.Any(c => c.Terms.Any(t => t.Type == ModelTermsFactory.WeightID) || c.Criteria.Any(ci => ci.Terms.Any(t => t.Type == ModelTermsFactory.WeightID))))
            {
                Expression weightExp = Expression.Property(pe_vitalsQueryType, "Weight");
                predicates.Add(Expression.Equal(Expression.Property(weightExp, "HasValue"), Expression.Constant(true)));

                Expression weightSelector = Expression.Property(weightExp, "Value");

                var weightCriteria = Criteria.SelectMany(c => c.Terms.Where(t => t.Type == ModelTermsFactory.WeightID)).Union(Criteria.SelectMany(c => c.Criteria.SelectMany(ci => ci.Terms.Where(t => t.Type == ModelTermsFactory.WeightID))));
                foreach (var weightTerm in weightCriteria)
                {
                    var weightRange = AdapterHelpers.ParseWeightValues(weightTerm);
                    if (weightRange.MinWeight.HasValue)
                    {
                        double minWeight = weightRange.MinWeight.Value;
                        predicates.Add(
                            Expression.GreaterThanOrEqual(weightSelector, Expression.Constant(minWeight))
                            );
                    }
                    if (weightRange.MaxWeight.HasValue)
                    {
                        double maxWeight = weightRange.MaxWeight.Value;
                        predicates.Add(
                            Expression.LessThanOrEqual(weightSelector, Expression.Constant(maxWeight))
                            );
                    }
                }
            }

            if (Criteria.Any(c => c.Terms.Any(t => t.Type == ModelTermsFactory.VitalsMeasureDateID) || c.Criteria.Any(ci => ci.Terms.Any(t => t.Type == ModelTermsFactory.VitalsMeasureDateID))))
            {
                var measureDateCriteria = Criteria.SelectMany(c => c.Terms.Where(t => t.Type == ModelTermsFactory.VitalsMeasureDateID)).Union(Criteria.SelectMany(c => c.Criteria.SelectMany(ci => ci.Terms.Where(t => t.Type == ModelTermsFactory.VitalsMeasureDateID))));
                foreach (var measureDateTerm in measureDateCriteria)
                {
                    BinaryExpression md_predicate = null;
                    var md_values = AdapterHelpers.ParseDateRangeValues(measureDateTerm);
                    if (md_values.StartDate.HasValue && md_values.EndDate.HasValue)
                    {
                        DateTime startDate = md_values.StartDate.Value.Date;
                        DateTime endDate   = md_values.EndDate.Value.Date;
                        md_predicate = Expression.AndAlso(Expression.GreaterThanOrEqual(measuredOnSelector, Expression.Constant(startDate)), Expression.LessThanOrEqual(measuredOnSelector, Expression.Constant(endDate)));
                    }
                    else if (md_values.StartDate.HasValue)
                    {
                        DateTime startDate = md_values.StartDate.Value.Date;
                        md_predicate = Expression.GreaterThanOrEqual(measuredOnSelector, Expression.Constant(startDate));
                    }
                    else if (md_values.EndDate.HasValue)
                    {
                        DateTime endDate = md_values.EndDate.Value.Date;
                        md_predicate = Expression.LessThanOrEqual(measuredOnSelector, Expression.Constant(endDate));
                    }

                    if (md_predicate != null)
                    {
                        predicates.Add(md_predicate);
                    }
                }
            }

            Expression predicateExpression;

            if (predicates.Count == 0)
            {
                predicateExpression = be_vitalsPatient;
            }
            else
            {
                predicateExpression = Expression.AndAlso(be_vitalsPatient, predicates[0]);
                if (predicates.Count > 1)
                {
                    for (int i = 1; i < predicates.Count; i++)
                    {
                        predicateExpression = Expression.AndAlso(predicateExpression, predicates[i]);
                    }
                }
            }

            Expression           vitalsProp      = Expressions.AsQueryable(Expression.Property(sourceTypeParameter, "Vitals"));
            MethodCallExpression measuredOnWhere = Expressions.Where(vitalsProp, Expression.Lambda(predicateExpression, pe_vitalsQueryType));

            MethodCallExpression orderByMeasureOn = Expressions.OrderByAscending(measuredOnWhere, Expression.Lambda(measuredOnSelector, pe_vitalsQueryType));

            MethodCallExpression measureOnSelect = Expression.Call(typeof(Queryable), "Select", new Type[] { pe_vitalsQueryType.Type, measuredOnSelector.Type }, orderByMeasureOn, Expression.Quote(Expression.Lambda(measuredOnSelector, pe_vitalsQueryType)));

            MethodCallExpression firstOrDefaultVitalMeasuredOn = Expression.Call(typeof(Queryable), "FirstOrDefault", new Type[] { typeof(DateTime) }, measureOnSelect);

            return(new[] {
                Expression.Bind(selectType.GetProperty("MeasuredOn"), firstOrDefaultVitalMeasuredOn)
            });
        }
예제 #12
0
 public virtual Boolean HasDssErrors(Int32 committeesCount)
 {
     return(UseDss && (MethodSettings.Error != Core.Dss.Domain.DssError.None || (committeesCount > 1 && WeightSettings.Error != Core.Dss.Domain.DssError.None) ||
                       (!MethodSettings.UseManualWeights && Criteria != null && Criteria.Any() && Criteria.Any(c => c.HasDssErrors()))));
 }
예제 #13
0
 public override bool HasCriteriaForField(string fieldName)
 {
     return(base.HasCriteriaForField(fieldName) ||
            Criteria.Any(searchOperation => searchOperation.HasCriteriaForField(fieldName)));
 }
예제 #14
0
        public override IEnumerable <System.Linq.Expressions.MemberBinding> InnerSelectBindings(Type selectType, System.Linq.Expressions.ParameterExpression sourceTypeParameter)
        {
            //the earliest  encounter date that satisfies the query critieria

            ParameterExpression pe_sourceQueryType = sourceTypeParameter;

            Expression encountersProp = Expressions.AsQueryable(Expression.Property(pe_sourceQueryType, "Encounters"));

            ParameterExpression pe_encountersQueryType = Expression.Parameter(typeof(PCORIQueryBuilder.Model.Encounter), "enc");

            Expression admittedOnSelector = Expression.Property(pe_encountersQueryType, "AdmittedOn");

            Expression encounterTypeSelector = Expression.Property(pe_encountersQueryType, "EncounterType");

            BinaryExpression be_encounterPatient = Expression.Equal(Expression.Property(pe_sourceQueryType, "ID"), Expression.Property(pe_encountersQueryType, "PatientID"));

            BinaryExpression predicate = be_encounterPatient;

            if (Criteria.Any(c => c.Terms.Any(t => t.Type == ModelTermsFactory.ObservationPeriodID) || c.Criteria.Any(ci => ci.Terms.Any(t => t.Type == ModelTermsFactory.ObservationPeriodID))))
            {
                var observationPeriodCriteria = Criteria.SelectMany(c => c.Terms.Where(t => t.Type == ModelTermsFactory.ObservationPeriodID)).Union(Criteria.SelectMany(c => c.Criteria.SelectMany(ci => ci.Terms.Where(t => t.Type == ModelTermsFactory.ObservationPeriodID))));
                foreach (var obpTerm in observationPeriodCriteria)
                {
                    var range = AdapterHelpers.ParseDateRangeValues(obpTerm);
                    if (range.StartDate.HasValue)
                    {
                        predicate = Expression.AndAlso(predicate, Expression.GreaterThanOrEqual(admittedOnSelector, Expression.Constant(range.StartDate.Value.DateTime.Date)));
                    }
                    if (range.EndDate.HasValue)
                    {
                        predicate = Expression.AndAlso(predicate, Expression.LessThanOrEqual(admittedOnSelector, Expression.Constant(range.EndDate.Value.DateTime.Date)));
                    }
                }
            }

            if (Criteria.Any(c => c.Terms.Any(t => t.Type == ModelTermsFactory.SettingID) || c.Criteria.Any(ci => ci.Terms.Any(t => t.Type == ModelTermsFactory.SettingID))))
            {
                var settingCriteria = Criteria.SelectMany(c => c.Terms.Where(t => t.Type == ModelTermsFactory.SettingID)).Union(Criteria.SelectMany(c => c.Criteria.SelectMany(ci => ci.Terms.Where(t => t.Type == ModelTermsFactory.SettingID))));;
                foreach (var term in settingCriteria)
                {
                    string             value = term.GetStringValue("Setting");
                    DTO.Enums.Settings enumValue;
                    if (Enum.TryParse <DTO.Enums.Settings>(value, out enumValue))
                    {
                        value = enumValue.ToString("G");
                    }

                    if (enumValue == DTO.Enums.Settings.AN)
                    {
                        //any encounter setting that is not null or string.Empty.
                        predicate = Expression.AndAlso(predicate, Expression.AndAlso(Expression.NotEqual(encounterTypeSelector, Expression.Constant("", typeof(string))), Expression.NotEqual(encounterTypeSelector, Expression.Constant(null))));
                    }
                    else if (!string.IsNullOrEmpty(value))
                    {
                        predicate = Expression.AndAlso(predicate, Expression.Equal(encounterTypeSelector, Expression.Constant(value, typeof(string))));
                    }
                }
            }

            MethodCallExpression encounterTypeWhere = Expressions.Where(encountersProp, Expression.Lambda(predicate, pe_encountersQueryType));

            MethodCallExpression orderByAdmittedOn = Expressions.OrderByAscending(encounterTypeWhere, Expression.Lambda(admittedOnSelector, pe_encountersQueryType));

            MethodCallExpression encounterTypeSelect = Expressions.Select(pe_encountersQueryType.Type, encounterTypeSelector.Type, orderByAdmittedOn, Expression.Lambda(encounterTypeSelector, pe_encountersQueryType));

            MethodCallExpression firstOrDefaultEncounterType = Expressions.FirstOrDefault <string>(encounterTypeSelect);

            return(new[] {
                Expression.Bind(selectType.GetProperty("EncounterType"), firstOrDefaultEncounterType)
            });
        }
예제 #15
0
파일: Weight.cs 프로젝트: dalangobeni/cnds
        public override IEnumerable <System.Linq.Expressions.MemberBinding> InnerSelectBindings(Type selectType, System.Linq.Expressions.ParameterExpression sourceTypeParameter)
        {
            ParameterExpression pe_sourceQueryType   = sourceTypeParameter;
            ParameterExpression pe_vitalsQueryType   = Expression.Parameter(typeof(PCORIQueryBuilder.Model.Vital), "v");
            Expression          weightSelector       = Expression.Property(pe_vitalsQueryType, "Weight");
            Expression          weightSelector_Value = Expression.Property(Expression.Property(pe_vitalsQueryType, "Weight"), "Value");

            BinaryExpression be_vitalsPatient = Expression.Equal(Expression.Property(pe_vitalsQueryType, "PatientID"), Expression.Property(pe_sourceQueryType, "ID"));

            //apply all the applicable criteria to the inner value select as well.
            List <Expression> predicates = new List <Expression>();

            if (Criteria.Any(c => c.Terms.Any(t => t.Type == ModelTermsFactory.ObservationPeriodID)))
            {
                Expression prop_Encounter = Expression.Property(pe_vitalsQueryType, "Encounter");
                Expression proper_Encounter_AdmittedOn = Expression.Property(prop_Encounter, "AdmittedOn");

                BinaryExpression observationPeriodPredicate = null;

                var observationPeriodCriteria = Criteria.SelectMany(c => c.Terms.Where(t => t.Type == ModelTermsFactory.ObservationPeriodID));
                foreach (var obpTerm in observationPeriodCriteria)
                {
                    BinaryExpression obp_predicate = null;
                    var obp_values = AdapterHelpers.ParseDateRangeValues(obpTerm);
                    if (obp_values.StartDate.HasValue && obp_values.EndDate.HasValue)
                    {
                        DateTime startDate = obp_values.StartDate.Value.Date;
                        DateTime endDate   = obp_values.EndDate.Value.Date;
                        obp_predicate = Expression.AndAlso(Expression.GreaterThanOrEqual(proper_Encounter_AdmittedOn, Expression.Constant(startDate)), Expression.LessThanOrEqual(proper_Encounter_AdmittedOn, Expression.Constant(endDate)));
                    }
                    else if (obp_values.StartDate.HasValue)
                    {
                        DateTime startDate = obp_values.StartDate.Value.Date;
                        obp_predicate = Expression.GreaterThanOrEqual(proper_Encounter_AdmittedOn, Expression.Constant(startDate));
                    }
                    else if (obp_values.EndDate.HasValue)
                    {
                        DateTime endDate = obp_values.EndDate.Value.Date;
                        obp_predicate = Expression.LessThanOrEqual(proper_Encounter_AdmittedOn, Expression.Constant(endDate));
                    }

                    if (obp_predicate == null)
                    {
                        continue;
                    }

                    if (observationPeriodPredicate == null)
                    {
                        observationPeriodPredicate = Expression.AndAlso(Expression.NotEqual(Expression.Property(pe_vitalsQueryType, "EncounterID"), Expression.Constant(null)), obp_predicate);
                    }
                    else
                    {
                        observationPeriodPredicate = Expression.AndAlso(observationPeriodPredicate, obp_predicate);
                    }
                }

                if (observationPeriodPredicate != null)
                {
                    predicates.Add(observationPeriodPredicate);
                }
            }


            if (Criteria.Any(c => c.Terms.Any(t => t.Type == ModelTermsFactory.HeightID)))
            {
                Expression heightSelector = Expression.Property(pe_vitalsQueryType, "Height");
                predicates.Add(Expression.Equal(Expression.Property(heightSelector, "HasValue"), Expression.Constant(true)));

                Expression heightSelector_Value = Expression.Property(heightSelector, "Value");

                var heightCriteria = Criteria.SelectMany(c => c.Terms.Where(t => t.Type == ModelTermsFactory.HeightID));
                foreach (var heightTerm in heightCriteria)
                {
                    var heightRange = AdapterHelpers.ParseHeightValues(heightTerm);
                    if (heightRange.MinHeight.HasValue)
                    {
                        double minHeight = heightRange.MinHeight.Value;
                        predicates.Add(
                            Expression.GreaterThanOrEqual(heightSelector_Value, Expression.Constant(minHeight))
                            );
                    }
                    if (heightRange.MaxHeight.HasValue)
                    {
                        double maxHeight = heightRange.MaxHeight.Value;
                        predicates.Add(
                            Expression.LessThanOrEqual(heightSelector_Value, Expression.Constant(maxHeight))
                            );
                    }
                }
            }

            if (Criteria.Any(c => c.Terms.Any(t => t.Type == ModelTermsFactory.WeightID)))
            {
                //if the weight term is included in critieria it enforces that the weight value cannot be null
                predicates.Add(Expression.Equal(Expression.Property(weightSelector, "HasValue"), Expression.Constant(true)));

                var weightCriteria = Criteria.SelectMany(c => c.Terms.Where(t => t.Type == ModelTermsFactory.WeightID));
                foreach (var weightTerm in weightCriteria)
                {
                    var weightRange = AdapterHelpers.ParseWeightValues(weightTerm);
                    if (weightRange.MinWeight.HasValue)
                    {
                        double minWeight = weightRange.MinWeight.Value;
                        predicates.Add(
                            Expression.GreaterThanOrEqual(weightSelector_Value, Expression.Constant(minWeight))
                            );
                    }
                    if (weightRange.MaxWeight.HasValue)
                    {
                        double maxWeight = weightRange.MaxWeight.Value;
                        predicates.Add(
                            Expression.LessThanOrEqual(weightSelector_Value, Expression.Constant(maxWeight))
                            );
                    }
                }
            }

            if (Criteria.Any(c => c.Terms.Any(t => t.Type == ModelTermsFactory.VitalsMeasureDateID)))
            {
                Expression measuredOnSelector = Expression.Property(pe_vitalsQueryType, "MeasuredOn");

                var measureDateCriteria = Criteria.SelectMany(c => c.Terms.Where(t => t.Type == ModelTermsFactory.VitalsMeasureDateID));
                foreach (var measureDateTerm in measureDateCriteria)
                {
                    BinaryExpression md_predicate = null;
                    var md_values = AdapterHelpers.ParseDateRangeValues(measureDateTerm);
                    if (md_values.StartDate.HasValue && md_values.EndDate.HasValue)
                    {
                        DateTime startDate = md_values.StartDate.Value.Date;
                        DateTime endDate   = md_values.EndDate.Value.Date;
                        md_predicate = Expression.AndAlso(Expression.GreaterThanOrEqual(measuredOnSelector, Expression.Constant(startDate)), Expression.LessThanOrEqual(measuredOnSelector, Expression.Constant(endDate)));
                    }
                    else if (md_values.StartDate.HasValue)
                    {
                        DateTime startDate = md_values.StartDate.Value.Date;
                        md_predicate = Expression.GreaterThanOrEqual(measuredOnSelector, Expression.Constant(startDate));
                    }
                    else if (md_values.EndDate.HasValue)
                    {
                        DateTime endDate = md_values.EndDate.Value.Date;
                        md_predicate = Expression.LessThanOrEqual(measuredOnSelector, Expression.Constant(endDate));
                    }

                    if (md_predicate != null)
                    {
                        predicates.Add(md_predicate);
                    }
                }
            }

            Expression predicateExpression = null;

            if (predicates.Count > 0)
            {
                predicateExpression = predicates[0];
                if (predicates.Count > 1)
                {
                    for (int i = 1; i < predicates.Count; i++)
                    {
                        predicateExpression = Expression.AndAlso(predicateExpression, predicates[i]);
                    }
                }
            }

            Expression vitalsProp = Expressions.AsQueryable(Expression.Property(sourceTypeParameter, "Vitals"));

            Expression           measureOnSelector = Expression.Property(pe_vitalsQueryType, "MeasuredOn");
            MethodCallExpression orderByMeasureOn;

            if (predicateExpression == null)
            {
                orderByMeasureOn = Expressions.OrderByAscending(vitalsProp, Expression.Lambda(measureOnSelector, pe_vitalsQueryType));
            }
            else
            {
                MethodCallExpression weightWhere = Expressions.Where(vitalsProp, Expression.Lambda(predicateExpression, pe_vitalsQueryType));
                orderByMeasureOn = Expressions.OrderByAscending(weightWhere, Expression.Lambda(measureOnSelector, pe_vitalsQueryType));
            }

            MethodCallExpression weightSelect = Expressions.Select(pe_vitalsQueryType.Type, weightSelector.Type, orderByMeasureOn, Expression.Lambda(weightSelector, pe_vitalsQueryType));

            MethodCallExpression firstOrDefaultVitalWeight = Expressions.FirstOrDefault <double?>(weightSelect);

            if (!HasStratifications)
            {
                return(new[] {
                    Expression.Bind(selectType.GetProperty("Weight"), firstOrDefaultVitalWeight)
                });
            }

            // apply the modifier for stratification
            DTO.Enums.WeightStratification stratification;
            if (!Enum.TryParse <DTO.Enums.WeightStratification>(Stratifications.First().ToString(), out stratification))
            {
                throw new ArgumentException("Unable to parse the specified stratification value as an WeightStratification: " + Stratifications.First().ToString());
            }

            Expression stratificationExp = Expression.Condition(Expression.Equal(Expression.Property(firstOrDefaultVitalWeight, "HasValue"), Expression.Constant(true, typeof(bool))),
                                                                Expression.Convert(Expressions.MathFloor <double>(Expression.Divide(Expression.Property(firstOrDefaultVitalWeight, "Value"), Expression.Constant(Convert.ToDouble((int)stratification)))), typeof(double?)),
                                                                firstOrDefaultVitalWeight);

            return(new[] {
                Expression.Bind(selectType.GetProperty("Weight"), stratificationExp)
            });
        }
예제 #16
0
        public override IEnumerable <System.Linq.Expressions.MemberBinding> InnerSelectBindings(Type selectType, System.Linq.Expressions.ParameterExpression sourceTypeParameter)
        {
            //the earliest  encounter date that satisfies the query critieria

            ParameterExpression pe_sourceQueryType = sourceTypeParameter;

            Expression encountersProp = Expressions.AsQueryable(Expression.Property(pe_sourceQueryType, "Encounters"));

            ParameterExpression pe_encountersQueryType = Expression.Parameter(typeof(PCORIQueryBuilder.Model.Encounter), "enc");

            Expression admittedOnSelector = Expression.Property(pe_encountersQueryType, "AdmittedOn");

            BinaryExpression be_encounterPatient = Expression.Equal(Expression.Property(pe_sourceQueryType, "ID"), Expression.Property(pe_encountersQueryType, "PatientID"));

            BinaryExpression predicate = be_encounterPatient;

            if (Criteria.Any(c => c.Terms.Any(t => t.Type == ModelTermsFactory.ObservationPeriodID)))
            {
                var observationPeriodCriteria = Criteria.SelectMany(c => c.Terms.Where(t => t.Type == ModelTermsFactory.ObservationPeriodID));
                foreach (var obpTerm in observationPeriodCriteria)
                {
                    DateTime dateValue;
                    var      range = AdapterHelpers.ParseDateRangeValues(obpTerm);
                    if (range.StartDate.HasValue)
                    {
                        dateValue = range.StartDate.Value.DateTime.Date;
                        predicate = Expression.AndAlso(predicate, Expression.GreaterThanOrEqual(admittedOnSelector, Expression.Constant(dateValue)));
                    }
                    if (range.EndDate.HasValue)
                    {
                        dateValue = range.EndDate.Value.DateTime.Date;
                        predicate = Expression.AndAlso(predicate, Expression.LessThanOrEqual(admittedOnSelector, Expression.Constant(dateValue)));
                    }
                }
            }

            MethodCallExpression admittedOnWhere = Expressions.Where(encountersProp, Expression.Lambda(predicate, pe_encountersQueryType));

            MethodCallExpression orderByAdmittedOn = Expressions.OrderByAscending(admittedOnWhere, Expression.Lambda(admittedOnSelector, pe_encountersQueryType));

            //need to cast the return type of the select to a nullable datetime so that the FirstOrDefault will be null as the default
            MethodCallExpression admittedOnSelect = Expressions.Select(pe_encountersQueryType.Type, typeof(DateTime?), orderByAdmittedOn, Expression.Lambda(Expression.Convert(admittedOnSelector, typeof(DateTime?)), pe_encountersQueryType));

            MethodCallExpression firstOrDefaultAdmittedOn = Expressions.FirstOrDefault <DateTime?>(admittedOnSelect);

            if (!HasStratifications)
            {
                return(new[] {
                    Expression.Bind(selectType.GetProperty("AdmittedOn"), firstOrDefaultAdmittedOn)
                });
            }

            //if stratified by Month -> return as string in format yyyy-MM
            //if stratified by Year -> return as string in format yyyy

            DTO.Enums.PeriodStratification stratification;
            if (!Enum.TryParse <DTO.Enums.PeriodStratification>(Stratifications.First().ToString(), out stratification))
            {
                throw new ArgumentException("Unable to parse the specified stratification value as an PeriodStratification: " + Stratifications.First().ToString());
            }

            Expression prop = Expression.Property(firstOrDefaultAdmittedOn, "Value");
            //Expression yearPartString = Expressions.CallToString<int>(Expression.Property(prop, "Year"));
            //if (stratification == DTO.Enums.PeriodStratification.Monthly)
            //{
            //    //if stratified by Month -> return as string in format yyyy-MM
            //    Expression monthPartString = Expressions.CallToString<int>(Expression.Property(prop, "Month"));

            //    prop = Expressions.ConcatStrings(yearPartString, Expression.Constant("-"), monthPartString);
            //}
            //else if (stratification == DTO.Enums.PeriodStratification.Yearly)
            //{
            //    //if stratified by Year -> return as string in format yyyy
            //    prop = yearPartString;
            //}
            //else
            //{
            //    throw new NotSupportedException("The specified period stratifcation is not currently supported; stratification value: " + Stratifications.First().ToString());
            //}

            //Expression stratificationModifier = Expression.Condition(Expression.NotEqual(firstOrDefaultAdmittedOn, Expression.Constant(null)), prop, Expression.Constant("", typeof(string)));
            //return new[] {
            //        Expression.Bind(selectType.GetProperty("AdmittedOn"), stratificationModifier)
            //    };

            Expression yearProp  = Expression.Property(prop, "Year");
            Expression monthProp = Expression.Property(prop, "Month");

            return(new[] {
                Expression.Bind(selectType.GetProperty("AdmittedOn"), firstOrDefaultAdmittedOn),
                Expression.Bind(selectType.GetProperty("AdmittedOnYear"), yearProp),
                Expression.Bind(selectType.GetProperty("AdmittedOnMonth"), monthProp)
            });
        }
예제 #17
0
 public override bool HasCriteriaWithValue(object value)
 {
     return(base.HasCriteriaWithValue(value) ||
            Criteria.Any(searchOperation => searchOperation.HasCriteriaWithValue(value)));
 }