Example #1
0
        protected override void ExecuteStatement(ExecutionContext context)
        {
            if (!context.Request.Context.CursorExists(CursorName))
            {
                throw new StatementException(String.Format("The cursor '{0}' was not found in the current context.", CursorName));
            }

            var cursor = context.Request.Context.FindCursor(CursorName);

            if (cursor == null)
            {
                throw new StatementException(String.Format("The cursor '{0}' was not found in the current context.", CursorName));
            }
            if (cursor.Status == CursorStatus.Closed)
            {
                throw new StatementException(String.Format("The cursor '{0}' was already closed.", CursorName));
            }

            int offset = -1;

            if (OffsetExpression != null)
            {
                offset = OffsetExpression.EvaluateToConstant(context.Request, null);
            }

            var row = cursor.Fetch(Direction, offset);

            if (row != null)
            {
                var result = new VirtualTable(row.Table, new List <int> {
                    row.RowId.RowNumber
                });
                context.SetResult(result);
            }
        }
Example #2
0
        private void DoSearch(ToolStripTextBox text, VirtualTable producersTable)
        {
            var searchText = text.Text;
            List <ProducerDto> producers;

            if (!String.IsNullOrEmpty(searchText))
            {
                producers = _producers.Where(p => p.Name.ToLower().Contains(searchText.ToLower())).ToList();
            }
            else
            {
                producers = _producers;
            }

            if (producers.Count > 0)
            {
                producersTable.TemplateManager.Source = producers;
                producersTable.Host.Focus();
            }
            else
            {
                MessageBox.Show("По вашему запросу ничеого не найдено", "Результаты поиска",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Warning);
            }
        }
Example #3
0
        public ProducerSearcher(List <ProducerDto> producers)
        {
            _producers = producers;
            var producersTable = new VirtualTable(new TemplateManager <ProducerDto>(
                                                      () => Row.Headers("Производитель"),
                                                      p => Row.Cells(p.Name)));

            _table = producersTable;

            producersTable.CellSpacing = 1;

            ToolStrip  = new ToolStrip();
            searchText = new ToolStripTextBox();

            ToolStrip.Items.Add(searchText);
            var searchButton = new ToolStripButton {
                Text = "Поиск"
            };

            ToolStrip.Items.Add(searchButton);
            producersTable.RegisterBehavior(
                new RowSelectionBehavior(),
                new ToolTipBehavior());

            searchButton.Click += (sender, args) => DoSearch(searchText, producersTable);
            searchText.InputMap().KeyDown(Keys.Enter, () => DoSearch(searchText, producersTable));
            producersTable.TemplateManager.Source = producers;
        }
Example #4
0
 internal void BuildVirtualTable()
 {
     if (VirtualTableBuilt)
     {
         return;
     }
     mVirtualTableBuilt = true;
     if (BaseType != null)
     {
         BaseType.BuildVirtualTable();
         VirtualTable.AddRange(BaseType.VirtualTable);
         foreach (KeyValuePair <HLMethod, int> kv in BaseType.VirtualLookup)
         {
             VirtualLookup.Add(kv.Key, kv.Value);
         }
         foreach (KeyValuePair <HLMethod, HLMethod> kv in VirtualMap.Where(p => p.Key.Container != this))
         {
             int index = VirtualLookup[kv.Key];
             VirtualTable[index] = kv.Value;
         }
     }
     foreach (KeyValuePair <HLMethod, HLMethod> kv in VirtualMap.Where(p => p.Key.Container == this))
     {
         int index = VirtualTable.Count;
         VirtualTable.Add(kv.Value);
         VirtualLookup.Add(kv.Key, index);
     }
 }
        public IActionResult AddTable([FromForm] VirtualTable formData)
        {
            _context.Set <VirtualTable>().Add(formData);

            _context.SaveChanges();

            return(RedirectToAction("Index"));
        }
 internal LowLevelNodeTraits(StorageDefinition def, VirtualTable table, DataPortDeclarations portDeclarations, KernelLayout kernelLayout)
 {
     IsCreated    = true;
     Storage      = def;
     VTable       = table;
     DataPorts    = portDeclarations;
     KernelLayout = kernelLayout;
 }
 internal LowLevelNodeTraits(StorageDefinition def, VirtualTable table)
 {
     IsCreated    = true;
     Storage      = def;
     VTable       = table;
     DataPorts    = new DataPortDeclarations();
     KernelLayout = default;
 }
Example #8
0
        public ShowAssortmentForProducer(uint producerId, Pager <AssortmentDto> assortments)
        {
            Text        = "Ассортимент";
            MinimumSize = new Size(640, 480);

            var tools = new ToolStrip()
                        .Button("Удалить (Delete)", Delete);

            var navigationToolStrip = new ToolStrip()
                                      .Button("Prev", "Предыдущая страница")
                                      .Label("PageLabel", "")
                                      .Button("Next", "Следующая страница");

            assortmentTable = new VirtualTable(new TemplateManager <AssortmentDto>(
                                                   () => Row.Headers(new Header("Проверен").AddClass("CheckBoxColumn1"), "Продукт", "Производитель"),
                                                   a => {
                var row = Row.Cells(new CheckBoxInput(a.Checked).Attr("Name", "Checked"), a.Product, a.Producer);
                if (a.Id == Settings.Default.BookmarkAssortimentId)
                {
                    ((IDomElementWithChildren)row.Children.ElementAt(1)).Prepend(new TextBlock {
                        Class = "BookmarkGlyph"
                    });
                }
                return(row);
            }));
            assortmentTable.CellSpacing = 1;
            assortmentTable.RegisterBehavior(
                new RowSelectionBehavior(),
                new ToolTipBehavior(),
                new ColumnResizeBehavior(),
                new InputController());
            assortmentTable.Behavior <ColumnResizeBehavior>().ColumnResized += column => WidthHolder.Update(assortmentTable, column, WidthHolder.AssortimentWidths);
            assortmentTable.TemplateManager.ResetColumns();
            assortmentTable.Host
            .InputMap()
            .KeyDown(Keys.Delete, Delete);

            assortmentTable.Host.InputMap()
            .KeyDown(Keys.Escape, Close);

            Controls.Add(assortmentTable.Host);
            Controls.Add(navigationToolStrip);
            Controls.Add(tools);

            navigationToolStrip.ActAsPaginator(
                assortments,
                page => {
                Pager <AssortmentDto> pager = null;
                Action(s => { pager = s.ShowAssortmentForProducer(producerId, page); });
                assortmentTable.TemplateManager.Source = pager.Content.ToList();
                return(pager);
            });

            assortmentTable.TemplateManager.Source = assortments.Content.ToList();

            Shown += (s, a) => assortmentTable.Host.Focus();
        }
