Exemple #1
0
        /// <summary>
        /// Установки представления.
        /// </summary>
        /// <param name="control">Контрол с именнованными полями.</param>
        public void SetView(UserControl control)
        {
            if (control == null)
            {
                throw new ArgumentNullException("control");
            }

            _id = null;

            //отписываемся
            foreach (var userControlController in _modelControllers)
            {
                userControlController.GetModel().PropertyChanged -= BindedModelOnPropertyChanged;
                userControlController.GetModel().PressKey        -= BindedModelOnPressKey;
            }
            _tabControlManager = new TabControlManager();

            _modelControllers.Clear();
            _modelData.Clear();
            _comboBoxItems.Clear();

            _lastValid = false;

            _view = control;

            //ищем все прорерти
            foreach (var propertyInfo in typeof(TModel).GetProperties())
            {
                ProcessProperty(propertyInfo);
            }

            CheckModelValid(true);
        }
        public static int FindLast <T, TKey>(IList <T> list, int index, int length, TKey?key, Func <T, TKey?> selector, IComparer <TKey> comparer)
        {
            var find = -1;
            var lo   = index;
            var hi   = index + length - 1;

            while (lo <= hi)
            {
                var mid = lo + ((hi - lo) >> 1);

#if NETSTANDARD2_1
                var c = comparer.Compare(selector(list[mid]) !, key !);
#else
                var c = comparer.Compare(selector(list[mid]), key);
#endif

                if (c == 0)
                {
                    find = mid;
                    lo   = mid + 1;
                }
                else if (c < 0)
                {
                    lo = mid + 1;
                }
                else
                {
                    hi = mid - 1;
                }
            }

            return(find >= 0 ? find : ~lo);
        }
            //---------------------------------------------------------------------------------------
            // Counts the elements in the underlying data source, walking the entire thing the first
            // time MoveNext is called on this object.
            //

            protected override bool MoveNextCore(ref long currentElement)
            {
                TSource?elementUnused = default(TSource);
                TKey?   keyUnused     = default(TKey);

                QueryOperatorEnumerator <TSource, TKey> source = _source;

                if (source.MoveNext(ref elementUnused, ref keyUnused))
                {
                    // We just scroll through the enumerator and keep a running count.
                    long count = 0;
                    int  i     = 0;
                    do
                    {
                        if ((i++ & CancellationState.POLL_INTERVAL) == 0)
                        {
                            _cancellationToken.ThrowIfCancellationRequested();
                        }

                        checked
                        {
                            count++;
                        }
                    }while (source.MoveNext(ref elementUnused, ref keyUnused));

                    currentElement = count;
                    return(true);
                }

                return(false);
            }
Exemple #4
0
 public TreeSynchronizerEntry(TItem item, TKey key, TKey?parentKey, TKey[] childrenKeys)
 {
     Item         = item;
     Key          = key;
     ParentKey    = parentKey;
     ChildrenKeys = childrenKeys;
 }
Exemple #5
0
            //---------------------------------------------------------------------------------------
            // Just walks the entire data source upon its first invocation, performing the per-
            // element action for each element.
            //

            internal override bool MoveNext([MaybeNullWhen(false), AllowNull] ref TInput currentElement, ref int currentKey)
            {
                Debug.Assert(_elementAction != null, "expected a compiled operator");

                // We just scroll through the enumerator and execute the action. Because we execute
                // "in place", we actually never even produce a single value.

                // Cancellation testing must be performed here as full enumeration occurs within this method.
                // We only need to throw a simple exception here.. marshalling logic handled via QueryTaskGroupState.QueryEnd (called by ForAllSpoolingTask)
                TInput?element   = default(TInput);
                TKey?  keyUnused = default(TKey);
                int    i         = 0;

                while (_source.MoveNext(ref element, ref keyUnused))
                {
                    if ((i++ & CancellationState.POLL_INTERVAL) == 0)
                    {
                        _cancellationToken.ThrowIfCancellationRequested();
                    }
                    ;
                    _elementAction(element);
                }

                return(false);
            }
        public JsonResult GetItemForm(TKey?id)
        {
            try
            {
                var model = InitEditModel(GetToken(), id);

                return
                    (Json(new JCrudDataResult
                {
                    ResultState = CrudResultKind.Success,
                    NeedReloadModel = false,
                    Data = PartialView(EditItemViewName, model).RenderToString()
                }));
            }
            catch (Exception ex)
            {
                var innerException = string.Empty;
                if (ex.InnerException != null)
                {
                    innerException = ex.InnerException.Message;
                } //if

                _logger.ErrorFormat(
                    "Во время получения формы для редактирования сущности {0} с ключем {1} произошла ошибка {2} {3} {4} {5}", typeof(TEditViewModel).Name,
                    id, ex.Message, ex.GetType(), innerException, ex.StackTrace);
                return(Json(new JCrudErrorResult(string.Format("Произошла ошибка {0}", ex.Message))));
            } //try
        }
