예제 #1
0
        public async Task <string> GetSessionId()
        {
            var url = _queryBuilder
                      .Add("docid", "crmlogin")
                      .Add("userid", _configuration.Username)
                      .Add("password", _configuration.Password)
                      .Build();

            var response = await _gateway.GetAsync(url);

            if (response.StatusCode != HttpStatusCode.OK)
            {
                throw new Exception($"Civica is unavailable. Responded with status code: {response.StatusCode}");
            }

            var xmlResponse = await response.Content.ReadAsStringAsync();

            var deserializedResponse = _xmlParser.DeserializeXmlStringToType <SessionIdModel>(xmlResponse, "Login").Result;

            if (!deserializedResponse.ErrorCode.Text.Equals("5"))
            {
                throw new Exception($"API login unsuccessful, check credentials. Actual response: {xmlResponse}");
            }

            var sessionId = deserializedResponse.SessionID;

            if (string.IsNullOrWhiteSpace(sessionId))
            {
                throw new Exception("No session id returned");
            }

            return(sessionId);
        }
예제 #2
0
        public void Add_ShouldAddEncodedStringToUrl(string key, string value)
        {
            var expectedUrl = $"?outputtype=xml&{HttpUtility.UrlEncode(key)}={HttpUtility.UrlEncode(value)}";

            var response = _queryBuild.Add(key, value).Build();

            Assert.Equal(expectedUrl, response);
        }
예제 #3
0
        protected void AddEnumFieldSearch <TTokenType, TEnumType>(Func <TEnumType[], ISearchTerm> valuesToTerm, ISearchExpression expression, IQueryBuilder queryBuilder)
            where TTokenType : ArgumentToken
            where TEnumType : struct, IConvertible
        {
            if (queryBuilder == null)
            {
                return;
            }

            var tokenGroups = expression.Tokens
                              .OfType <TTokenType>()
                              .GroupBy(x => x.Context.GetTermOccur());

            foreach (var tokenGroup in tokenGroups)
            {
                var values = tokenGroup
                             .Select(token => Enum.TryParse(token.Id, out TEnumType enumValue) ? (TEnumType?)enumValue : null)
                             .Where(value => value != null)
                             .OfType <TEnumType>()
                             .ToArray();

                if (values.Any())
                {
                    queryBuilder.Add(valuesToTerm(values), tokenGroup.Key);
                }
            }
        }
 protected override void AddIsSetSearch(IQueryBuilder queryBuilder, string attributeName, IField field, TermOccur termOccur)
 {
     if (attributeName == SystemTaskAttributes.DEADLINE_DATE)
     {
         queryBuilder.Add(AttributeFields.DateTime(attributeName).BeInRange(DateTime.MinValue, DateTime.MaxValue.AddDays(-1)), termOccur);
     }
     else
     {
         base.AddIsSetSearch(queryBuilder, attributeName, field, termOccur);
     }
 }