Example #9
0
        public void Rebuild_view_port_on_change()
        {
            var table = new VirtualTable(new TemplateManager <string>(
                                             () => Row.Headers("Тест"),
                                             value => Row.Cells(value)));

            var list = new ObservableCollection <string>();

            table.TemplateManager.Source = list;
            list.Add("test");
            Assert.That(table.ViewPort.ToString(), Is.StringContaining("test"));
        }
Example #10
0
        public void Sort_observable_collection()
        {
            var table = new VirtualTable(new TemplateManager <Tuple <string> >(
                                             () => Row.Headers(new Header("Тест").Sortable("Item1")),
                                             x => Row.Cells(x.Item1)));

            table.RegisterBehavior(new SortInList());

            var list = new ObservableCollection2 <Tuple <string> >(Enumerable.Range(0, 10).Select(x => Tuple.Create(x.ToString())).ToList());

            table.TemplateManager.Source = list;
            table.Behavior <SortBehavior>().SortBy("Item1");
        }
Example #11
0
        // evaluation blackboard
        //private int[,] spacetime;

        public int Evaluate(Problem problem, Chromosome solution, List <Booking> bookings)
        {
            int result = 0;

            int [,] spacetime = new int[problem.Restaurant.Tables.Count(), problem.Restaurant.MaxTime];

            /*
             * for (int t = 0; t < tables; t++)
             *  for (int m = 0; m < maxTime; m++)
             *      spacetime[t, m] = 0;
             */
            int geneNr = 0;

            foreach (Booking booking in problem.GoalBookings)
            {
                VirtualTable vt = problem.Restaurant.VirtualTables[solution.VirtualTableIds[geneNr]];

                foreach (int tableId in vt.TableIds)
                {
                    for (int time = booking.Start; time < booking.End; time++)
                    {
                        spacetime[tableId, time]++;
                    }
                }

                // punishment for every booking that has a VT with too few seats
                if (vt.Capacity < booking.Guests)
                {
                    result += booking.Guests - vt.Capacity;
                }

                geneNr++;
            }

            for (int table = 0; table < problem.Restaurant.Tables.Count(); table++)
            {
                for (int time = 0; time < problem.Restaurant.MaxTime; time++)
                {
                    result += spacetime[table, time] > 1 ? spacetime[table, time] - 1 : 0;
                }
            }



            return(result);
        }
Example #12
0
        public static void Update(VirtualTable table, Column column, List <int> widths)
        {
            var element = column;

            do
            {
                widths[table.Columns.IndexOf(element)] = element.ReadonlyStyle.Get(StyleElementType.Width);
                var node = table.Columns.Find(element).Next;
                if (node != null)
                {
                    element = node.Value;
                }
                else
                {
                    element = null;
                }
            } while (element != null);
        }
Example #13
0
        public ShowOffers(List <OfferView> offers)
        {
            MinimumSize = new Size(640, 480);
            KeyPreview  = true;
            Text        = "Предложения";
            var offersTable = new VirtualTable(new TemplateManager <OfferView>(
                                                   () => {
                var row = Row.Headers();

                var header = new Header("Поставщик").Sortable("Supplier");
                header.InlineStyle.Set(StyleElementType.Width, WidthHolder.OffersWidths[0]);
                row.Append(header);

                header = new Header("Наименование").Sortable("ProductSynonym");
                header.InlineStyle.Set(StyleElementType.Width, WidthHolder.OffersWidths[2]);
                row.Append(header);

                header = new Header("Производитель").Sortable("ProducerSynonym");
                header.InlineStyle.Set(StyleElementType.Width, WidthHolder.OffersWidths[3]);
                row.Append(header);
                return(row);
            },
                                                   offer => Row.Cells(offer.Supplier,
                                                                      offer.ProductSynonym,
                                                                      offer.ProducerSynonym)));

            offersTable.CellSpacing = 1;
            offersTable.RegisterBehavior(
                new ToolTipBehavior(),
                new ColumnResizeBehavior(),
                new SortInList());
            offersTable.TemplateManager.Source = offers;
            offersTable.Behavior <ColumnResizeBehavior>().ColumnResized += column => WidthHolder.Update(offersTable, column, WidthHolder.OffersWidths);
            offersTable.TemplateManager.ResetColumns();
            Controls.Add(offersTable.Host);
            this.InputMap().KeyDown(Keys.Escape, Close);
        }
Example #14
0
        public static ITable ExhaustiveSelect(this ITable table, IQueryContext context, SqlExpression expression)
        {
            var result = table;

            // Exit early if there's nothing in the table to select from
            int rowCount = table.RowCount;
            if (rowCount > 0) {
                var tableResolver = table.GetVariableResolver();
                List<int> selectedSet = new List<int>(rowCount);

                foreach (var row in table) {
                    int rowIndex = row.RowId.RowNumber;

                    var rowResolver = tableResolver.ForRow(rowIndex);

                    // Resolve expression into a constant.
                    var exp = expression.Evaluate(context, rowResolver);
                    if (exp.ExpressionType != SqlExpressionType.Constant)
                        throw new NotSupportedException();

                    var value = ((SqlConstantExpression) exp).Value;
                    // If resolved to true then include in the selected set.
                    if (!value.IsNull && value.Type is BooleanType &&
                        value == true) {
                        selectedSet.Add(rowIndex);
                    }
                }

                result = new VirtualTable(table, selectedSet); ;
            }

            return result;
        }