Exemple #7
0
 public abstract Task <CursorPaginationResponse <TKey, TEntity> > PaginateAsync <TKey>(
     Expression <Func <TEntity, TKey> > selector,
     Expression <Func <TEntity, bool> >?predicate = null,
     TKey?cursor          = null,
     int size             = 10,
     Ordering ordering    = Ordering.Descending,
     CancellationToken ct = default) where TKey : struct;
Exemple #8
0
        /// <summary>
        /// Биндит значения определенной модели.
        /// </summary>
        /// <param name="model">Модель содержащая значения для установки значений.</param>
        public void SetModelValues(TModel model)
        {
            _id = model.Id;

            foreach (var userControlController in _modelControllers)
            {
                var property = typeof(TModel).GetProperty(userControlController.GetModel().Id);
                if (property != null)
                {
                    var value = property.GetValue(model, null);
                    userControlController.GetModel().RawValue = value;
                    //для комбобокса производим реинициализацию значений
                    if (userControlController is ComboBoxController)
                    {
                        var combobox = _comboBoxItems[userControlController.GetModel().Id];
                        combobox.ReInitialize(value);
                    }
                }
            }

            foreach (var key in _modelData.Keys.ToList())
            {
                var property = typeof(TModel).GetProperty(key);

                if (property != null)
                {
                    _modelData[key] = property.GetValue(model, null);
                } //if
            }     //foreach
        }
Exemple #9
0
 /// <summary>
 /// Вызывает исключение при не нахождении определенного элемента.
 /// </summary>
 /// <param name="instance">Элемент который необходимо проверить.</param>
 /// <param name="id">Код элемента.</param>
 /// <param name="name">Наименование элемента.</param>
 protected static void RiseExceptionIfNotFound(object instance, TKey?id, string name)
 {
     if (instance == null)
     {
         throw new Exception(string.Format("Для сущности {0} не найден id {1}", name, id));
     }
 }
Exemple #10
0
        public static int FindFirst <T, TKey>(Span <T> span, TKey?key, Func <T, TKey?> selector, IComparer <TKey> comparer)
        {
            var find = -1;
            var lo   = 0;
            var hi   = span.Length - 1;

            while (lo <= hi)
            {
                var mid = lo + ((hi - lo) >> 1);

#if NETSTANDARD2_1
                var c = comparer.Compare(selector(span[mid]) !, key !);
#else
                var c = comparer.Compare(selector(span[mid]), key);
#endif

                if (c == 0)
                {
                    find = mid;
                    hi   = mid - 1;
                }
                else if (c < 0)
                {
                    lo = mid + 1;
                }
                else
                {
                    hi = mid - 1;
                }
            }

            return(find >= 0 ? find : ~lo);
        }
Exemple #11
0
        public OptionalEntityRef(Func <TEntity, TKey> funcEntityToKey)
        {
            Contract.Requires <ArgumentNullException>(funcEntityToKey != null);

            _funcEntityToKey = funcEntityToKey;
            _foreignKey      = null;
            _entity          = null;
        }