예제 #5
0
        protected void AddAttributesSearch(ISearchExpression expression, IQueryBuilder attributesQueryBuilder)
        {
            if (attributesQueryBuilder == null)
            {
                return;
            }

            var attributeIsSetTokens = expression.Tokens.OfType <AttributeIsSetToken>().ToList();

            foreach (var group in attributeIsSetTokens.GroupByAttributeAndOccur())
            {
                var token = group.First();
                var field = GetAttributeField(token, group.Key.AttributeName);
                AddIsSetSearch(attributesQueryBuilder, group.Key.AttributeName, field, group.Key.Occur);
            }

            var stringAttributeValueTokens = expression.Tokens.OfType <StringAttributeValueToken>().ToList();

            foreach (var group in stringAttributeValueTokens.GroupByAttributeAndOccur())
            {
                var attributeName = group.Key.AttributeName;
                var field         = AttributeFields.String(attributeName);

                var values = group.Select(token => EscapeStringValue(token.Value));
                attributesQueryBuilder.AddAnyOf(values.Select(x => field.Be(x)).ToArray(), group.Key.Occur);
            }

            var orgUnitValueTokens = expression.Tokens.OfType <OrgUnitAttributeValueToken>().ToList();

            foreach (var group in orgUnitValueTokens.GroupByAttributeAndOccur())
            {
                var attributeName = group.Key.AttributeName;
                var field         = AttributeFields.OrgUnit(attributeName);

                var positions = group
                                .Select(token => token is OrgUnitMeArgumentToken
                        ? _context.GetCurrentPerson()
                        : _context.GetPerson(Convert.ToInt32(token.Id)))
                                .SelectMany(x => x.Positions)
                                .Distinct()
                                .ToArray();
                attributesQueryBuilder.Add(field.BeAnyOf(positions), group.Key.Occur);
            }

            var stateAttributeValueTokens = expression.Tokens.OfType <UserStateAttributeValueToken>().ToList();

            foreach (var group in stateAttributeValueTokens.GroupByAttributeAndOccur())
            {
                var field = AttributeFields.State(group.Key.AttributeName);
                attributesQueryBuilder.Add(field.BeAnyOf(group.Select(x => Guid.Parse(x.Id)).Distinct().ToArray()), group.Key.Occur);
            }

            var dateAttributesNames = expression.Tokens.OfType <DateAttributeNameToken>();

            foreach (var dateAttributeNameToken in dateAttributesNames)
            {
                var dateFieldName = dateAttributeNameToken.Data;
                var dateField     = AttributeFields.DateTime(dateFieldName);
                AddDateSearch(
                    token => token.Context[TokenBase.GroupParentKey].Value is DateAttributeNameToken && token.Context[nameof(AttributeNameTokenBase)].Value as string == dateFieldName,
                    datesRange => dateField.BeInRange(datesRange.FromUtc, datesRange.ToUtc),
                    null,
                    expression, attributesQueryBuilder, null);
            }

            var numberAttributeTokens   = expression.Tokens.OfType <NumberAttributeValueToken>().ToList();
            var fromNumAttributesTokens = numberAttributeTokens.Where(x => (bool?)x.Context[RangeToken.IsRangeTopKey].Value != true).ToList();
            var toNumAttributesToknes   = numberAttributeTokens.Where(x => (bool?)x.Context[RangeToken.IsRangeTopKey].Value == true).ToList();

            var numAttributesRanges = new List <NumAttributeRange>();

            foreach (var fromRangeToken in fromNumAttributesTokens)
            {
                var attributeName = fromRangeToken.Context[nameof(AttributeNameTokenBase)].Value as string;
                var fromValue     = double.Parse(fromRangeToken.Value, CultureInfo.InvariantCulture);
                var isFloat       = fromRangeToken.Context[nameof(FloatNumberAttributeNameToken)].Value != null;

                if (fromRangeToken.Context[TokenBase.GroupParentKey].Value is NumberAttributeGreaterToken)
                {
                    numAttributesRanges.Add(new NumAttributeRange(attributeName, isFloat, fromValue, double.PositiveInfinity, fromRangeToken.Context));
                    continue;
                }

                if (fromRangeToken.Context[TokenBase.GroupParentKey].Value is NumberAttributeLessToken)
                {
                    numAttributesRanges.Add(new NumAttributeRange(attributeName, isFloat, double.NegativeInfinity, fromValue, fromRangeToken.Context));
                    continue;
                }

                var groupParent  = fromRangeToken.Context[TokenBase.GroupParentKey].Value;
                var toRangeToken = toNumAttributesToknes.FirstOrDefault(x => ReferenceEquals(groupParent, x.Context[TokenBase.GroupParentKey].Value));
                var toValue      = toRangeToken != null ? (double?)double.Parse(toRangeToken.Value, CultureInfo.InvariantCulture) : null;

                numAttributesRanges.Add(new NumAttributeRange(attributeName, isFloat, fromValue, toValue, fromRangeToken.Context));
            }

            foreach (var range in numAttributesRanges)
            {
                var doubleFiled = AttributeFields.Double(range.AttrName);
                var longField   = AttributeFields.Integer(range.AttrName);

                var fromDoubleValue = range.From;
                var fromLongValue   = double.IsNegativeInfinity(fromDoubleValue) ? long.MinValue : Convert.ToInt64(Math.Floor(fromDoubleValue));

                if (range.To == null)
                {
                    var searchTerm = range.IsFloat ? doubleFiled.Be(fromDoubleValue) : longField.Be(fromLongValue);
                    attributesQueryBuilder.Add(searchTerm, range.Context.GetTermOccur());
                }
                else
                {
                    var toDoubleValue = (double)range.To;
                    var toLongValue   = double.IsPositiveInfinity(toDoubleValue) ? long.MaxValue : Convert.ToInt64(Math.Floor(toDoubleValue));

                    var searchTerm = range.IsFloat ? doubleFiled.BeInRange(fromDoubleValue, toDoubleValue) : longField.BeInRange(fromLongValue, toLongValue);
                    attributesQueryBuilder.Add(searchTerm, range.Context.GetTermOccur());
                }
            }
        }
예제 #6
0
        protected virtual void AddIsSetSearch(IQueryBuilder queryBuilder, string attributeName, IField field, TermOccur termOccur)
        {
            var term = field.Exists();

            queryBuilder.Add(term, termOccur);
        }