Example #15
0
        private void compute(ComputationContext ctx)
        {
            foreach (TypeDefinition trait in this.AssociatedTraits)
            {
                trait.computeAncestors(ctx, new HashSet <TypeDefinition>());
            }
            computeAncestors(ctx, new HashSet <TypeDefinition>());

            IEnumerable <INode> owned_nodes = this.ChildrenNodes.Concat(this.AssociatedTraits.SelectMany(it => it.ChildrenNodes));

            owned_nodes.WhereType <ISurfable>().ForEach(it => it.Surfed(ctx));

            // --

            if (this.Modifier.HasMutable &&
                (!this.Modifier.HasHeapOnly || this.NestedFunctions.Any(it => it.IsCopyInitConstructor(ctx))))
            {
                // creating counterparts of mutable methods

                // todo: this should be implemented differently -- instead of creating methods, creating expressions
                // copy-cons, mutable call, return obj
                // on demand, in-place, when const non-existing method is called

                HashSet <string> const_functions = this.NestedFunctions.Where(f => !f.Modifier.HasMutable).Concat(
                    this.Inheritance.OrderedAncestorsIncludingObject.SelectMany(it => it.TargetType.NestedFunctions
                                                                                .Where(f => !f.Modifier.HasMutable && !f.Modifier.HasPrivate)))
                                                   .Select(it => it.Name.Name)
                                                   .ToHashSet();

                foreach (FunctionDefinition func in this.NestedFunctions.Where(it => it.Modifier.HasMutable).StoreReadOnly())
                {
                    string const_name = NameFactory.UnmutableName(func.Name.Name);
                    if (const_functions.Contains(const_name))
                    {
                        continue;
                    }

                    if (!ctx.Env.IsOfUnitType(func.ResultTypeName))
                    {
                        continue;
                    }

                    INameReference result_typename = NameFactory.ItNameReference();
                    if (this.Modifier.HasHeapOnly)
                    {
                        result_typename = NameFactory.PointerNameReference(result_typename);
                    }

                    var instructions = new List <IExpression>();
                    if (this.Modifier.HasHeapOnly)
                    {
                        instructions.Add(VariableDeclaration.CreateStatement("cp", null,
                                                                             ExpressionFactory.HeapConstructor(NameFactory.ItNameReference(), NameReference.CreateThised())));
                    }
                    else
                    {
                        // explicit typename is needed, because otherwise we would get a reference to this, not value (copy)
                        instructions.Add(VariableDeclaration.CreateStatement("cp", NameFactory.ItNameReference(),
                                                                             NameReference.CreateThised()));
                    }

                    instructions.Add(FunctionCall.Create(NameReference.Create("cp", func.Name.Name),
                                                         func.Parameters.Select(it => NameReference.Create(it.Name.Name)).ToArray()));
                    instructions.Add(Return.Create(NameReference.Create("cp")));

                    FunctionDefinition const_func = FunctionBuilder.Create(const_name, func.Name.Parameters,
                                                                           result_typename,
                                                                           Block.CreateStatement(instructions))
                                                    .SetModifier(EntityModifier.AutoGenerated)
                                                    // native methods have parameters with forbidden read
                                                    .Parameters(func.Parameters.Select(it => it.CloneAsReadable()));

                    this.AddNode(const_func);
                    const_func.Surfed(ctx);
                }
            }



            if (this.Modifier.HasEnum)
            {
                // finally we are at point when we know from which offset we can start setting ids for enum cases

                FunctionDefinition zero_constructor = this.NestedFunctions.Single(it => it.IsZeroConstructor() && it.Modifier.HasStatic);
                if (zero_constructor.IsComputed)
                {
                    throw new System.Exception("Internal error -- we cannot alter the body after the function was already computed");
                }

                int enum_ord = this.InstanceOf.PrimaryAncestors(ctx).Select(it => it.TargetType)
                               .Sum(it => it.NestedFields.Count(f => f.Modifier.HasEnum));

                foreach (VariableDeclaration decl in this.NestedFields.Where(it => it.Modifier.HasEnum))
                {
                    zero_constructor.UserBody.Append(decl.CreateFieldInitCall(NatLiteral.Create($"{enum_ord++}")));
                }
            }

            // base method -> derived (here) method
            var virtual_mapping = new VirtualTable(isPartial: false);

            foreach (EntityInstance parent_instance in this.Inheritance.MinimalParentsIncludingObject
                     .Concat(this.AssociatedTraits.SelectMany(it => it.Inheritance.MinimalParentsIncludingObject))
                     .Distinct(EntityInstance.Comparer)
                     .Reverse())
            {
                virtual_mapping.OverrideWith(parent_instance.TargetType.InheritanceVirtualTable);
            }

            IEnumerable <FunctionDefinition> all_nested_functions = this.AllNestedFunctions
                                                                    .Concat(this.AssociatedTraits.SelectMany(it => it.AllNestedFunctions));

            // derived (here) method -> base methods
            Dictionary <FunctionDefinition, List <FunctionDefinition> > derivation_mapping = all_nested_functions
                                                                                             .Where(it => it.Modifier.HasOverride)
                                                                                             .ToDictionary(it => it, it => new List <FunctionDefinition>());

            var inherited_member_instances = new HashSet <EntityInstance>(EntityInstance.Comparer);

            var missing_func_implementations = new List <FunctionDefinition>();

            foreach (EntityInstance ancestor in this.Inheritance.OrderedAncestorsIncludingObject
                     .Concat(this.AssociatedTraits.SelectMany(it => it.Inheritance.OrderedAncestorsIncludingObject))
                     .Distinct(EntityInstance.Comparer))
            {
                // special case are properties -- properties are in fact not inherited, their accessors are
                // however user sees properties, so we get members here (including properties), but when we compute
                // what function overrode which, we use really functions, and only having them in hand we check if
                // they are property accessors
                IEnumerable <EntityInstance> members = (ancestor.TargetType.AvailableEntities ?? Enumerable.Empty <EntityInstance>())
                                                       .Where(it => it.Target is IMember);

                foreach (EntityInstance entity_instance in members
                         .Where(it => it.Target.Modifier.HasPublic || it.Target.Modifier.HasProtected)
                         .Where(it => !(it.Target is FunctionDefinition func) || !func.IsAnyConstructor()))
                {
                    EntityInstance translated = entity_instance.TranslateThrough(ancestor);
                    inherited_member_instances.Add(translated);
                }

                foreach (FunctionDerivation deriv_info in TypeDefinitionExtension.PairDerivations(ctx, ancestor, all_nested_functions))
                {
                    if (deriv_info.Derived == null)
                    {
                        // we can skip implementation or abstract signature of the function in the abstract type
                        if (deriv_info.Base.Modifier.RequiresOverride && !this.Modifier.IsAbstract)
                        {
                            missing_func_implementations.Add(deriv_info.Base);
                        }
                    }
                    else
                    {
                        {
                            if (deriv_info.Base.IsPropertyAccessor(out Property base_property))
                            {
                                EntityInstance base_prop_instance = base_property.InstanceOf.TranslateThrough(ancestor);
                                inherited_member_instances.Remove(base_prop_instance);
                            }

                            EntityInstance base_instance = deriv_info.Base.InstanceOf.TranslateThrough(ancestor);
                            inherited_member_instances.Remove(base_instance);
                        }

                        if (deriv_info.Derived.Modifier.HasOverride)
                        {
                            derivation_mapping[deriv_info.Derived].Add(deriv_info.Base);
                            // user does not have to repeat "pinned" all the time, but for easier tracking of pinned methods
                            // we add it automatically
                            if (deriv_info.Base.Modifier.HasPinned)
                            {
                                deriv_info.Derived.SetModifier(deriv_info.Derived.Modifier | EntityModifier.Pinned);
                            }

                            if (deriv_info.Base.Modifier.HasHeapOnly != deriv_info.Derived.Modifier.HasHeapOnly)
                            {
                                ctx.AddError(ErrorCode.HeapRequirementChangedOnOverride, deriv_info.Derived);
                            }
                        }
                        else if (!deriv_info.Base.Modifier.IsSealed)
                        {
                            ctx.AddError(ErrorCode.MissingOverrideModifier, deriv_info.Derived);
                        }

                        if (!deriv_info.Base.Modifier.IsSealed)
                        {
                            virtual_mapping.Update(deriv_info.Base, deriv_info.Derived);

                            // the rationale for keeping the same access level is this
                            // narrowing is pretty easy to skip by downcasting
                            // expanding looks like a good idea, but... -- the author of original type
                            // maybe had better understanding why given function is private/protected and not protected/public
                            // it is better to keep it safe, despite little annoyance (additional wrapper), than finding out
                            // how painful is violating that "good reason" because it was too easy to type "public"
                            if (!deriv_info.Base.Modifier.SameAccess(deriv_info.Derived.Modifier))
                            {
                                ctx.AddError(ErrorCode.AlteredAccessLevel, deriv_info.Derived.Modifier);
                            }
                        }
                        else if (deriv_info.Derived.Modifier.HasOverride)
                        {
                            ctx.AddError(ErrorCode.CannotOverrideSealedMethod, deriv_info.Derived);
                        }
                    }
                }
            }

            foreach (FunctionDefinition missing_impl in missing_func_implementations)
            {
                if (!isDerivedByAncestors(missing_impl))
                {
                    ctx.AddError(ErrorCode.BaseFunctionMissingImplementation, this, missing_impl);
                }
            }

            // here we eliminate "duplicate" entries -- if we have some method in ancestor A
            // and this method is overridden in ancestor B, then we would like to have
            // only method B listed, not both
            foreach (EntityInstance inherited in inherited_member_instances.ToArray())
            {
                IEntity target = inherited.Target;
                if (target is Property prop)
                {
                    target = prop.Getter;
                }
                if (target is FunctionDefinition func && isDerivedByAncestors(func))
                {
                    inherited_member_instances.Remove(inherited);
                }
            }

            this.InheritanceVirtualTable = virtual_mapping;
            this.DerivationTable         = new DerivationTable(ctx, this, derivation_mapping);
            this.availableEntities       = ScopeTable.Combine(this.AvailableEntities, inherited_member_instances);

            foreach (FunctionDefinition func in derivation_mapping.Where(it => !it.Value.Any()).Select(it => it.Key))
            {
                ctx.AddError(ErrorCode.NothingToOverride, func);
            }

            this.isEvaluated = true;
        }
        protected override void Init()
        {
            toolStrip = new ToolStrip()
                        .Button("Rename", "Переименовать (F2)")
                        .Button("Объединить (F3)", ShowJoinView)
                        .Button("Delete", "Удалить (Delete)")
                        .Separator()
                        .Button("Продукты (Enter)", ShowProductsAndProducersOrOffers)
                        .Button("Показать в ассортименте", ShowAssortmentForProducer)
                        .Separator()
                        .Button("Создать эквивалент", ShowCreateEquivalentForProducer)
                        .Button("Обновить (F11)", Reload);
            toolStrip.Tag = "Searchable";

            var bookmarksToolStrip = new ToolStrip()
                                     .Button("К закаладке", MoveToBookmark)
                                     .Button("Установить закладку", SetBookmark);

            producerTable = new VirtualTable(new TemplateManager <ProducerDto>(
                                                 () => Row.Headers(new Header("Проверен").AddClass("CheckBoxColumn1"), "Производитель"),
                                                 producer => {
                var row = Row.Cells(new CheckBoxInput(producer.Checked).Attr("Name", "Checked"), producer.Name);
                if (producer.HasOffers)
                {
                    row.AddClass("WithoutOffers");
                }
                if (producer.Id == BookmarkProducerId)
                {
                    ((IDomElementWithChildren)row.Children.Last()).Prepend(new TextBlock {
                        Class = "BookmarkGlyph"
                    });
                }
                return(row);
            }));
            producerTable.RegisterBehavior(new InputController());
            producerTable.Host.Name     = "Producers";
            producerTable.Host.KeyDown += (sender, args) => {
                if (args.KeyCode == Keys.Enter && String.IsNullOrEmpty(searchText.Text))
                {
                    ShowProductsAndProducersOrOffers();
                }
                else if (args.KeyCode == Keys.Enter)
                {
                    Search(searchText.Text);
                }
                else if (args.KeyCode == Keys.Escape && !String.IsNullOrEmpty(searchText.Text))
                {
                    searchText.Text = "";
                }
                else if (args.KeyCode == Keys.Escape && String.IsNullOrEmpty(searchText.Text))
                {
                    ReseteFilter();
                }
                else if (args.KeyCode == Keys.Tab)
                {
                    synonymsTable.Host.Focus();
                }
                else if (args.KeyCode == Keys.F3)
                {
                    ShowJoinView();
                }
            };
            producerTable.Host.KeyPress += (sender, args) => {
                if (Char.IsLetterOrDigit(args.KeyChar))
                {
                    searchText.Text += args.KeyChar;
                }
            };
            producerTable.Host.InputMap()
            .KeyDown(Keys.F11, Reload);

            synonymsTable = new VirtualTable(new TemplateManager <ProducerSynonymDto>(
                                                 () => {
                var row    = Row.Headers();
                var header = new Header("Синоним").Sortable("Name");
                row.Append(header);

                header = new Header("Поставщик").Sortable("Supplier");
                row.Append(header);

                header = new Header("Регион").Sortable("Region");
                row.Append(header);

                return(row);
            },
                                                 synonym => {
                var row = Row.Cells(synonym.Name,
                                    synonym.Supplier,
                                    synonym.Region);
                if (synonym.HaveOffers)
                {
                    row.AddClass("WithoutOffers");
                }
                return(row);
            }));

            synonymsTable.Host.Name = "ProducerSynonyms";
            synonymsTable.Host
            .InputMap()
            .KeyDown(Keys.Enter, ShowProductsAndProducersOrOffers)
            .KeyDown(Keys.Escape, () => producerTable.Host.Focus());

            equivalentTable = new VirtualTable(new TemplateManager <ProducerEquivalentDto>(
                                                   () => Row.Headers("Эквивалент"),
                                                   e => Row.Cells(e.Name)));
            equivalentTable.Host.Name = "ProducerEquivalents";

            var producersToSynonymsSplit = new SplitContainer {
                Dock        = DockStyle.Fill,
                Orientation = Orientation.Horizontal
            };
            var producersToEquivalentsSplit = new SplitContainer {
                Dock = DockStyle.Fill,
            };

            producersToEquivalentsSplit.Panel1.Controls.Add(producerTable.Host);
            producersToEquivalentsSplit.Panel2.Controls.Add(equivalentTable.Host);

            producersToSynonymsSplit.Panel1.Controls.Add(producersToEquivalentsSplit);
            producersToSynonymsSplit.Panel2.Controls.Add(synonymsTable.Host);
            Controls.Add(producersToSynonymsSplit);
            Controls.Add(new Legend("WithoutOffers"));
            Controls.Add(bookmarksToolStrip);
            Controls.Add(toolStrip);
            producersToSynonymsSplit.SplitterDistance    = (int)(0.5 * Height);
            producersToEquivalentsSplit.SplitterDistance = (int)(0.7 * producersToEquivalentsSplit.Width);
            Shown += (sender, args) => producerTable.Host.Focus();
            synonymsTable.TemplateManager.ResetColumns();
        }