Exemple #12
0
 /// <summary>
 ///     LINQ to Objects (IEnumerable) AsHierachy() extension method
 /// </summary>
 /// <typeparam name="TEntity"> Entity class </typeparam>
 /// <typeparam name="TKey"> Property of entity class </typeparam>
 /// <param name="allItems"> Flat collection of entities </param>
 /// <param name="keySelector"> A function to extract the key from an element. </param>
 /// <param name="parentKeySelector"> A function to extract the parent key from an element. </param>
 /// <param name="rootItemId"> Value of root item Id/Key </param>
 /// <returns> Hierarchical structure of entities </returns>
 public static IEnumerable <HierarchyNode <TEntity> > AsHierarchy <TEntity, TKey>(
     this IEnumerable <TEntity> allItems,
     Func <TEntity, TKey> keySelector,
     Func <TEntity, TKey?> parentKeySelector,
     TKey?rootItemId)
     where TEntity : class
     where TKey : struct
 => CreateHierarchy(allItems, default(TEntity), keySelector, parentKeySelector, rootItemId, 0, 0);
 /// <summary>
 /// Вызывает исключение при не нахождении определенного элемента.
 /// </summary>
 /// <param name="instance">Элемент который необходимо проверить.</param>
 /// <param name="id">Код элемента.</param>
 /// <param name="name">Наименование элемента.</param>
 protected static void RiseExceptionIfNotFound(object instance, TKey?id, string name)
 {
     if (instance == null)
     {
         //TODO определить специальное исключение с перехватом.
         throw new Exception(string.Format("Для сущности {0} не найден id {1}", name, id));
     }
 }
 /// <summary>
 ///     LINQ to SQL (IQueryable) AsHierachy() extension method
 /// </summary>
 /// <typeparam name="TEntity"> Entity class </typeparam>
 /// <typeparam name="TKey"> Property of entity class. </typeparam>
 /// <param name="allItems"> Flat collection of entities </param>
 /// <param name="keySelector"> A function to extract the key from an element. </param>
 /// <param name="parentKeySelector"> A function to extract the parent key from an element. </param>
 /// <param name="rootItemId"> Value of root item Id/Key </param>
 /// <returns> Hierarchical structure of entities </returns>
 public static IEnumerable <HierarchyNode <TEntity> > AsHierarchy <TEntity, TKey>(
     this IQueryable <TEntity> allItems,
     Expression <Func <TEntity, TKey> > keySelector,
     Expression <Func <TEntity, TKey?> > parentKeySelector,
     //string parentIdProperty,
     TKey?rootItemId)
     where TEntity : class
     where TKey : struct => CreateHierarchy(allItems, null, keySelector, parentKeySelector, rootItemId, 0, 0);
Exemple #15
0
 void IEnumerator.Reset()
 {
     if (_version != _sortedList.version)
     {
         throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
     }
     _index      = 0;
     _currentKey = default;
 }
 public CardBaseEntity(bool create, TKey?userId)
     : base(create)
 {
     if (create)
     {
         this.CreateUser = userId;
         this.CreateDate = DateTime.Now;
     }
 }
Exemple #17
0
        private NotifyDictionaryChangedEventArgs(NotifyDictionaryChangedAction action, TKey?key = default, TValue?oldValue = default, TValue?newValue = default)
        {
            Assert(AssertionsEnabled && Enum.IsDefined(action));

            _action   = action;
            _key      = key;
            _oldValue = oldValue;
            _newValue = newValue;
        }
Exemple #18
0
 internal Enumerator(SortedList <TKey, TValue> sortedList, int getEnumeratorRetType)
 {
     _sortedList           = sortedList;
     _index                = 0;
     _version              = _sortedList.version;
     _getEnumeratorRetType = getEnumeratorRetType;
     _key   = default;
     _value = default;
 }
Exemple #19
0
        public static TValue GetValueOrDefault <TKey, TValue>(
            this IDictionary <TKey, TValue> self, TKey?key, TValue defaultValue = null)
            where TKey : struct
            where TValue : class
        {
            TValue value;

            return(key.HasValue && self.TryGetValue(key.Value, out value)
                ? value : defaultValue);
        }
Exemple #20
0
 public static TModel PlaceholderInstance <TModel, TKey>(this TKey?key)
     where TModel : class, IBaseModel <TKey>, new()
     where TKey : struct
 {
     return(key == null
         ? (TModel)null
         : new TModel
     {
         Id = key.Value
     });
 }
Exemple #21
0
 internal override void CreateByIdFromRegistry(TKey id, bool forLoadingFromHash)
 {
     if (!this.isJustCreated)
     {
         throw new CriticalException("Object already has an id");
     }
     this._id           = id;
     this.isJustCreated = false;
     //System.Threading.ThreadPool.QueueUserWorkItem(state => this.AfterCreate(forLoadingFromHash));
     this.AfterCreate(forLoadingFromHash);
 }