예제 #7
0
        public async Task <List <BenefitsClaimSummary> > GetBenefits(string personReference)
        {
            var cacheResponse = await _cacheProvider.GetStringAsync($"{personReference}-{ECacheKeys.Benefits}");

            if (!string.IsNullOrEmpty(cacheResponse))
            {
                return(JsonConvert.DeserializeObject <List <BenefitsClaimSummary> >(cacheResponse));
            }

            var sessionId = await _sessionProvider.GetSessionId(personReference);

            var url = _queryBuilder
                      .Add("docid", "hbsel")
                      .Add("sessionId", sessionId)
                      .Build();

            var body = new FormUrlEncodedContent(new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("claimsts", "All")
            });

            var response = await _gateway.PostAsync(url, body);

            var content = await response.Content.ReadAsStringAsync();

            var parsedResponse = _xmlParser.DeserializeXmlStringToType <BenefitsClaimsSummaryResponse>(content, "HBSelectDoc");
            var claimSummary   = parsedResponse.Claims.Summary;

            claimSummary.ForEach(_ => _.PersonName = parsedResponse.PersonName);

            _ = _cacheProvider.SetStringAsync($"{personReference}-{ECacheKeys.Benefits}", JsonConvert.SerializeObject(claimSummary));

            return(claimSummary);
        }
예제 #8
0
        internal static SelectQuery <TPoco> JoinOn(
            IQueryBuilder builder,
            KeyValuePair <DbClassInfoCache, DbPropertyInfoCache>[] path,
            JoinMode joinAs = null,
            Func <ConditionalEvalQuery <TPoco>, ConditionalEvalQuery <TPoco> > joinCondition = null)
        {
            joinAs = joinAs ?? JoinMode.Default;

            IQueryBuilder target      = builder;
            var           targetAlias = target.ContainerObject
                                        .SearchLast <ISelectableQueryPart>(e => !(e is JoinTableQueryPart))
                                        .Alias;
            var parentJoinPart = builder.ContainerObject.Joins;

            foreach (var keyValuePair in path)
            {
                var targetTable = target.ContainerObject.Search(targetAlias);

                var pathOfJoin = target.ContainerObject.GetPathOf(targetAlias) + "." +
                                 keyValuePair.Value.PropertyName;
                var parentAlias = target.ContainerObject
                                  .CreateTableAlias(pathOfJoin);

                var joinExists = parentJoinPart.FirstOrDefault(e => e.Alias.Equals(parentAlias));
                if (joinExists != null)
                {
                    parentJoinPart = joinExists.DependingJoins;
                    targetAlias    = parentAlias;
                    continue;
                }


                Type referenceType;
                if (keyValuePair.Value.CheckForListInterface())
                {
                    referenceType = keyValuePair.Value.PropertyType.GetElementType();
                    if (referenceType == null)
                    {
                        referenceType = keyValuePair.Value.PropertyType.GetGenericArguments().FirstOrDefault();
                    }
                }
                else
                {
                    referenceType = keyValuePair.Value.PropertyType;
                }

                var referencedTypeCache = target.ContainerObject.AccessLayer.GetClassInfo(referenceType);

                var targetAliasOfJoin = new QueryIdentifier
                {
                    QueryIdType = QueryIdentifier.QueryIdTypes.Table,
                    Value       = referencedTypeCache.TableName
                };

                ColumnInfo onSourceTableKey;
                ColumnInfo selfPrimaryKey;

                var referenceColumn = keyValuePair.Value.ForginKeyAttribute?.Attribute;

                if (referenceColumn == null)
                {
                    throw new InvalidOperationException("There is no known reference from table " +
                                                        $"'{keyValuePair.Key.Type}' " +
                                                        "to table " +
                                                        $"'{referenceType}'." +
                                                        "Use a ForeignKeyDeclarationAttribute to connect both");
                }

                var forginColumns = DbAccessLayer.GetSelectableColumnsOf(referencedTypeCache)
                                    .Select(e => new ColumnInfo(e, parentAlias, target.ContainerObject))
                                    .ToList();

                selfPrimaryKey
                    = targetTable.Columns.FirstOrDefault(e => e.IsEquivalentTo(referenceColumn.ForeignKey));
                onSourceTableKey
                    = forginColumns.FirstOrDefault(e => e.IsEquivalentTo(referenceColumn.ReferenceKey));

                var joinTableQueryPart = new JoinTableQueryPart(
                    targetAliasOfJoin,
                    targetAlias,
                    parentAlias,
                    keyValuePair.Key.Type,
                    onSourceTableKey,
                    selfPrimaryKey,
                    forginColumns,
                    keyValuePair.Value,
                    joinAs);

                parentJoinPart.Add(joinTableQueryPart.JoinParseInfo);
                parentJoinPart = joinTableQueryPart.JoinParseInfo.DependingJoins;

                target.ContainerObject.SearchLast <ISelectQueryPart>().AddJoin(joinTableQueryPart);
                target      = target.Add(joinTableQueryPart);
                targetAlias = parentAlias;
            }

            if (joinCondition != null)
            {
                var lastJoin   = target.ContainerObject.SearchLast <JoinTableQueryPart>();
                var condition  = new ConditionStatementQueryPart();
                var tempSelect = new ConditionalEvalQuery <TPoco>(target.Add(condition));
                joinCondition(tempSelect);
                lastJoin.Condition = condition;
            }

            return(new SelectQuery <TPoco>(target));
        }