Example #17
0
        public ShowAssortment(Pager <AssortmentDto> assortments)
        {
            Text        = "Ассортимент";
            MinimumSize = new Size(640, 480);

            tools = new ToolStrip()
                    .Edit("SearchText")
                    .Button("Поиск", Search)
                    .Separator()
                    .Button("Удалить (Delete)", Delete)
                    .Separator()
                    .Button("Удалить синоним", DeleteProducerSynonym)
                    .Button("Обновить (F11)", Reload);

            navigationToolStrip = new ToolStrip()
                                  .Button("К закаладке", MoveToBookmark)
                                  .Button("Установить закладку", SetBookmark)
                                  .Separator()
                                  .Button("Prev", "Предыдущая страница")
                                  .Label("PageLabel", "")
                                  .Button("Next", "Следующая страница");

            assortmentTable = new VirtualTable(new TemplateManager <AssortmentDto>(
                                                   () => Row.Headers("Продукт", "Производитель"),
                                                   a => {
                var row = Row.Cells(new Cell(new TextBlock(a.Product)), new Cell(new TextBlock(a.Producer)));
                if (a.Id == Settings.Default.BookmarkAssortimentId)
                {
                    ((IDomElementWithChildren)row.Children.ElementAt(1)).Prepend(new TextBlock {
                        Class = "BookmarkGlyph"
                    });
                }
                return(row);
            }));
            assortmentTable.CellSpacing = 1;
            assortmentTable.RegisterBehavior(
                new RowSelectionBehavior(),
                new ToolTipBehavior(),
                new ColumnResizeBehavior(),
                new InputController());
            assortmentTable.Behavior <ColumnResizeBehavior>().ColumnResized += column => WidthHolder.Update(assortmentTable, column, WidthHolder.AssortimentWidths);
            assortmentTable.TemplateManager.ResetColumns();
            assortmentTable.Host
            .InputMap()
            .KeyDown(Keys.Delete, Delete)
            .KeyDown(Keys.F11, Reload);

            UpdateAssortment(assortments);

            var searchText = ((ToolStripTextBox)tools.Items["SearchText"]);

            searchText.KeyDown += (sender, args) => {
                if (args.KeyCode == Keys.Enter)
                {
                    Search();
                }
            };

            assortmentTable.Host.InputMap()
            .KeyDown(Keys.Enter, Search)
            .KeyDown(Keys.Escape, () => {
                searchText.Text = "";
                if (!String.IsNullOrEmpty(_searchText))
                {
                    _searchText = "";
                    var pager   = Request(s => s.GetAssortmentPage(0));
                    UpdateAssortment(pager);
                    navigationToolStrip.UpdatePaginator(pager);
                }
            })
            .KeyPress((o, a) => {
                if (!Char.IsLetterOrDigit(a.KeyChar))
                {
                    return;
                }
                searchText.Text += a.KeyChar;
            });

            var behavior = assortmentTable.Behavior <IRowSelectionBehavior>();

            behavior.SelectedRowChanged += (oldRow, newRow) => SelectedAssortmentChanged(behavior.Selected <AssortmentDto>());

            synonymsTable = new VirtualTable(new TemplateManager <ProducerSynonymDto>(
                                                 () => {
                var row    = Row.Headers();
                var header = new Header("Синоним").Sortable("Name");
                header.InlineStyle.Set(StyleElementType.Width, WidthHolder.ProducerWidths[0]);
                row.Append(header);

                header = new Header("Поставщик").Sortable("Supplier");
                header.InlineStyle.Set(StyleElementType.Width, WidthHolder.ProducerWidths[1]);
                row.Append(header);

                header = new Header("Регион").Sortable("Region");
                header.InlineStyle.Set(StyleElementType.Width, WidthHolder.ProducerWidths[2]);
                row.Append(header);

                return(row);
            },
                                                 synonym => {
                var row = Row.Cells(synonym.Name,
                                    synonym.Supplier,
                                    synonym.Region);
                if (synonym.HaveOffers)
                {
                    row.AddClass("WithoutOffers");
                }
                return(row);
            }));
            synonymsTable.CellSpacing = 1;
            synonymsTable.RegisterBehavior(new ToolTipBehavior(),
                                           new SortInList(),
                                           new ColumnResizeBehavior(),
                                           new RowSelectionBehavior());

            synonymsTable.Host.InputMap();
            synonymsTable.Behavior <ColumnResizeBehavior>().ColumnResized += column => WidthHolder.Update(synonymsTable, column, WidthHolder.ProducerWidths);

            equivalentTable = new VirtualTable(new TemplateManager <ProducerEquivalentDto>(
                                                   () => Row.Headers("Эквивалент"), e => Row.Cells(e.Name)));

            var producersToSynonymsSplit = new SplitContainer {
                Dock        = DockStyle.Fill,
                Orientation = Orientation.Horizontal
            };
            var producersToEquivalentsSplit = new SplitContainer {
                Dock = DockStyle.Fill,
            };

            producersToEquivalentsSplit.Panel1.Controls.Add(assortmentTable.Host);
            producersToEquivalentsSplit.Panel2.Controls.Add(equivalentTable.Host);

            producersToSynonymsSplit.Panel1.Controls.Add(producersToEquivalentsSplit);
            producersToSynonymsSplit.Panel2.Controls.Add(synonymsTable.Host);

            Controls.Add(producersToSynonymsSplit);
            Controls.Add(navigationToolStrip);
            Controls.Add(tools);

            producersToSynonymsSplit.SplitterDistance    = (int)(0.5 * Height);
            producersToEquivalentsSplit.SplitterDistance = (int)(0.7 * producersToEquivalentsSplit.Width);

            assortmentTable.Host.Tag = PaginatorExtention.TableName;

            navigationToolStrip.ActAsPaginator(assortments, LoadPage);

            MoveToBookmark();
            Shown += (s, a) => assortmentTable.Host.Focus();

            var selected = assortmentTable.Selected <AssortmentDto>();

            SelectedAssortmentChanged(selected);
        }
        protected override void Init()
        {
            var excludes = new VirtualTable(new TemplateManager <ExcludeDto>(
                                                () => {
                var row = Row.Headers(
                    new Header("Продукт").Sortable("Catalog"),
                    new Header("Оригинальное наименование").Sortable("Catalog"),
                    new Header("Синоним").Sortable("ProducerSynonym"),
                    new Header("Поставщик").Sortable("Supplier"),
                    new Header("Регион").Sortable("Region"),
                    new Header("Оператор").Sortable("Operator"));
                return(row);
            },
                                                e => Row.Cells(e.Catalog, e.OriginalSynonym, e.ProducerSynonym, e.Supplier, e.Region, e.Operator)));

            excludes.Host.Name = "Excludes";
            excludes.Host.Tag  = PaginatorExtention.TableName;

            var synonymsTable = new VirtualTable(new TemplateManager <ProducerSynonymDto>(
                                                     () => {
                return(Row.Headers(
                           new Header("Синоним").Sortable("Name"),
                           new Header("Производитель").Sortable("Producer"),
                           new Header("Поставщик").Sortable("Supplier"),
                           new Header("Регион").Sortable("Region")));
            },
                                                     synonym => {
                var row = Row.Cells(synonym.Name,
                                    synonym.Producer,
                                    synonym.Supplier,
                                    synonym.Region);
                if (synonym.HaveOffers)
                {
                    row.AddClass("WithoutOffers");
                }
                if (synonym.SameAsCurrent)
                {
                    row.AddClass("SameAsCurrent");
                }
                return(row);
            }));

            synonymsTable.Host.Name = "ProducerSynonyms";

            var assortment = new VirtualTable(new TemplateManager <ProducerOrEquivalentDto>(
                                                  () => Row.Headers(new Header("Производитель").Sortable("Producer")),
                                                  synonym => Row.Cells(synonym.Name)));

            assortment.Host.Name = "ProducerOrEquivalents";

            var split = new SplitContainer {
                Height      = 200,
                Orientation = Orientation.Vertical,
                Dock        = DockStyle.Bottom
            };

            split.Panel1.Controls.Add(assortment.Host);
            split.Panel2.Controls.Add(synonymsTable.Host);

            Controls.Add(excludes.Host);
            Controls.Add(split);
            Controls.Add(new Legend("WithoutOffers", "SameAsCurrent"));
            Controls.Add(new ToolStrip()
                         .Item(new ToolStripButton {
                CheckOnClick = true, Name = "ShowHidden", Text = "Показать скрытых"
            })
                         .Item(new ToolStripButton {
                CheckOnClick = true, Name = "ShowPharmacie", Text = "Показать только фармацевтику"
            })
                         .Separator()
                         .Button("AddToAssortment", "Добавить в ассортимент")
                         .Button("DoNotShow", "Больше не показывать")
                         .Button("MistakenExclude", "Ошибочное исключение")
                         .Button("DeleteSynonym", "Ошибочное сопоставление по наименованию")
                         .Button("MistakenProducerSynonym", "Ошибочное сопоставление по производителю")
                         .Button("AddEquivalent", "Создать эквивалент")
                         .Button("Обновить (F11)", Reload));
            excludes.Host.InputMap()
            .KeyDown(Keys.F11, Reload);

            Shown += (s, a) => excludes.Host.Focus();
        }
