Exemplo n.º 1
0
        /// <summary> Метод "Get" для свойств, имеющих тип DBObject[], которые содержут объекты, ссылающиеся на данный объект </summary>
        protected T[] GetBindedArrayPropertyValue <T>(string propertyName, string linkedObjectPropertyName = null) where T : DBObject
        {
            //Имя свойства объекта, массив которых нужно получить
            if (linkedObjectPropertyName == null)
            {
                linkedObjectPropertyName = this.GetType().Name;
            }
            //Свойство, содержащее ID объекта
            string linkedObjectIDFieldName = string.Format("{0}ID", linkedObjectPropertyName);
            //Свойство, вызовшее данный метод
            PropertyInfo thisPropertyInfo = this.GetType().GetProperty(propertyName);
            //Свойство объекта, массив которых нужно получить
            FieldInfo arrayObjectsIDFieldInfo = typeof(T).GetField(linkedObjectIDFieldName, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);

            //Если свойство не найдено, значит класс определён неверно...
            if (arrayObjectsIDFieldInfo == null)
            {
                //...выбрасываем исключение
                throw new Exception(string.Format("Неверное определение класса {0}: отсутствует запрошенное свойство {1}", typeof(T).Name, linkedObjectPropertyName));
            }
            T[] arrayObjects = this.DataStorage
                               .GetDBObjects(typeof(T))
                               .Where(x => arrayObjectsIDFieldInfo.GetValue(x) as id == this.ID)
                               //Применяем фильтрацию по указанному в описании класса условию
                               .ApplyConditions(thisPropertyInfo)
                               .Cast <T>()
                               .ToArray();
            //Применяем сортировку по указанному в описании класса свойству
            SortingAttribute sortingAttribute = thisPropertyInfo.GetAttribute <SortingAttribute>();

            if (sortingAttribute != null)
            {
                MemberInfo sortingMemberInfo = sortingAttribute.GetMemberInfo(typeof(T));
                if (sortingMemberInfo is PropertyInfo)
                {
                    arrayObjects = arrayObjects.OrderBy(x => (sortingMemberInfo as PropertyInfo).GetValue(x, null)).ToArray();
                }
                else if (sortingMemberInfo is MethodInfo)
                {
                    arrayObjects = arrayObjects.OrderBy(x => (sortingMemberInfo as MethodInfo).Invoke(x, null)).ToArray();
                }
            }
            //Результат
            return(arrayObjects);
        }
Exemplo n.º 2
0
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            var modelName           = bindingContext.ModelName;
            var valueProviderResult = bindingContext.ValueProvider.GetValue(modelName);

            if (valueProviderResult == ValueProviderResult.None)
            {
                return(Task.CompletedTask);
            }

            bindingContext.ModelState.SetModelValue(modelName, valueProviderResult);
            var value = valueProviderResult.FirstValue;

            if (string.IsNullOrEmpty(value))
            {
                return(Task.CompletedTask);
            }

            var sortings = SortingAttribute.GetSortings(value);

            bindingContext.Result = ModelBindingResult.Success(sortings);
            return(Task.CompletedTask);
        }
Exemplo n.º 3
0
        private DataPage <TResource> ExecuteAdjustedQuery <TResource>(string query, Pagination pagination, SortingInstructions sorting, AttributesToFetch attributes = null) where TResource : RmResource
        {
            attributes = attributes ?? AttributesToFetch.All;

            Initialize();

            var ctx = LogContext.WithConfigFormat();

            _log.Debug(ctx.Format("Executing query {0} with paging: {1}, sorting {2} and attributes {3}"), query, pagination.ToJSON(), sorting.ToJSON(), attributes.GetNames().ToJSON());

            // first request - only to get enumeration context and total rows count
            var enumerationRequest = new EnumerationRequest(query);

            // do not fetch any items - total count only; however this cannot be set to 0 because then total count is not returned (is always set to 0)
            enumerationRequest.MaxElements = 1;
            // get only ObjectID attribute to minimize overhead caused by this operation which returns elements not used for further processing
            enumerationRequest.Selection = new List <string>
            {
                RmResource.AttributeNames.ObjectID.Name
            };
            var enumerateResponse = _pagedQueriesClient.Enumerate(enumerationRequest);

            long totalCount = enumerateResponse.Count ?? 0;

            // second request - to actually get desired data
            var pullRequest = new PullRequest();

            // set enumeration context from previous query
            pullRequest.EnumerationContext = enumerateResponse.EnumerationContext;

            // if attributes names to fetch defined...
            var attributeNames = attributes.GetNames();

            if (attributeNames != null)
            {
                // ... set them to context
                pullRequest.EnumerationContext.Selection         = new Selection();
                pullRequest.EnumerationContext.Selection.@string = attributeNames.ToList();
            }
            else
            {
                pullRequest.EnumerationContext.Selection = null;
            }

            // if paging defined...
            if (pagination.PageSize != Pagination.AllPagesSize)
            {
                // set current page's first row index...
                pullRequest.EnumerationContext.CurrentIndex = pagination.GetFirstRowIndex();
                // ...and page size
                pullRequest.MaxElements = pagination.PageSize;
            }
            // ... if not - get all elements
            else
            {
                // reset current row index...
                pullRequest.EnumerationContext.CurrentIndex = 0;
                // ... page size to max (this may throw if message size exceeds configured maximum, but this situation - getting all items using this method - is not likely to happen)
                pullRequest.MaxElements = int.MaxValue;
            }

            // if sorting defined...
            if (sorting != SortingInstructions.None)
            {
                var sortingAttribute = new SortingAttribute()
                {
                    Ascending = sorting.Order == SortOrder.Ascending,
                    Value     = sorting.AttributeName
                };
                // due to implementation details of these classes, new instances of each of them needs to be created
                pullRequest.EnumerationContext.Sorting = new Sorting
                {
                    SortingAttribute = new List <SortingAttribute>
                    {
                        sortingAttribute
                    }
                };
            }

            var pullResponse = _pagedQueriesClient.Pull(pullRequest);
            var results      = _defaultClient.ResourceFactory.CreateResource(pullResponse)
                               .Cast <TResource>()
                               .ToList();

            log_query_executed(ctx, "Paged query {0} returned {1} results and {2} total count", query, results.Count, totalCount);

            return(new DataPage <TResource>(results, totalCount));
        }