Exemple #22
0
        private static bool HandleNullableValue(TKey?value, out TKey key)
        {
            if (value.HasValue)
            {
                key = (TKey)value;
                return(true);
            }

            key = default(TKey);
            return(false);
        }
        /// <summary>Try to select the given key in the dropdown.</summary>
        /// <param name="key">The key to select.</param>
        /// <returns>Returns whether the value was selected.</returns>
        public bool TrySelect(TKey?key)
        {
            int selectedIndex = this.Options.FindIndex(p => p.Item2.Equals(key));

            if (selectedIndex >= 0)
            {
                this.Dropdown.selectedOption = selectedIndex;
                return(true);
            }

            return(false);
        }
Exemple #24
0
 public static void AddKeyValueIfNotNull <TKey, TValue>(
     this IDictionary <TKey, TValue> dictionary,
     TKey?key,
     TValue?value)
     where TKey : class
     where TValue : class
 {
     if (key != null && value != null)
     {
         dictionary.Add(key, value);
     }
 }
Exemple #25
0
        public bool TryGetMax(out TKey?max)
        {
            var root = Root;

            if (root is null)
            {
                max = default;
                return(false);
            }

            max = GetMax(root).Key;
            return(true);
        }
Exemple #26
0
        public bool TryGetMin(out TKey?min)
        {
            var root = Root;

            if (root is null)
            {
                min = default;
                return(false);
            }

            min = GetMin(root).Key;
            return(true);
        }
Exemple #27
0
        /// <inheritdoc />
        public int Compare(TKey?x, TKey?y)
        {
            var z = Arguments.EnsureNotNull(x, nameof(x));

            var result = z.CompareTo(y);

            if (result == 0)
            {
                return(1); // Handle equality as being greater
            }

            return(result);
        }
Exemple #28
0
        private static IEnumerable <HierarchyNode <TEntity> > CreateHierarchy <TEntity, TKey>(
            IEnumerable <TEntity> allItems,
            TEntity parentItem,
            Func <TEntity, TKey> idProperty,
            Func <TEntity, TKey?> parentIdProperty,
            TKey?rootItemId,
            int maxDepth,
            int depth)
            where TEntity : class
            where TKey : struct
        {
            IEnumerable <TEntity> childs;

            if (rootItemId.HasValue)
            {
                childs = allItems.Where(i => idProperty(i).Equals(rootItemId));
            }
            else
            {
                if (parentItem == null)
                {
                    childs = allItems.Where(i => parentIdProperty(i).Equals(default(TKey?)));
                }
                else
                {
                    childs = allItems.Where(i => parentIdProperty(i).Equals(idProperty(parentItem)));
                }
            }

            if (childs.Any())
            {
                depth++;

                if ((depth <= maxDepth) || (maxDepth == 0))
                {
                    foreach (var item in childs)
                    {
                        yield return
                            new HierarchyNode <TEntity>
                            {
                                Entity     = item,
                                ChildNodes =
                                    CreateHierarchy(allItems.AsEnumerable(), item, idProperty, parentIdProperty, default(TKey?), maxDepth, depth),
                                Depth  = depth,
                                Parent = parentItem
                            }
                    }
                    ;
                }
            }
        }
Exemple #29
0
        private bool TryCreateFromCurrentValues(IUpdateEntry entry, [NotNullWhen(true)] out TKey?key)
        {
            // TODO: Move into delegate
            foreach (var property in _foreignKey.Properties)
            {
                if (entry.IsConceptualNull(property))
                {
                    key = default;
                    return(false);
                }
            }

            return(_dependentKeyValueFactory.TryCreateFromCurrentValues(entry, out key));
        }
            /// <summary>
            /// Implements <see cref="System.Collections.IEnumerator.MoveNext"/>.
            /// </summary>
            public bool MoveNext()
            {
                while (this.enumerator.MoveNext())
                {
                    TKey?key = this.enumerator.Current.Key.Target;
                    if (key != null)
                    {
                        this.Current = key;
                        return(true);
                    }
                }

                return(false);
            }