Example #19
0
        public static ITable SelectRange(this ITable thisTable, ObjectName columnName, IndexRange[] ranges)
        {
            // If this table is empty then there is no range to select so
            // trivially return this object.
            if (thisTable.RowCount == 0)
                return thisTable;

            // Are we selecting a black or null range?
            if (ranges == null || ranges.Length == 0)
                // Yes, so return an empty table
                return thisTable.EmptySelect();

            // Are we selecting the entire range?
            if (ranges.Length == 1 &&
                ranges[0].Equals(IndexRange.FullRange))
                // Yes, so return this table.
                return thisTable;

            // Must be a non-trivial range selection.

            // Find the column index of the column selected
            int column = thisTable.IndexOfColumn(columnName);

            if (column == -1) {
                throw new Exception(
                    "Unable to find the column given to select the range of: " +
                    columnName.Name);
            }

            // Select the range
            var rows = thisTable.SelectRowsRange(column, ranges);

            // Make a new table with the range selected
            var result = new VirtualTable(thisTable, rows.ToArray());

            // We know the new set is ordered by the column.
            result.SortColumn = column;

            return result;
        }
        public ShowProductsAndProducers(ProducerDto producer, List <ProducerDto> producers, List <ProductAndProducer> productAndProducers)
        {
            this.producer            = producer;
            this.productAndProducers = productAndProducers;
            this.producers           = producers;

            MinimumSize = new Size(640, 480);
            Size        = new Size(640, 480);
            Text        = "Продукты";
            KeyPreview  = true;
            KeyDown    += (sender, args) => {
                if (args.KeyCode == Keys.Escape)
                {
                    Close();
                }
            };

            productsAndProducers = new VirtualTable(new TemplateManager <ProductAndProducer>(
                                                        () => {
                var row = Row.Headers(new Header().AddClass("CheckBoxColumn"));

                var header = new Header("Продукт").Sortable("Product");
                header.InlineStyle.Set(StyleElementType.Width, WidthHolder.ProductsAndProducersWidths[0]);
                row.Append(header);

                header = new Header("Производитель").Sortable("Producer");
                header.InlineStyle.Set(StyleElementType.Width, WidthHolder.ProductsAndProducersWidths[1]);
                row.Append(header);

                header = new Header("Количество предложений").Sortable("OffersCount");
                header.InlineStyle.Set(StyleElementType.Width, WidthHolder.ProductsAndProducersWidths[2]);
                row.Append(header);

                header = new Header("Количество заказов").Sortable("OrdersCount");
                header.InlineStyle.Set(StyleElementType.Width, WidthHolder.ProductsAndProducersWidths[3]);
                row.Append(header);
                return(row);
            },
                                                        offer => {
                var row = Row.Cells(offer.Product,
                                    offer.Producer,
                                    offer.OffersCount,
                                    offer.OrdersCount);
                if (offer.ExistsInRls == 0)
                {
                    row.AddClass("NotExistsInRls");
                }
                if (offer.ProducerId != producer.Id)
                {
                    row.Prepend(new CheckBoxInput(offer.Selected));
                }
                else
                {
                    row.Prepend(new Cell());
                }
                return(row);
            }));
            productsAndProducers.CellSpacing = 1;
            productsAndProducers.RegisterBehavior(
                new ToolTipBehavior(),
                new SortInList(),
                new RowSelectionBehavior(),
                new ColumnResizeBehavior(),
                new InputSupport(input => {
                var row = (Row)input.Parent.Parent;
                var productAndProducer = productsAndProducers.Translate <ProductAndProducer>(row);
                ((IList <ProductAndProducer>)productsAndProducers.TemplateManager.Source)
                .Where(p => p.ProducerId == productAndProducer.ProducerId)
                .Each(p => p.Selected = ((CheckBoxInput)input).Checked);
                productsAndProducers.RebuildViewPort();
            }));
            productsAndProducers.TemplateManager.Source = productAndProducers;
            productsAndProducers.Behavior <ColumnResizeBehavior>().ColumnResized += column => WidthHolder.Update(productsAndProducers, column, WidthHolder.ProductsAndProducersWidths);
            productsAndProducers.Host.InputMap()
            .KeyDown(Keys.F3, Join)
            .KeyDown(Keys.F4, ShowOffersForProducerId)
            .KeyDown(Keys.F5, ShowOffersForCatalogId);

            var toolStrip = new ToolStrip();

            toolStrip
            .Button(String.Format("Объединить c {0} (F3)", producer.Name), Join)
            .Button("Предложения для производителя (F4)", ShowOffersForProducerId)
            .Button("Предложения для продукта (F5)", ShowOffersForCatalogId);

            productsAndProducers.TemplateManager.ResetColumns();
            Controls.Add(productsAndProducers.Host);
            Controls.Add(toolStrip);
        }
        public ShowSuspiciousSynonyms(IList <SynonymReportItem> items)
        {
            Text        = "Подозрительные сопоставления";
            MinimumSize = new Size(640, 480);
            var widths = WidthHolder.SyspiciosSynonyms;
            var tools  = new ToolStrip()
                         .Button("Удалить (Delete)", Delete)
                         .Button("Не подозрительный (Пробел)", NotSuspicious)
                         .Button("Отправить уведомление поставщику", SendNotificationToSupplier)
                         .Button("Обновить (F11)", Reload);

            report = new VirtualTable(new TemplateManager <SynonymReportItem>(
                                          () => {
                var row = new Row();

                var header = new Header("Пользователь").Sortable("User");
                header.InlineStyle.Set(StyleElementType.Width, widths[0]);
                row.Append(header);

                header = new Header("Прайс").Sortable("Price");
                header.InlineStyle.Set(StyleElementType.Width, widths[1]);
                row.Append(header);

                header = new Header("Регион").Sortable("Region");
                header.InlineStyle.Set(StyleElementType.Width, widths[2]);
                row.Append(header);

                header = new Header("Синоним").Sortable("Synonym");
                header.InlineStyle.Set(StyleElementType.Width, widths[3]);
                row.Append(header);

                header = new Header("Производитель").Sortable("Producer");
                header.InlineStyle.Set(StyleElementType.Width, widths[4]);
                row.Append(header);

                header = new Header("Продукты").Sortable("Products");
                header.InlineStyle.Set(StyleElementType.Width, widths[4]);
                row.Append(header);

                return(row);
            },
                                          i => Row.Cells(i.User, i.Price, i.Region, i.Synonym, i.Producer, i.Products)));
            report.CellSpacing = 1;
            report.RegisterBehavior(new ToolTipBehavior(),
                                    new ColumnResizeBehavior(),
                                    new RowSelectionBehavior(),
                                    new SortInList());
            report.Host
            .InputMap()
            .KeyDown(Keys.Delete, NotSuspicious)
            .KeyDown(Keys.Space, Delete)
            .KeyDown(Keys.F11, Reload);

            report.TemplateManager.Source = items.ToList();
            report.Behavior <ColumnResizeBehavior>().ColumnResized += column => WidthHolder.Update(report, column, widths);
            report.TemplateManager.ResetColumns();

            Controls.Add(report.Host);
            Controls.Add(tools);
            KeyPreview = true;
            this.InputMap().KeyDown(Keys.Escape, Close);

            Shown += (s, a) => report.Host.Focus();
        }
        public ShowSynonymReport(IList <SynonymReportItem> items)
        {
            Text   = "Отчет о сопоставлениях";
            report = new VirtualTable(new TemplateManager <SynonymReportItem>(
                                          () => {
                var row = new Row();

                var widths = WidthHolder.ReportWidths;

                var header = new Header("Пользователь").Sortable("User");
                header.InlineStyle.Set(StyleElementType.Width, widths[0]);
                row.Append(header);

                header = new Header("Прайс").Sortable("Price");
                header.InlineStyle.Set(StyleElementType.Width, widths[1]);
                row.Append(header);

                header = new Header("Регион").Sortable("Region");
                header.InlineStyle.Set(StyleElementType.Width, widths[2]);
                row.Append(header);

                header = new Header("Синоним").Sortable("Synonym");
                header.InlineStyle.Set(StyleElementType.Width, widths[3]);
                row.Append(header);

                header = new Header("Производитель").Sortable("Producer");
                header.InlineStyle.Set(StyleElementType.Width, widths[4]);
                row.Append(header);

                header = new Header("Продукты").Sortable("Products");
                header.InlineStyle.Set(StyleElementType.Width, widths[4]);
                row.Append(header);

                return(row);
            },
                                          i => {
                var row = Row.Cells(i.User, i.Price, i.Region, i.Synonym, i.Producer, i.Products);
                if (i.IsSuspicious == 1)
                {
                    row.AddClass("Suspicious");
                }
                return(row);
            }));
            report.CellSpacing = 1;
            report.RegisterBehavior(new ToolTipBehavior(),
                                    new ColumnResizeBehavior(),
                                    new SortInList(),
                                    new RowSelectionBehavior());
            report.TemplateManager.Source = items.ToList();
            report.Behavior <ColumnResizeBehavior>().ColumnResized += column => WidthHolder.Update(report, column, WidthHolder.ReportWidths);
            report.TemplateManager.ResetColumns();
            report.Host
            .InputMap()
            .KeyDown(Keys.Space, Suspicios)
            .KeyDown(Keys.Delete, Delete)
            .KeyDown(Keys.F11, Reload);

            Controls.Add(report.Host);

            var toolBar = new ToolStrip();

            Controls.Add(toolBar);

            var begin = DateTime.Now.AddDays(-1).Date;
            var end   = DateTime.Now.Date;

            var beginPeriodCalendar = new DateTimePicker {
                Value = begin,
                Width = 130,
            };

            var endPeriodCalendar = new DateTimePicker {
                Value = end,
                Width = 130,
            };

            toolBar
            .Label("C")
            .Host(beginPeriodCalendar)
            .Label("По")
            .Host(endPeriodCalendar)
            .Button("Показать", () => Action(s => {
                lastBeginDate = beginPeriodCalendar.Value;
                lastEndDate   = endPeriodCalendar.Value;
                report.TemplateManager.Source = s.ShowSynonymReport(beginPeriodCalendar.Value, endPeriodCalendar.Value).ToList();
            }))
            .Separator()
            .Button("Suspicious", "Подозрительный (Пробел)", Suspicios)
            .Button("Удалить (Delete)", Delete)
            .Button("Обновить (F11)", Reload);

            MinimumSize = new Size(640, 480);
            KeyPreview  = true;
            this.InputMap().KeyDown(Keys.Escape, Close);
            report.Behavior <IRowSelectionBehavior>().SelectedRowChanged += (oldIndex, newIndex) => {
                var item = report.Translate <SynonymReportItem>(report.ViewPort.GetRow(newIndex));
                if (item.IsSuspicious == 0)
                {
                    toolBar.Items["Suspicious"].Text = "Подозрительный (Пробел)";
                }
                else
                {
                    toolBar.Items["Suspicious"].Text = "Не подозрительный (Пробел)";
                }
            };
        }
Example #23
0
        public static ITable Join(this ITable table, ITable otherTable, bool quick)
        {
            ITable outTable;

            if (quick) {
                // This implementation doesn't materialize the join
                outTable = new NaturallyJoinedTable(table, otherTable);
            } else {
                var tabs = new [] { table, otherTable};
                var rowSets = new IList<int>[2];

                // Optimized trivial case, if either table has zero rows then result of
                // join will contain zero rows also.
                if (table.RowCount == 0 || otherTable.RowCount == 0) {
                    rowSets[0] = new List<int>(0);
                    rowSets[1] = new List<int>(0);
                } else {
                    // The natural join algorithm.
                    List<int> thisRowSet = new List<int>();
                    List<int> tableRowSet = new List<int>();

                    // Get the set of all rows in the given table.
                    var tableSelectedSet = otherTable.Select(x => x.RowId.RowNumber).ToList();

                    int tableSelectedSetSize = tableSelectedSet.Count;

                    // Join with the set of rows in this table.
                    var e = table.GetEnumerator();
                    while (e.MoveNext()) {
                        int rowIndex = e.Current.RowId.RowNumber;
                        for (int i = 0; i < tableSelectedSetSize; ++i) {
                            thisRowSet.Add(rowIndex);
                        }

                        tableRowSet.AddRange(tableSelectedSet);
                    }

                    // The row sets we are joining from each table.
                    rowSets[0] = thisRowSet;
                    rowSets[1] = tableRowSet;
                }

                // Create the new VirtualTable with the joined tables.
                outTable = new VirtualTable(tabs, rowSets);
            }

            return outTable;
        }