Inheritance: MonoBehaviour
示例#1
0
        public void Grid_SetsSource()
        {
            IQueryable<GridModel> expected = new GridModel[2].AsQueryable();
            IQueryable<GridModel> actual = new Grid<GridModel>(expected).Source;

            Assert.Same(expected, actual);
        }
        public ActionResult Create()
        {
            try
            {
                GridModel m = new GridModel();
                List<Transaction<RoleModel>> transactions = m.LoadTransactions<RoleModel>(HttpContext.Request.Form["ig_transactions"]);

                foreach (Transaction<RoleModel> t in transactions)
                {
                    if (t.type == "newrow")
                    {
                        Roles.CreateRole(t.row.RoleName);
                    }
                    else if (t.type == "deleterow")
                    {
                        Roles.DeleteRole(t.row.RoleName);
                    }
                }
                JsonResult result = new JsonResult();
                Dictionary<string, bool> response = new Dictionary<string, bool>();
                response.Add("Success", true);
                result.Data = response;
                return result;
            }
            catch
            {
                return View();
            }
        }
 public Move GetBestMove(GridModel<ShapeViewDrawable> gridModel, int movesToLookAhead)
 {
     if (movesToLookAhead < 1)
         throw new Exception();
     List<Move> validMoves = Helpers.GetValidMoves(gridModel);
     foreach (Move move in validMoves)
     {
         GridModel<ShapeViewDrawable> tempGridModel = gridModel.CloneRawGrid();
         tempGridModel.DoMove(move);
         //do the whole matching stuff on it
         move.PredictedScore = tempGridModel.Score;
         if (movesToLookAhead - 1 < 1)
             continue;
         Move bestNextMove = GetBestMove(gridModel, movesToLookAhead - 1);
         if (bestNextMove == null)
         {
             //no valid moves left
             move.PredictedScore = Int32.MinValue;
         }
         else
         {
             move.PredictedScore += bestNextMove.PredictedScore;
         }
     }
     Move bestMove = validMoves.OrderBy(mv => mv.PredictedScore).LastOrDefault();
     return bestMove;
 }
示例#4
0
        public ActionResult Update()
        {
            GridModel gridModel = new GridModel();
            List<Transaction<Product>> transactions = gridModel.LoadTransactions<Product>(HttpContext.Request.Form["ig_transactions"]);
            foreach (Transaction<Product> t in transactions)
            {
                if (t.type == "newrow")
                {

                }
                else if (t.type == "deleterow")
                {
                    //t.rowId = productid
                }
                else if (t.type == "row")
                {
                    //update
                }
            }
            JsonResult result = new JsonResult();
            Dictionary<string, bool> response = new Dictionary<string, bool>();
            response.Add("Success", true);
            result.Data = response;
            return result;
        }
        private GridModel GridLoadOnDemandModel()
        {
            GridModel grid = new GridModel();
            grid.AutoGenerateLayouts = false;
            grid.AutoGenerateColumns = true;
            grid.PrimaryKey = "ID";
            grid.Width = "100%";
            grid.Columns.Add(new GridColumn() { HeaderText = "Service ID", Key = "ID", DataType = "number" });
            grid.Columns.Add(new GridColumn() { HeaderText = "Client ID", Key = "ClientID", DataType = "number" });
            grid.Columns.Add(new GridColumn() { HeaderText = "Package ID", Key = "PackageID", DataType = "number" });

            GridColumnLayoutModel layout = new GridColumnLayoutModel();
            layout.Key = "ServiceHistory";
            layout.ForeignKey = "ID";
            layout.PrimaryKey = "ID";
            layout.AutoGenerateColumns = false;
            layout.Columns.Add(new GridColumn() { HeaderText = "Log ID", Key = "LogID", DataType = "number", Hidden = true });
            layout.Columns.Add(new GridColumn() { HeaderText = "Service ID", Key = "ID", DataType = "number", Hidden = true});
            layout.Columns.Add(new GridColumn() { HeaderText = "Client ID", Key = "ClientID", DataType = "number" });
            layout.Columns.Add(new GridColumn() { HeaderText = "Package ID", Key = "PackageID", DataType = "number" });

            layout.Width = "100%";
            grid.ColumnLayouts.Add(layout);

            return grid;
        }
        public void Grid_PartialViewName_CreatesGridWithSource()
        {
            IEnumerable<GridModel> expected = new GridModel[0].AsQueryable();
            IEnumerable<GridModel> actual = html.Grid("_Partial", expected).Grid.Source;

            Assert.Same(expected, actual);
        }
    void Awake()
    {
        mSceneCamera = GameObject.Find("Main Camera").GetComponent<Camera>();
        mDestination = cachedTransform.position;

        gridModel = GameObject.Find("GridArea").GetComponent<GridModel>();

        pathFinder = new PathFinder(gridModel);
    }
    public GridInfo(GridModel model, int x, int z)
    {
        this.model = model;
        mTx = x;
        mTz = z;

        mCenterPosition.x = mTx * model.quadSize + model.quadSize * 0.5f;
        mCenterPosition.z = mTz * model.quadSize + model.quadSize * 0.5f;
    }
		public void Setup()
		{
			_model = new GridModel<Person>();
			_people = new List<Person> {new Person {Id = 1, Name = "Jeremy", DateOfBirth = new DateTime(1987, 4, 19)}};
			_viewEngine = MockRepository.GenerateMock<IViewEngine>();
			_engines = new ViewEngineCollection(new List<IViewEngine> { _viewEngine });
			_writer = new StringWriter();
			_querystring= new NameValueCollection();
			RouteTable.Routes.MapRoute("default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional });
		}
    public void init()
    {
        model = cachedGameObject.GetComponent<GridModel>();
        if (null == model)
            model = cachedGameObject.AddComponent<GridModel>();

        view = cachedGameObject.GetComponent<GridView>();
        if (null == view)
            view = cachedGameObject.AddComponent<GridView>();
    }
        public void GetTotal_returns_total_of_grid_model()
        {
            var model = new GridModel
            {
                Total = 1
            };

            var adapter = Adapter(() => model);

            Assert.Equal(model.Total, adapter.GetTotal());
        }
        public void GetDataSource_returns_data_of_grid_model()
        {
            var model = new GridModel
            {
                Data = new object[0]
            };

            var adapter = Adapter(() => model);

            Assert.Same(model.Data, adapter.GetDataSource());
        }
示例#13
0
 public void RowEnd_section_should_be_stored_when_rendered()
 {
     var model = new GridModel<Person>();
     _grid.WithModel(model).RowEnd(x => "foo");
     _grid.ToString();
     ((IGridModel<Person>)model).Sections.Row
         .EndSectionRenderer(
             new GridRowViewData<Person>(new Person(), true),
             GridRendererTester.FakeRenderingContext()
         ).ShouldBeTrue();
 }
示例#14
0
 public static List<Move> GetValidMoves(GridModel<ShapeViewDrawable> gridModel)
 {
     List<Move> possibleMoves = GetPossibleMoves(gridModel);
     List<Move> validMoves = new List<Move>();
     foreach (Move move in possibleMoves)
     {
         if (gridModel.IsValidMove(move))
         {
             validMoves.Add(move);
         }
     }
     return validMoves;
 }
 public void Should_set_descending_sortorder_on_current_column()
 {
     ViewContext context = new ViewContext();
     context.HttpContext = MvcMockHelpers.DynamicHttpContextBase();
     context.HttpContext.Request.QueryString["SortBy"] = "DateOfBirth";
     context.HttpContext.Request.QueryString["SortOrder"] = "Ascending";
     _model = new GridModel<Person>();
     _model.Column.For(x => x.Name).Sortable(true);
     _model.Column.For(x => x.DateOfBirth).Sortable(false);
     RenderGrid(context);
     GridColumn<Person> testColumn = ((IGridModel<Person>)_model).Columns.LastOrDefault();
     testColumn.SortOptions.SortOrder.ShouldEqual(System.Data.SqlClient.SortOrder.Descending);
 }
 public void Setup()
 {
     _model = new GridModel<Person>();
     _people = new ComparableSortList<Person>(new List<Person> { new Person { Id = 1, Name = "Jeremy", DateOfBirth = new DateTime(1987, 4, 19) } });
     _viewEngine = MockRepository.GenerateMock<IViewEngine>();
     _engines = new ViewEngineCollection(new List<IViewEngine> { _viewEngine });
     _writer = new StringWriter();
     _context = new ViewContext();
     _context.HttpContext = MvcMockHelpers.DynamicHttpContextBase();
     var response = MockRepository.GenerateStub<HttpResponseBase>();
     _context.HttpContext.Stub(p => p.Response).Return(response);
     response.Stub(p => p.Output).Return(_writer);
 }
示例#17
0
 public ActionResult OrdersSaveData()
 {
     GridModel gridModel = new GridModel();
     List<Transaction<Order>> transactions = gridModel.LoadTransactions<Order>(HttpContext.Request.Form["ig_transactions"]);
     var orders = RepositoryFactory.GetOrderRepository();
     foreach (Transaction<Order> t in transactions)
     {
         if (t.type == "newrow")
         {
             orders.Add(t.row);
         }
         else if (t.type == "deleterow")
         {
             orders.Delete(o => o.OrderID == Int32.Parse(t.rowId));
         }
         else if (t.type == "row")
         {
             var order = (from o in orders.Get()
                            where o.OrderID == Int32.Parse(t.rowId)
                            select o).Single();
             if (t.row.OrderDate != null)
             {
                 order.OrderDate = t.row.OrderDate;
             }
             if (t.row.TotalPrice != null)
             {
                 order.TotalPrice = t.row.TotalPrice;
             }
             if (t.row.TotalItems != null)
             {
                 order.TotalItems = t.row.TotalItems;
             }
             if (t.row.CustomerID != null)
             {
                 order.CustomerID = t.row.CustomerID;
             }
             if (t.row.ShipAddress != null)
             {
                 order.ShipAddress = t.row.ShipAddress;
             }
             orders.Update(order, o => o.OrderID == Int32.Parse(t.rowId));
         }
     }
     orders.Save();
     JsonResult result = new JsonResult();
     Dictionary<string, bool> response = new Dictionary<string, bool>();
     response.Add("Success", true);
     result.Data = response;
     return result;
 }
示例#18
0
        public void Columns_should_be_stored_in_the_order_they_were_defined()
        {
            var model = new GridModel<Person>();
            _grid.WithModel(model)
                .Columns(col =>
                {
                    col.For(x => x.Id);
                    col.For(x => x.Name);
                });

            var cols = ((IGridModel<Person>)model).Columns;
            cols.ElementAt(0).Name.ShouldEqual("Id");
            cols.ElementAt(1).Name.ShouldEqual("Name");
        }
 public Move GetBestMove(GridModel<ShapeViewDrawable> gridModel, int movesToLookAhead)
 {
     if (movesToLookAhead < 1)
         return new Move(new Position(-1, -1), new Position(-1, -1));
     List<Move> validMoves = Helpers.GetValidMoves(gridModel);
     foreach (Move move in validMoves)
     {
         GridModel<ShapeViewDrawable> tempGridModel = gridModel.CloneRawGrid();
         tempGridModel.DoMove(move);
         //do the whole matching stuff on it
         move.PredictedScore = tempGridModel.Score;
     }
     Move bestMove = validMoves.OrderBy(mv => mv.PredictedScore).LastOrDefault();
     return bestMove;
 }
示例#20
0
 private static List<Move> GetPossibleMoves(GridModel<ShapeViewDrawable> gridModel)
 {
     int rows = gridModel.Rows;
     int columns = gridModel.Columns;
     List<Move> moves = new List<Move>();
     for (int row = 0; row < rows - 1; row++)
     {
         for (int column = 0; column < columns - 1; column++)
         {
             Position from = new Position(row, column);
             //only allow moving down and to the right, moving left or up are just mirror moves
             moves.Add(new Move(from, new Position(from.Row, from.Column + 1)));
             moves.Add(new Move(from, new Position(from.Row + 1, from.Column)));
         }
     }
     return moves;
 }
    public PathFinder(GridModel model)
    {
        mModel = model;
        mGridX = (ushort)mModel.row;
        mGridY = (ushort)mModel.column;

        mGridXBitWide = (ushort)(Math.Log(mGridX - 1, 2) + 1);
        mGridXMinus = (ushort)( Math.Pow(2, mGridXBitWide) - 1);

        int maxIndex = ( (mGridY - 1) << mGridXBitWide ) + (mGridX - 1);
        //0 - maxIndex
        int size = maxIndex + 1;
        if (null == mCalcGrid || mCalcGrid.Length != (size))
            mCalcGrid = new PathNodeFast[size];

        mOpen = new HeapTree(mCalcGrid);
    }
示例#22
0
        private void InitializeGridControl()
        {
            grid.Model.TableStyle.CellType = "Static";
            grid.Model.RowCount            = 30;
            grid.Model.ColumnCount         = 25;
            int rowIndex = 1;
            int colIndex = 2;

            this.grid.Model.CoveredCells.Add(new CoveredCellInfo(rowIndex, colIndex, rowIndex, colIndex + 1));
            grid.Model[rowIndex, colIndex].CellValue           = "Text Formats";
            grid.Model[rowIndex, colIndex].Background          = Brushes.DarkBlue;
            grid.Model[rowIndex, colIndex].Foreground          = Brushes.White;
            grid.Model[rowIndex, colIndex].Font.FontSize       = 15;
            grid.Model[rowIndex, colIndex].HorizontalAlignment = HorizontalAlignment.Center;
            rowIndex = rowIndex + 3;
            colIndex++;

            //NumberFormat
            string[] NumberFormat = new string[]
            {
                "0.00",
                "C",
                "0.00;(0.00)",
                "###0.##%",
                "#0.#E+00",
                "10:##,##0.#"
            };

            GridModel model = this.grid.Model;

            foreach (string format in NumberFormat)
            {
                model[rowIndex - 1, colIndex].Text       = format;
                model[rowIndex - 1, colIndex].Background = Brushes.Green;
                model[rowIndex - 1, colIndex].Foreground = Brushes.White;

                model[rowIndex - 1, colIndex - 1].Text       = "Format";
                model[rowIndex - 1, colIndex - 1].Background = Brushes.Green;
                model[rowIndex - 1, colIndex - 1].Foreground = Brushes.White;

                model[rowIndex, colIndex - 1].Text       = "Example";
                model[rowIndex, colIndex - 1].Background = Brushes.Green;
                model[rowIndex, colIndex - 1].Foreground = Brushes.White;
                ///Value
                model[rowIndex, colIndex].Format        = format;
                model[rowIndex, colIndex].CellValue     = Math.PI;
                model[rowIndex, colIndex].CellValueType = typeof(double);
                rowIndex += 3;
            }

            rowIndex = 1;
            colIndex = 5;
            this.grid.Model.CoveredCells.Add(new CoveredCellInfo(rowIndex, colIndex, rowIndex, colIndex + 1));
            model[rowIndex, colIndex].Text                = "DateTime Formats";
            grid.Model[rowIndex, colIndex].Background     = Brushes.DarkBlue;
            grid.Model[rowIndex, colIndex].Foreground     = Brushes.White;
            grid.Model[rowIndex, colIndex].Font.FontSize  = 15;
            model[rowIndex, colIndex].HorizontalAlignment = HorizontalAlignment.Center;
            rowIndex = rowIndex + 3;
            colIndex++;

            //DateTimeFormat
            string[] DateTimeFormat = new string[]
            {
                "d",
                "D",
                "f",
                "dddd, dd MMMM yyyy",
                "t",
                "s"
            };
            foreach (string format in DateTimeFormat)
            {
                model[rowIndex - 1, colIndex].Text       = format;
                model[rowIndex - 1, colIndex].Background = Brushes.Green;
                model[rowIndex - 1, colIndex].Foreground = Brushes.White;

                model[rowIndex - 1, colIndex - 1].Text       = "Format";
                model[rowIndex - 1, colIndex - 1].Background = Brushes.Green;
                model[rowIndex - 1, colIndex - 1].Foreground = Brushes.White;

                model[rowIndex, colIndex - 1].Text       = "Example";
                model[rowIndex, colIndex - 1].Background = Brushes.Green;
                model[rowIndex, colIndex - 1].Foreground = Brushes.White;
                ///Value
                model[rowIndex, colIndex].Format        = format;
                model[rowIndex, colIndex].CellValue     = DateTime.Now;
                model[rowIndex, colIndex].CellValueType = typeof(DateTime);
                rowIndex += 3;
            }

            rowIndex -= 1;
            colIndex  = 2;
            this.grid.Model.CoveredCells.Add(new CoveredCellInfo(rowIndex, colIndex, rowIndex, colIndex + 4));
            model[rowIndex, colIndex].Text                = "Format using the FormatProvider property";
            grid.Model[rowIndex, colIndex].Background     = Brushes.DarkBlue;
            grid.Model[rowIndex, colIndex].Foreground     = Brushes.White;
            grid.Model[rowIndex, colIndex].Font.FontSize  = 15;
            model[rowIndex, colIndex].HorizontalAlignment = HorizontalAlignment.Center;
            rowIndex += 3;
            colIndex += 1;
            string[] CustomFormat = new string[]
            {
                "{0:ES}",
                "{0:US}"
            };
            foreach (string format in CustomFormat)
            {
                model[rowIndex - 1, colIndex].Text       = format;
                model[rowIndex - 1, colIndex].Background = Brushes.Green;
                model[rowIndex - 1, colIndex].Foreground = Brushes.White;

                model[rowIndex - 1, colIndex - 1].Text       = "Format";
                model[rowIndex - 1, colIndex - 1].Background = Brushes.Green;
                model[rowIndex - 1, colIndex - 1].Foreground = Brushes.White;

                model[rowIndex, colIndex - 1].Text       = "Example";
                model[rowIndex, colIndex - 1].Background = Brushes.Green;
                model[rowIndex, colIndex - 1].Foreground = Brushes.White;
                ///Value
                model[rowIndex, colIndex].Format         = format;
                model[rowIndex, colIndex].CellValue      = Math.PI;
                model[rowIndex, colIndex].FormatProvider = new CustomNumberFormat();
                model[rowIndex, colIndex].CellValueType  = typeof(double);
                rowIndex += 3;
            }

            rowIndex -= 6;
            colIndex  = 6;
            string[] AccountFormat = new string[]
            {
                "{0:H}",
                "{0:I}"
            };
            foreach (string format in AccountFormat)
            {
                model[rowIndex - 1, colIndex].Text       = format;
                model[rowIndex - 1, colIndex].Background = Brushes.Green;
                model[rowIndex - 1, colIndex].Foreground = Brushes.White;

                model[rowIndex - 1, colIndex - 1].Text       = "Format";
                model[rowIndex - 1, colIndex - 1].Background = Brushes.Green;
                model[rowIndex - 1, colIndex - 1].Foreground = Brushes.White;

                model[rowIndex, colIndex - 1].Text       = "Example";
                model[rowIndex, colIndex - 1].Background = Brushes.Green;
                model[rowIndex, colIndex - 1].Foreground = Brushes.White;
                ///Value
                model[rowIndex, colIndex].Format         = format;
                model[rowIndex, colIndex].CellValue      = 104254567890;
                model[rowIndex, colIndex].FormatProvider = new AccountNumberFormat();
                model[rowIndex, colIndex].CellValueType  = typeof(Int64);
                rowIndex += 3;
            }

            grid.Model.ColumnWidths[3] = 140d;
            grid.Model.ColumnWidths[6] = 250;
        }
示例#23
0
 public void Setup()
 {
     gridModel   = new GridModel(new Board());
     playerTiles = new List <Tile>();
     boardTiles  = new List <Tile>();
 }
        private GridModel GridLoadOnDemandModel()
        {
            // Define the Categories layout
            GridModel grid = new GridModel();
            grid.AutoGenerateLayouts = false;
            grid.AutoGenerateColumns = false;
            grid.PrimaryKey = "ID";
            grid.Width = "100%";
            grid.Columns.Add(new GridColumn() { HeaderText = "Category ID", Key = "ID", DataType = "number", Width = "0%", Hidden = true});
            grid.Columns.Add(new GridColumn() { HeaderText = "Category Name", Key = "CategoryName", DataType = "string", Width = "30%" });
            grid.Columns.Add(new GridColumn() { HeaderText = "Description", Key = "Description", DataType = "string", Width = "50%" });
            grid.Columns.Add(new GridColumn() { HeaderText = "Products Count", Key = "ProductCount", DataType = "number", Width = "20%" });

            // Define the Products layout
            GridColumnLayoutModel layout = new GridColumnLayoutModel();
            layout.Key = "Products";
            layout.ForeignKey = "CategoryID";
            layout.PrimaryKey = "ID";
            layout.AutoGenerateColumns = false;
            layout.Columns.Add(new GridColumn() { HeaderText = "Product ID", Key = "ID", DataType = "number", Width = "0%", Hidden = true });
            layout.Columns.Add(new GridColumn() { HeaderText = "Category ID", Key = "CategoryID", DataType = "number",Width = "0%", Hidden = true});
            layout.Columns.Add(new GridColumn() { HeaderText = "Product Name", Key = "ProductName", DataType = "string",Width = "40%"});
            layout.Columns.Add(new GridColumn() { HeaderText = "Unit Price", Key = "UnitPrice", DataType = "number", Width = "30%" });
            layout.Columns.Add(new GridColumn() { HeaderText = "Units In Stock", Key = "UnitsInStock", DataType = "number", Width = "30%" });

            layout.Width = "100%";
            grid.ColumnLayouts.Add(layout);

            GridPaging paging = new GridPaging();
            paging.Type = OpType.Remote;
            paging.Inherit = true;
            paging.PageSize = 5;
            grid.Features.Add(paging);

            return grid;
        }
示例#25
0
 /// <summary>
 /// Used to get GridModel and GridStyleInfoCahe
 /// </summary>
 public GridOneTimeOnlyQueryCellInfoCache(GridModel gridModel)
 {
     _gridModel = (OneTimeOnlyQueryCellInfoGridModel)gridModel;
     _dataCache = new GridStyleInfoCache();
 }
示例#26
0
        public async Task <IActionResult> ProductList(GridCommand command, ProductListModel model)
        {
            var gridModel = new GridModel <ProductOverviewModel>();

            var fields = new List <string> {
                "name"
            };

            if (_searchSettings.SearchFields.Contains("sku"))
            {
                fields.Add("sku");
            }

            if (_searchSettings.SearchFields.Contains("shortdescription"))
            {
                fields.Add("shortdescription");
            }

            var searchQuery = new CatalogSearchQuery(fields.ToArray(), model.SearchProductName)
                              .HasStoreId(model.SearchStoreId)
                              .WithCurrency(_workContext.WorkingCurrency)
                              .WithLanguage(_workContext.WorkingLanguage);

            if (model.SearchIsPublished.HasValue)
            {
                searchQuery = searchQuery.PublishedOnly(model.SearchIsPublished.Value);
            }

            if (model.SearchHomePageProducts.HasValue)
            {
                searchQuery = searchQuery.HomePageProductsOnly(model.SearchHomePageProducts.Value);
            }

            if (model.SearchProductTypeId > 0)
            {
                searchQuery = searchQuery.IsProductType((ProductType)model.SearchProductTypeId);
            }

            if (model.SearchWithoutManufacturers.HasValue)
            {
                searchQuery = searchQuery.HasAnyManufacturer(!model.SearchWithoutManufacturers.Value);
            }
            else if (model.SearchManufacturerId != 0)
            {
                searchQuery = searchQuery.WithManufacturerIds(null, model.SearchManufacturerId);
            }


            if (model.SearchWithoutCategories.HasValue)
            {
                searchQuery = searchQuery.HasAnyCategory(!model.SearchWithoutCategories.Value);
            }
            else if (model.SearchCategoryId != 0)
            {
                searchQuery = searchQuery.WithCategoryIds(null, model.SearchCategoryId);
            }

            IPagedList <Product> products;

            if (_searchSettings.UseCatalogSearchInBackend)
            {
                searchQuery = searchQuery.Slice((command.Page - 1) * command.PageSize, command.PageSize);

                var sort = command.Sorting?.FirstOrDefault();
                if (sort != null)
                {
                    switch (sort.Member)
                    {
                    case nameof(ProductModel.Name):
                        searchQuery = searchQuery.SortBy(sort.Descending ? ProductSortingEnum.NameDesc : ProductSortingEnum.NameAsc);
                        break;

                    case nameof(ProductModel.Price):
                        searchQuery = searchQuery.SortBy(sort.Descending ? ProductSortingEnum.PriceDesc : ProductSortingEnum.PriceAsc);
                        break;

                    case nameof(ProductModel.CreatedOn):
                        searchQuery = searchQuery.SortBy(sort.Descending ? ProductSortingEnum.CreatedOn : ProductSortingEnum.CreatedOnAsc);
                        break;
                    }
                }

                if (!searchQuery.Sorting.Any())
                {
                    searchQuery = searchQuery.SortBy(ProductSortingEnum.NameAsc);
                }

                var searchResult = await _catalogSearchService.SearchAsync(searchQuery);

                products = await searchResult.GetHitsAsync();
            }
            else
            {
                var query = _catalogSearchService
                            .PrepareQuery(searchQuery)
                            .ApplyGridCommand(command, false);

                products = await new PagedList <Product>(query, command.Page - 1, command.PageSize).LoadAsync();
            }

            var fileIds = products.AsEnumerable()
                          .Select(x => x.MainPictureId ?? 0)
                          .Where(x => x != 0)
                          .Distinct()
                          .ToArray();

            var files = (await _mediaService.GetFilesByIdsAsync(fileIds)).ToDictionarySafe(x => x.Id);

            gridModel.Rows = products.AsEnumerable().Select(x =>
            {
                var productModel = new ProductOverviewModel
                {
                    Sku                  = x.Sku,
                    Published            = x.Published,
                    ProductTypeLabelHint = x.ProductTypeLabelHint,
                    Name                 = x.Name,
                    Id                        = x.Id,
                    StockQuantity             = x.StockQuantity,
                    Price                     = x.Price,
                    LimitedToStores           = x.LimitedToStores,
                    EditUrl                   = Url.Action("Edit", "Product", new { id = x.Id }),
                    ManufacturerPartNumber    = x.ManufacturerPartNumber,
                    Gtin                      = x.Gtin,
                    MinStockQuantity          = x.MinStockQuantity,
                    OldPrice                  = x.OldPrice,
                    AvailableStartDateTimeUtc = x.AvailableStartDateTimeUtc,
                    AvailableEndDateTimeUtc   = x.AvailableEndDateTimeUtc
                };

                //MiniMapper.Map(x, productModel);

                files.TryGetValue(x.MainPictureId ?? 0, out var file);

                // TODO: (core) Use IImageModel
                productModel.PictureThumbnailUrl = _mediaService.GetUrl(file, _mediaSettings.CartThumbPictureSize);
                productModel.NoThumb             = file == null;

                productModel.ProductTypeName = x.GetProductTypeLabel(_localizationService);
                productModel.UpdatedOn       = _dateTimeHelper.ConvertToUserTime(x.UpdatedOnUtc, DateTimeKind.Utc);
                productModel.CreatedOn       = _dateTimeHelper.ConvertToUserTime(x.CreatedOnUtc, DateTimeKind.Utc);

                return(productModel);
            });

            gridModel.Total = products.TotalCount;

            return(Json(gridModel));
        }
示例#27
0
 public void Setup()
 {
     _model = new GridModel <Person>();
 }
示例#28
0
        public ActionResult GetUserData()
        {
            GridModel gridmodel = userData.GetData();

            return(PartialView("_PVUserData", gridmodel));
        }
 public ActionResult EditingSaveChanges()
 {
     ViewData["GenerateCompactJSONResponse"] = false;
     GridModel m = new GridModel();
     List<Transaction<Category>> categoryTransactions = m.LoadTransactions<Category>(HttpContext.Request.Form["ig_transactions"]);
     foreach (Transaction<Category> t in categoryTransactions)
     {
         DataRow dr = this.CategoriesProducts.Tables["Categories"].Rows.Find(Int32.Parse(t.rowId));
         if ((t.layoutKey == null) && (dr != null))
         {
             if (t.type == "row")
             {
                 Category categoryRow = (Category)t.row;
                 if (categoryRow.CategoryName != null) {
                     dr["CategoryName"] = categoryRow.CategoryName;
                 }
                 if (categoryRow.Description != null){
                     dr["Description"] = categoryRow.Description;
                 }
             } else if (t.type == "deleterow")
             {
                 this.CategoriesProducts.Tables["Categories"].Rows.Remove(dr);
             }
         }
     }
     List<Transaction<Product>> productTransactions = m.LoadTransactions<Product>(HttpContext.Request.Form["ig_transactions"]);
     foreach (Transaction<Product> t in productTransactions)
     {
         DataRow dr = this.CategoriesProducts.Tables["Products"].Rows.Find(Int32.Parse(t.rowId));
         if ((t.layoutKey == "Products") && (dr != null))
         {
             if (t.type == "deleterow")
             {
                 this.CategoriesProducts.Tables["Products"].Rows.Remove(dr);
             }
             else if (t.type == "row")
             {
                 Product productRow = (Product)t.row;
                 if (productRow.ProductName != null)
                 {
                     dr["ProductName"] = productRow.ProductName;
                 }
                 if (productRow.CategoryID != null)
                 {
                     dr["CategoryID"] = productRow.CategoryID;
                 }
                 if (productRow.UnitPrice != null)
                 {
                     dr["UnitPrice"] = productRow.UnitPrice;
                 }
                 if (productRow.UnitsInStock != null)
                 {
                     dr["UnitsInStock"] = productRow.UnitsInStock;
                 }
                 dr["Discontinued"] = productRow.Discontinued;
             }
         }
     }
     JsonResult result = new JsonResult();
     Dictionary<string, bool> response = new Dictionary<string, bool>();
     response.Add("Success", true);
     result.Data = response;
     return result;
 }
示例#30
0
        private GridModel GetNestedGridWithSharedColumnsModel()
        {
            GridModel model = new GridModel();

            Pen gridLinePen = new Pen(Brushes.DarkGray, 1);

            gridLinePen.Freeze();

            model.Options.AllowSelection       = GridSelectionFlags.Cell;
            model.ColumnWidths.HeaderLineCount = 1;
            model.ColumnCount = 10;

            model.RowHeights.HeaderLineCount = 1;
            model.RowHeights.FooterLineCount = 1;
            model.RowCount = 13; // make sure this matched covered cell size ...
            model.RowHeights.DefaultLineSize = 30;

            Color clr         = Color.FromArgb(128, 0, 0, 0);
            Brush headerBrush = new SolidColorBrush(clr);

            headerBrush.Freeze();

            Color clr2        = Color.FromArgb(128, 128, 0, 0);
            Brush footerBrush = new SolidColorBrush(clr2);

            footerBrush.Freeze();

            for (int n = 0; n < model.RowCount; n++)
            {
                for (int c = 0; c < model.ColumnCount; c++)
                {
                    GridStyleInfo ci = new GridStyleInfo();
                    ci.CellType             = "TextBox";
                    ci.CellValue            = String.Format("{0}:{1}", n, c);
                    ci.BorderMargins.Top    = gridLinePen.Thickness;
                    ci.BorderMargins.Left   = gridLinePen.Thickness;
                    ci.BorderMargins.Right  = gridLinePen.Thickness / 2;
                    ci.BorderMargins.Bottom = gridLinePen.Thickness / 2;
                    ci.Borders.Right        = gridLinePen;
                    ci.Background           = null;// Brushes.White;
                    ci.Borders.Bottom       = gridLinePen;
                    model.Data[n, c]        = ci.Store;

                    if (c == 0 || n == 0)
                    {
                        ci.CellType   = "Static";
                        ci.Background = headerBrush;
                    }

                    if (c == 3 || n == 3)
                    {
                        ci.CellType  = "CheckBox";
                        ci.CellValue = false;
                    }
                    if (c == 4 || n == 4)
                    {
                        ci.CellType  = "Static";
                        ci.CellValue = "Static";
                    }
                    if (n == model.RowCount - 1)
                    {
                        ci.CellType   = "Static";
                        ci.Background = footerBrush;
                    }
                }
            }
            model.SelectedCells = GridRangeInfo.Empty;

            return(model);
        }
示例#31
0
文件: DevBiz.cs 项目: kyoybs/MvcGrid
        public static GridModel GetField(int fieldId)
        {
            GridModel model = new GridModel();

            using (var sqlb = DbHelper.CreateSql())
            {
                sqlb.SelectSql = @"SELECT f.*, t.ControlTypeName FROM DevFieldInfo f LEFT JOIN dbo.DevControlType t ON f.ControlTypeId=t.ControlTypeId ";
                sqlb.AddFilter("f.FieldId = @FieldId", "@FieldId",  fieldId);
                model.Data = sqlb.QueryDataTable() ;
                model.AutoSetFields();
            }
            return model;
        }
示例#32
0
 public GridComboBoxCellModelEx(GridModel grid)
     : base(grid)
 {
 }
示例#33
0
        public HttpResponseMessage Get(DispensaryDataTableParams filter)
        {
            IQueryable <Dispensary> query = null;

            if (User.IsInRole("GlobalAdmin"))
            {
                query = from d in HGContext.Dispensaries.Include(d => d.Address) where !d.IsDeleted select d;
            }
            else
            {
                query = from d in HGContext.Dispensaries.Include(d => d.Address) where !d.IsHidden && !d.IsDeleted select d;
            }

            if (!String.IsNullOrEmpty(filter.name))
            {
                query = query.Where(i => i.Name.Contains(filter.name));
            }
            if (!String.IsNullOrEmpty(filter.state))
            {
                query = query.Where(i => i != null && i.Address.State != null && i.Address.State.Contains(filter.state));
            }

            if (filter.iSortCol_0 == 0)
            {
                query = filter.sSortDir_0 == "desc" ? query.OrderByDescending(d => d.Name) : query.OrderBy(d => d.Name);
            }
            if (filter.iSortCol_0 == 1)
            {
                query = filter.sSortDir_0 == "desc" ? query.OrderByDescending(d => d.Address.State) : query.OrderBy(d => d.Address.State);
            }
            if (filter.iSortCol_0 == 2)
            {
                query = filter.sSortDir_0 == "desc" ? query.OrderByDescending(d => d.Type) : query.OrderBy(d => d.Type);
            }
            if (filter.iSortCol_0 == 3)
            {
                query = filter.sSortDir_0 == "desc" ? query.OrderByDescending(d => d.EmailAddress) : query.OrderBy(d => d.EmailAddress);
            }
            if (filter.iSortCol_0 == 4)
            {
                query = filter.sSortDir_0 == "desc" ? query.OrderByDescending(d => d.PhoneNumber) : query.OrderBy(d => d.PhoneNumber);
            }

            var dispensaries = query.AsNoTracking().Skip(filter.iDisplayStart).Take(filter.iDisplayLength).Select(d => new DispensaryModel()
            {
                Id      = d.Id,
                Address = new AddressModel()
                {
                    Name             = d.Address.Name,
                    Address1         = d.Address.Address1,
                    Address2         = d.Address.Address2,
                    Country          = d.Address.Country,
                    City             = d.Address.City,
                    FormattedAddress = d.Address.FormattedAddress,
                    Id          = d.Address.Id,
                    Latitude    = d.Address.Latitude,
                    Longitude   = d.Address.Longitude,
                    PhoneNumber = d.Address.PhoneNumber,
                    State       = d.Address.State,
                    Zip         = d.Address.Zip,
                },
                Description          = d.Description,
                EmailAddress         = d.EmailAddress,
                PhoneNumber          = d.PhoneNumber,
                HasDelivery          = d.HasDelivery,
                HasPickup            = d.HasPickup,
                HasStorefront        = d.HasStorefront,
                HasScheduledDelivery = d.HasScheduledDelivery,
                HoursAndInfo         = d.HoursAndInfo,
                IsHidden             = d.IsHidden,
                IsPrivate            = d.IsPrivate,
                Name = d.Name,
                Slug = d.Slug,
                Type = d.Type,
                HoursOfOperationString     = d.HoursOfOperation,
                ApprovalZipCodesCollection = d.ApprovalZipCodes.Select(z => z.Code),
                DeliveryZipCodesCollection = d.DeliveryZipCodes.Select(z => z.Code)
            }).ToList();

            foreach (DispensaryModel dispensary in dispensaries)
            {
                if (dispensary.ApprovalZipCodesCollection != null)
                {
                    dispensary.ApprovalZipCodes = String.Join(", ", dispensary.ApprovalZipCodesCollection);
                }
                if (dispensary.DeliveryZipCodesCollection != null)
                {
                    dispensary.DeliveryZipCodes = String.Join(", ", dispensary.DeliveryZipCodesCollection);
                }

                dispensary.HoursOfOperation = Mapper.Map <List <HoursOfOperation> >(dispensary.HoursOfOperationString);
            }

            var count = query.AsNoTracking().Count();

            GridModel <DispensaryModel> gritItems = new GridModel <DispensaryModel>()
            {
                aaData = dispensaries,
                iTotalDisplayRecords = count,
                iTotalRecords        = count,
                sEcho = filter.sEcho
            };

            var response = Request.CreateResponse(HttpStatusCode.OK, gritItems);

            return(response);
        }
示例#34
0
        /// <summary>
        /// Customization for Pasting the data to grid
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void gridControl1_ClipboardCanPaste(object sender, GridCutPasteEventArgs e)
        {
            IDataObject dataObject = Clipboard.GetDataObject();

            if (dataObject != null)
            {
                if (dataObject.GetDataPresent("Biff", true))
                {
                    ExcelEngine  xlEngine = new ExcelEngine();
                    IApplication app      = xlEngine.Excel;
                    IWorkbooks   workBook = app.Workbooks;
                    workBook.PasteWorkbook();
                    IWorkbook  book      = workBook[0];
                    IWorksheet worksheet = book.Worksheets[0];

                    IRange ur = worksheet.UsedRange;

                    IRange[] ranges = ur.Cells;//worksheet.UsedCells;
                    System.Text.StringBuilder str = new System.Text.StringBuilder();



                    int lastCol = ranges[0].Column, lastRow = ranges[0].Row;
                    int rc = ur.LastRow - ur.Row + 1;
                    int cc = ur.LastColumn - ur.Column + 1;

                    GridExcelConverterControl converter = new GridExcelConverterControl();
                    GridModel model = new GridModel();

                    model.ColCount = cc;
                    model.RowCount = rc;
                    ur.MoveTo(worksheet.Range[1, 1, rc, cc]);
                    ranges = worksheet.Range[1, 1, rc, cc].Cells;
                    foreach (IRange cell in ranges)
                    {
                        converter.ConvertExcelRangeToGrid(cell, model);
                    }

                    GridData data = new GridData();
                    data.InsertRows(1, rc);
                    data.InsertCols(1, cc);

                    for (int i = 1; i <= model.Data.RowCount; i++)
                    {
                        for (int j = 1; j <= model.ColCount; j++)
                        {
                            if (model.Data[i, j] != null)
                            {
                                data[i - 1, j - 1] = model.Data[i, j].Clone() as GridStyleInfoStore;
                            }
                        }
                    }

                    //Clipboard.Clear();
                    DataObject newDataObject = new DataObject(data);
                    Clipboard.SetDataObject(newDataObject, true);
                    xlEngine.ThrowNotSavedOnDestroy = false;
                    xlEngine.Dispose();
                }
            }
        }
示例#35
0
        public ActionResult List(bool liveRates = false)
        {
            if (!_services.Permissions.Authorize(StandardPermissionProvider.ManageCurrencies))
            {
                return(AccessDeniedView());
            }

            var store  = _services.StoreContext.CurrentStore;
            var models = _currencyService.GetAllCurrencies(true).Select(x => x.ToModel()).ToList();

            foreach (var model in models)
            {
                model.IsPrimaryStoreCurrency        = (store.PrimaryStoreCurrencyId == model.Id);
                model.IsPrimaryExchangeRateCurrency = (store.PrimaryExchangeRateCurrencyId == model.Id);
            }

            //var allStores = _services.StoreService.GetAllStores();
            //foreach (var model in models)
            //{
            //	var storeNames = allStores.Where(x => x.PrimaryStoreCurrencyId == model.Id).Select(x => x.Name).ToList();

            //	model.IsPrimaryStoreCurrency = string.Join("<br />", storeNames);

            //	storeNames = allStores.Where(x => x.PrimaryExchangeRateCurrencyId == model.Id).Select(x => x.Name).ToList();

            //	model.IsPrimaryExchangeRateCurrency = string.Join("<br />", storeNames);
            //}

            if (liveRates)
            {
                try
                {
                    var primaryExchangeCurrency = _services.StoreContext.CurrentStore.PrimaryExchangeRateCurrency;
                    if (primaryExchangeCurrency == null)
                    {
                        throw new SmartException("Primary exchange rate currency is not set");
                    }

                    ViewBag.Rates = _currencyService.GetCurrencyLiveRates(primaryExchangeCurrency.CurrencyCode);
                }
                catch (Exception exc)
                {
                    NotifyError(exc, false);
                }
            }

            ViewBag.ExchangeRateProviders = new List <SelectListItem>();

            foreach (var erp in _currencyService.LoadAllExchangeRateProviders())
            {
                ViewBag.ExchangeRateProviders.Add(new SelectListItem
                {
                    Text     = _pluginMediator.GetLocalizedFriendlyName(erp.Metadata),
                    Value    = erp.Metadata.SystemName,
                    Selected = erp.Metadata.SystemName.Equals(_currencySettings.ActiveExchangeRateProviderSystemName, StringComparison.InvariantCultureIgnoreCase)
                });
            }

            ViewBag.AutoUpdateEnabled = _currencySettings.AutoUpdateEnabled;

            var gridModel = new GridModel <CurrencyModel>
            {
                Data  = models,
                Total = models.Count()
            };

            return(View(gridModel));
        }
示例#36
0
 /// <summary>
 /// Initializes a new <see cref="EllipsisCellModel"/> object
 /// and stores a reference to the <see cref="GridModel"/> this cell belongs to.
 /// </summary>
 /// <param name="grid">The <see cref="GridModel"/> for this cell model.</param>
 /// <remarks>
 /// You typically access cell models through the <see cref="GridModel.CellModels"/>
 /// property of the <see cref="GridModel"/> class.
 /// </remarks>
 public EllipsisCellModel(GridModel grid)
     : base(grid)
 {
 }
示例#37
0
 public ActionResult User(GridModel gridModel)
 {
     gridModel = userData.GetData();
     return(View(gridModel));
 }
        public ActionResult Index(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            //data.projects = data.projects.OrderBy(project => project.status).ThenBy(project => project.project_id).ToList();

            string    pID      = data.projects[0].project_id.ToString(); // Obtain 1st Project ID
            GridModel overview = new GridModel();

            overview.DataSource = data.resourceOverview[pID].weeks[0].resources.AsQueryable();

            overview.ID                  = "resource-overview-table";
            overview.PrimaryKey          = "employeedID";
            overview.Width               = "100%";
            overview.AutoGenerateColumns = false;
            overview.AutoGenerateLayouts = false;
            overview.EnableHoverStyles   = false;
            overview.AutofitLastColumn   = false;

            GridColumn employeeIDCol = new GridColumn();

            employeeIDCol.Key        = "employeeID";
            employeeIDCol.HeaderText = "Employee ID";
            employeeIDCol.DataType   = "string";
            employeeIDCol.Hidden     = true;

            GridColumn disciplineCol = new GridColumn();

            disciplineCol.Key               = "discipline";
            disciplineCol.HeaderText        = "Discipline";
            disciplineCol.DataType          = "string";
            disciplineCol.Width             = "113px";
            disciplineCol.HeaderCssClass    = "disciplineCol";
            disciplineCol.ColumnCssClass    = "disciplineCol";
            disciplineCol.FormatterFunction = "formatResourceFirstCol";

            overview.Columns.Add(employeeIDCol);
            overview.Columns.Add(disciplineCol);

            int      wk = 1;
            int      compareWithStartDate, compareWithEndDate;
            string   today = "2015-07-07 12:00:00";
            DateTime t1 = Convert.ToDateTime(today);
            DateTime sdate, edate;
            string   sdateMonth, edateMonth, sdateDay, edateDay, curLabel;

            curLabel = @Resources.Main.Overview_CurrentLabel;
            foreach (var week in data.resourceOverview[pID].weeks)
            {
                sdate = Convert.ToDateTime(week.startDate);
                edate = Convert.ToDateTime(week.endDate);
                compareWithStartDate = DateTime.Compare(t1, sdate);
                compareWithEndDate   = DateTime.Compare(t1, edate);

                sdateMonth = week.startDate.Substring(5, 2).TrimStart(new Char[] { '0' });
                sdateDay   = week.startDate.Substring(8, 2).TrimStart(new Char[] { '0' });
                edateMonth = week.endDate.Substring(5, 2).TrimStart(new Char[] { '0' });
                edateDay   = week.endDate.Substring(8, 2).TrimStart(new Char[] { '0' });
                GridColumn weekCol = new GridColumn();
                weekCol.Key = "discipline";
                if (compareWithStartDate > 0 && compareWithEndDate < 0)
                {
                    weekCol.HeaderText = @"<div class='igColHeader current' data-week='" + wk + "' data-week-end='" + week.endDate + "' data-week-start='" + week.startDate + "'>" + sdateMonth + "/" + sdateDay + "-" + edateMonth + "/" + edateDay + " <small style='color: #fff;'>(" + curLabel + ")</small></div>";
                }
                else
                {
                    weekCol.HeaderText = @"<div class='igColHeader' data-week='" + wk + "' data-week-end='" + week.endDate + "' data-week-start='" + week.startDate + "'>" + sdateMonth + "/" + sdateDay + "-" + edateMonth + "/" + edateDay + "</div>";
                }
                weekCol.DataType       = "string";
                weekCol.Width          = "113px";
                weekCol.ColumnCssClass = "gaugeRow";
                weekCol.Template       = @"<div class='hidden notification overage'></div><div class='linear-gauge week" + wk + "' data-week='" + wk + "'></div>";

                overview.Columns.Add(weekCol);

                wk = wk + 1;
            }
            overview.AddClientEvent("rowsRendered", "app.utils.renderLinearGauge(resourceOverview['10000'])");



            GridModel tasks = new GridModel();

            tasks.DataSource = data.taskList[pID].tasks.AsQueryable();

            tasks.ID                  = "project-tasks-table";
            tasks.PrimaryKey          = "id";
            tasks.AutoGenerateColumns = false;
            tasks.AlternateRowStyles  = false;
            tasks.EnableHoverStyles   = true;
            tasks.ShowHeader          = false;


            GridColumn taskIDCol = new GridColumn();

            taskIDCol.Key        = "id";
            taskIDCol.HeaderText = "Task ID";
            taskIDCol.DataType   = "number";
            taskIDCol.Hidden     = true;

            GridColumn taskCol = new GridColumn();

            taskCol.Key               = "name";
            taskCol.HeaderText        = "Task";
            taskCol.DataType          = "string";
            taskCol.FormatterFunction = @"function(v,r) { return ""<div class='taskItem' data-task-end='"" + r.endDate + ""' data-task-start='"" + r.startDate + ""'><span class='taskname "" + r.flag + ""' data-category='"" + r.discipline.toLowerCase().replace(' ', '-') + ""'>"" + v + "" <small>(# "" + r.id + "")</small></span><span class='enddate'>"" + Resources.TaskProjectedEndLabel + "" "" + (parseDate(r.endDate).getMonth()+1) + '/' + parseDate(r.endDate).getDate() + ""</span><span class='hours'>"" + r.hours +  "" <span class='visible-lg-inline'>"" + Resources.TaskHoursLabel + ""</span><span class='visible-md-inline visible-sm-inline visible-xs-inline'>"" + Resources.TaskHrsLabel + ""</span></span></div>""; }";

            GridColumn flagCol = new GridColumn();

            flagCol.Key        = "flag";
            flagCol.HeaderText = "Flag";
            flagCol.DataType   = "string";
            flagCol.Hidden     = true;

            GridColumn discCol = new GridColumn();

            discCol.Key        = "discipline";
            discCol.HeaderText = "Discipline";
            discCol.DataType   = "string";
            discCol.Hidden     = true;

            GridColumn edateCol = new GridColumn();

            edateCol.Key        = "endDate";
            edateCol.HeaderText = "End Date";
            edateCol.DataType   = "string";
            edateCol.Hidden     = true;

            GridColumn sdateCol = new GridColumn();

            sdateCol.Key        = "startDate";
            sdateCol.HeaderText = "Start Date";
            sdateCol.DataType   = "string";
            sdateCol.Hidden     = true;

            GridColumn hoursCol = new GridColumn();

            hoursCol.Key        = "hours";
            hoursCol.HeaderText = "hours";
            hoursCol.DataType   = "string";
            hoursCol.Hidden     = true;

            /*Add Columns*/
            tasks.Columns.Add(taskIDCol);
            tasks.Columns.Add(taskCol);
            tasks.Columns.Add(flagCol);
            tasks.Columns.Add(discCol);
            tasks.Columns.Add(edateCol);
            tasks.Columns.Add(sdateCol);
            tasks.Columns.Add(hoursCol);

            GridColumnLayoutModel layout = new GridColumnLayoutModel();

            layout.Key = "assets";
            layout.AutoGenerateColumns = false;
            layout.EnableHoverStyles   = false;
            layout.ShowHeader          = false;

            GridColumn type = new GridColumn();

            type.Key               = "type";
            type.HeaderText        = "Type";
            type.DataType          = "string";
            type.ColumnCssClass    = "file-type";
            type.FormatterFunction = @"function(val){return ""<i class='icon-sm icon-"" + val + ""'></i>"";}";

            GridColumn name = new GridColumn();

            name.Key            = "name";
            name.HeaderText     = "Assets";
            name.DataType       = "string";
            name.ColumnCssClass = "task-name";

            GridColumn url = new GridColumn();

            url.Key               = "url";
            url.HeaderText        = "URL";
            url.DataType          = "string";
            url.FormatterFunction = @"function(val){return ""<small>(<a href='"" + val + ""' target='_blank'>"" + Resources.TaskViewFile + ""</a>)</small>"";}";

            layout.Columns.Add(type);
            layout.Columns.Add(name);
            layout.Columns.Add(url);


            tasks.ColumnLayouts.Add(layout);

            tasks.AddClientEvent("rowsRendered", "app.utils.taskListRowsRendered()");
            tasks.AddClientEvent("rowExpanding", "app.utils.taskListRowsExpanding(evt,ui)");


            dynamic vm = new ExpandoObject();

            vm.data  = data;
            vm.grid  = overview;
            vm.tasks = tasks;

            return(View(vm));
        }
 internal DataGridColumnCollection(GridModel owner)
 {
     this.owner = owner;
 }
示例#40
0
        public GridModel <MeritRangeViewModel> ObtenerLista(DataTableAjaxPostModel filters)
        {
            var searchBy = (filters.search != null) ? filters.search.value : null;


            string sortBy  = "";
            string sortDir = "";

            if (filters.order != null)
            {
                // in this example we just default sort on the 1st column
                sortBy  = filters.columns[filters.order[0].column].data;
                sortDir = filters.order[0].dir.ToLower();
            }


            GridModel <MeritRangeViewModel> resultado    = new GridModel <MeritRangeViewModel>();
            IQueryable <merit_ranges>       queryFilters = Set;



            int count_records          = queryFilters.Count();
            int count_records_filtered = count_records;


            if (String.IsNullOrWhiteSpace(searchBy) == false)
            {
                // as we only have 2 cols allow the user type in name 'firstname lastname' then use the list to search the first and last name of dbase
                var searchTerms = searchBy.Split(' ').ToList().ConvertAll(x => x.ToLower());

                queryFilters = queryFilters.Where(s => searchTerms.Any(srch => s.name.ToLower().Contains(srch)));


                count_records_filtered = queryFilters.Count();
            }


            var query = queryFilters.Select(a => new MeritRangeViewModel
            {
                merit_range_id = a.merit_range_id,
                name           = a.name,
                lower_limit    = a.lower_limit,
                upper_limit    = a.upper_limit,
                url_image      = a.url_image
            });

            if (String.IsNullOrEmpty(sortBy))
            {
                sortBy = "merit_range_id";
            }
            if (String.IsNullOrEmpty(sortDir))
            {
                sortDir = "asc";
            }
            string sortExpression = sortBy.Trim() + " " + sortDir.Trim();

            if (sortExpression.Trim() != "")
            {
                query = OrderByDinamic.OrderBy <MeritRangeViewModel>(query, sortExpression.Trim());
            }
            resultado.rows = query.Skip(filters.start).Take(filters.length).ToList();



            resultado.total = count_records;

            resultado.recordsFiltered = count_records_filtered;
            return(resultado);
        }
 public MultipleButtonCellModel(GridModel grid)
     : base(grid)
 {
     AllowFloating = false;
     ButtonBarSize = new Size(120, 120);
 }
示例#42
0
        public NestedGridSampleGridControl()
        {
            GridCellNestedGridModel       gridModel                  = new GridCellNestedGridModel(GridNestedAxisLayout.Normal, GridNestedAxisLayout.Normal);
            GridCellNestedScrollGridModel scrollGridModel            = new GridCellNestedScrollGridModel();
            GridCellNestedGridModel       shareRowLayoutGridModel    = new GridCellNestedGridModel(GridNestedAxisLayout.Shared, GridNestedAxisLayout.Normal);
            GridCellNestedGridModel       shareColumnLayoutGridModel = new GridCellNestedGridModel(GridNestedAxisLayout.Normal, GridNestedAxisLayout.Shared);
            GridCellNestedGridModel       gridInRowModel             = new GridCellNestedGridModel(GridNestedAxisLayout.Nested, GridNestedAxisLayout.Normal);

            Model.CellModels.Add("Grid", gridModel);
            Model.CellModels.Add("ScrollGrid", scrollGridModel);
            Model.CellModels.Add("ShareRowLayoutGrid", shareRowLayoutGridModel);
            Model.CellModels.Add("ShareColumnLayoutGrid", shareColumnLayoutGridModel);
            Model.CellModels.Add("GridInRow", gridInRowModel);


            #region Sample Setup

            RowHeights.DefaultLineSize = 20;
            Model.RowCount             = 6000;

            ColumnWidths.DefaultLineSize = 100;
            Model.ColumnCount            = 20;

            Random buttonRandom    = new Random(23);
            Random orangePenRandom = new Random(2);
            Random backBrushRandom = new Random(18);

            gridLinePen = new Pen(Brushes.DarkGray, 1);
            gridLinePen.Freeze();

            Pen orangePen = new Pen(Brushes.DarkOrange, 5);
            orangePen.EndLineCap   = PenLineCap.Triangle;
            orangePen.StartLineCap = PenLineCap.Triangle;
            orangePen.Freeze();

            Pen bgPen = new Pen(Brushes.Gold, 6);
            bgPen.EndLineCap   = PenLineCap.Triangle;
            bgPen.StartLineCap = PenLineCap.Triangle;
            bgPen.Freeze();


            SolidColorBrush bg1 = new SolidColorBrush(Color.FromArgb(128, 128, 0, 0));
            SolidColorBrush bg2 = new SolidColorBrush(Color.FromArgb(128, 0, 128, 0));
            SolidColorBrush bg3 = new SolidColorBrush(Color.FromArgb(128, 0, 0, 128));

            GradientBrush bg = new LinearGradientBrush(Color.FromArgb(128, 255, 255, 0), Color.FromArgb(128, 0, 255, 255), 45.0);
            //GradientBrush bg = new LinearGradientBrush(Colors.Gray, Colors.White, 45);
            CellSpanBackgrounds.Add(new CellSpanBackgroundInfo(9, 2, 22, 8, false, false, bg1, bgPen));
            CellSpanBackgrounds.Add(new CellSpanBackgroundInfo(3, 4, 28, 6, false, false, bg2, bgPen));
            CellSpanBackgrounds.Add(new CellSpanBackgroundInfo(25, 2, 30, 4, false, false, bg3, bgPen));
            CellSpanBackgrounds.Add(new CellSpanBackgroundInfo(0, 0, 12, 1, false, false, bg, null));
            CoveredCells.Add(new CoveredCellInfo(4, 0, 6, 1));
            CoveredCells.Add(new CoveredCellInfo(4, 19, 6, 19));
            CoveredCells.Add(new CoveredCellInfo(6, 2, 8, 4));
            CoveredCells.Add(new CoveredCellInfo(4, 2, 5, 3));

            Model.QueryCellInfo += new GridQueryCellInfoEventHandler(Model_QueryCellInfo);

            for (int n = 0; n < Model.RowCount; n++)
            {
                for (int c = 0; c < Model.ColumnCount; c++)
                {
                    GridStyleInfo ci = new GridStyleInfo();

                    if (backBrushRandom.Next(10) == 5)
                    {
                        ci.Background = Brushes.Tomato;
                    }

                    if (c == 5)//% 4 == 3)// || c == 5)
                    {
                        ci.CellType    = "CheckBox";
                        ci.Description = String.Format("Check {0}:{1}", n, c);
                        ci.CellValue   = n % 2 == 0;
                    }

                    if (c == 2)
                    {
                        ci.CellType  = "TextBox";
                        ci.CellValue = String.Format("Edit {0}:{1}", n, c);
                    }


                    if (buttonRandom.Next(10) == 5)
                    {
                        ci.CellType    = "Button";
                        ci.Description = String.Format("Click {0}:{1}", n, c);
                        ci.Background  = null;
                    }

                    if (orangePenRandom.Next(10) == 5)
                    {
                        ci.Borders.Right  = orangePen;
                        ci.Borders.Bottom = orangePen;
                        ci.Borders.Left   = orangePen;
                        ci.Borders.Top    = orangePen;
                        //ci.BorderMargins.Right = orangePen.Thickness / 2;
                        //ci.BorderMargins.Bottom = orangePen.Thickness / 2;
                        //ci.BorderMargins.Top = orangePen.Thickness / 2;
                        //ci.BorderMargins.Left = orangePen.Thickness / 2;
                    }

                    if (!ci.IsEmpty)
                    {
                        //if (n == Model.RowCount - 1 && c == Model.ColCount - 1)
                        //    Console.WriteLine("ddd");
                        Model[n, c].Background = Brushes.Red;
                        Model[n, c]            = ci;
                    }
                }
            }

            if (true)
            {
                Model[6, 2].CellType = "Grid";
                //Model[6, 2].CellRenderer = gridRenderer;
                Model[6, 2].CellValue = GetSimpleNestedGrid();
            }

            if (true)
            {
                CoveredCellInfo coveredCell1 = new CoveredCellInfo(36, 0, 36, Model.ColumnCount - 1);
                coveredCell1.SpanWholeRow = true;
                CoveredCells.Add(coveredCell1);
                Model[36, 0].CellType = "GridInRow";
                //Model[36, 0].CellRenderer = gridInRowRenderer;
                GridModel m = GetSimpleNestedGrid();
                Model[36, 0].CellValue = m;
                //PixelScrollAxis mb = new PixelScrollAxis(new ScrollInfo(), m.RowHeights);
                RowHeights.SetNestedLines(36, m.RowHeights);//.Distances;//.TotalDistance

                GridModel m2 = GetSimpleNestedGrid();
                m[5, 1].Background = new SolidColorBrush(Colors.LightCoral);
                m[5, 1].CellValue  = m2;
                m2.ColumnWidths.DefaultLineSize = 65;
                m[5, 1].CellType = "GridInRow";
                //m[5, 1].CellRenderer = gridInRowRenderer;
                m.RowHeights.SetNestedLines(5, m2.RowHeights);
                m.CoveredCells.Add(new CoveredCellInfo(5, 1, 5, 6));
            }

            if (true)
            {
                Model[40, 2].CellType = "ScrollGrid";
                //Model[40, 2].CellRenderer = scrollGridRenderer;
                Model[40, 2].CellValue = GetScrollNestedGrid();
                CoveredCells.Add(new CoveredCellInfo(40, 2, 49, 5));
            }

            if (true)
            {
                Model[60, 1].CellType = "ShareColumnLayoutGrid";
                //Model[60, 1].CellRenderer = shareColumnLayoutGridRenderer;
                Model[60, 1].BorderMargins.Top    = 0;
                Model[60, 1].BorderMargins.Left   = 0;
                Model[60, 1].BorderMargins.Right  = 0;
                Model[60, 1].BorderMargins.Bottom = 0;
                Model[60, 1].Background           = SystemColors.InactiveCaptionBrush;
                GridModel nestedGridWithSharedColumnsModel = GetNestedGridWithSharedColumnsModel();
                Model[60, 1].CellValue = nestedGridWithSharedColumnsModel;
                CoveredCells.Add(new CoveredCellInfo(60, 1, 80, 1 + nestedGridWithSharedColumnsModel.ColumnCount - 1));
            }

            if (true)
            {
                Model[100, 2].CellType = "ShareRowLayoutGrid";
                //Model[100, 2].CellRenderer = shareRowLayoutGridRenderer;
                Model[100, 2].BorderMargins.Top    = 0;
                Model[100, 2].BorderMargins.Left   = 0;
                Model[100, 2].BorderMargins.Right  = 0;
                Model[100, 2].BorderMargins.Bottom = 0;
                Model[100, 2].Background           = SystemColors.InactiveCaptionBrush;
                GridModel nestedGridWithSharedRowsModel = GetNestedGridWithSharedRowsModel();
                Model[100, 2].CellValue = nestedGridWithSharedRowsModel;
                CoveredCells.Add(new CoveredCellInfo(100, 2, 100 + nestedGridWithSharedRowsModel.RowCount - 1, 5));

                Random rnd = new Random(120);
                for (int n = 0; n < 100; n++)
                {
                    RowHeights[rnd.Next(Model.RowCount)] = rnd.Next(10, 50);
                }

                for (int n = 0; n < 5; n++)
                {
                    ColumnWidths[rnd.Next(Model.ColumnCount)] = rnd.Next(40, 400);
                }
            }

            RowHeights.SetHidden(10, 20, true);

            FrozenRows    = 2;
            FrozenColumns = 1;
            FooterColumns = 1;
            FooterRows    = 1;

            Console.WriteLine(FrozenRows);
            Console.WriteLine(FrozenColumns);

            #endregion

            GridStyleInfo tableStyle  = Model.TableStyle;
            GridStyleInfo headerStyle = Model.HeaderStyle;
            GridStyleInfo footerStyle = Model.FooterStyle;

            tableStyle.CellType             = "TextBox";
            tableStyle.BorderMargins.Top    = gridLinePen.Thickness;
            tableStyle.BorderMargins.Left   = gridLinePen.Thickness;
            tableStyle.BorderMargins.Right  = gridLinePen.Thickness / 2;
            tableStyle.BorderMargins.Bottom = gridLinePen.Thickness / 2;
            tableStyle.Borders.Right        = gridLinePen;
            tableStyle.Background           = null;// Brushes.White;
            tableStyle.Borders.Bottom       = gridLinePen;

            headerStyle.Background = SystemColors.ControlBrush;
            headerStyle.CellType   = "Static";

            footerStyle.Background = Brushes.Wheat;
        }
示例#43
0
        public GridModel <GoogleProductModel> GetGridModel(GridCommand command, string searchProductName = null, string touched = null)
        {
            var model    = new GridModel <GoogleProductModel>();
            var textInfo = CultureInfo.InvariantCulture.TextInfo;

            // there's no way to share a context instance across repositories which makes GoogleProductObjectContext pretty useless here.
            // so let's fallback to good ole sql... by the way, fastest possible paged data query ever.

            var whereClause = new StringBuilder("(NOT ([t2].[Deleted] = 1)) AND ([t2].[VisibleIndividually] = 1)");

            if (searchProductName.HasValue())
            {
                whereClause.AppendFormat(" AND ([t2].[Name] LIKE '%{0}%')", searchProductName.Replace("'", "''"));
            }

            if (touched.HasValue())
            {
                if (touched.IsCaseInsensitiveEqual("touched"))
                {
                    whereClause.Append(" AND ([t2].[IsTouched] = 1)");
                }
                else
                {
                    whereClause.Append(" AND ([t2].[IsTouched] = 0 OR [t2].[IsTouched] IS NULL)");
                }
            }

            string sql =
                "SELECT [TotalCount], [t3].[Id], [t3].[Name], [t3].[SKU], [t3].[ProductTypeId], [t3].[value] AS [Taxonomy], [t3].[value2] AS [Gender], [t3].[value3] AS [AgeGroup], [t3].[value4] AS [Color], [t3].[value5] AS [Size], [t3].[value6] AS [Material], [t3].[value7] AS [Pattern]" +
                " FROM (" +
                "    SELECT COUNT(id) OVER() [TotalCount], ROW_NUMBER() OVER (ORDER BY [t2].[Name]) AS [ROW_NUMBER], [t2].[Id], [t2].[Name], [t2].[SKU], [t2].[ProductTypeId], [t2].[value], [t2].[value2], [t2].[value3], [t2].[value4], [t2].[value5], [t2].[value6], [t2].[value7]" +
                "    FROM (" +
                "        SELECT [t0].[Id], [t0].[Name], [t0].[SKU], [t0].[ProductTypeId], [t1].[Taxonomy] AS [value], [t1].[Gender] AS [value2], [t1].[AgeGroup] AS [value3], [t1].[Color] AS [value4], [t1].[Size] AS [value5], [t1].[Material] AS [value6], [t1].[Pattern] AS [value7], [t0].[Deleted], [t0].[VisibleIndividually], [t1].[IsTouched]" +
                "        FROM [Product] AS [t0]" +
                "        LEFT OUTER JOIN [GoogleProduct] AS [t1] ON [t0].[Id] = [t1].[ProductId]" +
                "        ) AS [t2]" +
                "    WHERE " + whereClause.ToString() +
                "    ) AS [t3]" +
                " WHERE [t3].[ROW_NUMBER] BETWEEN {0} + 1 AND {0} + {1}" +
                " ORDER BY [t3].[ROW_NUMBER]";


            var data = _gpRepository.Context.SqlQuery <GoogleProductModel>(sql, (command.Page - 1) * command.PageSize, command.PageSize).ToList();

            data.ForEach(x =>
            {
                if (x.ProductType != ProductType.SimpleProduct)
                {
                    string key        = "Admin.Catalog.Products.ProductType.{0}.Label".FormatWith(x.ProductType.ToString());
                    x.ProductTypeName = Helper.GetResource(key);
                }

                var googleProduct = GetGoogleProductRecord(x.Id);
                if (x.Gender.HasValue())
                {
                    x.GenderLocalize = Helper.GetResource("Gender" + textInfo.ToTitleCase(x.Gender));
                }

                if (x.AgeGroup.HasValue())
                {
                    x.AgeGroupLocalize = Helper.GetResource("AgeGroup" + textInfo.ToTitleCase(x.AgeGroup));
                }
            });

            model.Data  = data;
            model.Total = (data.Count > 0 ? data.First().TotalCount : 0);

            return(model);

            #region old code

            //var searchContext = new ProductSearchContext()
            //{
            //	Keywords = searchProductName,
            //	PageIndex = command.Page - 1,
            //	PageSize = command.PageSize,
            //	VisibleIndividuallyOnly = true,
            //	ShowHidden = true
            //};

            //var products = _productService.SearchProducts(searchContext);

            //var data = products.Select(x =>
            //{
            //	var gModel = new GoogleProductModel()
            //	{
            //		ProductId = x.Id,
            //		Name = x.Name
            //	};

            //	var googleProduct = GetByProductId(x.Id);

            //	if (googleProduct != null)
            //	{
            //		gModel.Taxonomy = googleProduct.Taxonomy;
            //		gModel.Gender = googleProduct.Gender;
            //		gModel.AgeGroup = googleProduct.AgeGroup;
            //		gModel.Color = googleProduct.Color;
            //		gModel.Size = googleProduct.Size;
            //		gModel.Material = googleProduct.Material;
            //		gModel.Pattern = googleProduct.Pattern;

            //		if (gModel.Gender.HasValue())
            //			gModel.GenderLocalize = Helper.GetResource("Gender" + CultureInfo.InvariantCulture.TextInfo.ToTitleCase(gModel.Gender));

            //		if (gModel.AgeGroup.HasValue())
            //			gModel.AgeGroupLocalize = Helper.GetResource("AgeGroup" + CultureInfo.InvariantCulture.TextInfo.ToTitleCase(gModel.AgeGroup));
            //	}

            //	return gModel;
            //})
            //.ToList();

            //var model = new GridModel<GoogleProductModel>()
            //{
            //	Data = data,
            //	Total = products.TotalCount
            //};

            //return model;

            #endregion old code
        }
示例#44
0
 public Model(GridModel model)
 {
     this.model = model;
 }
示例#45
0
 // visszatérési értéke a lépés helyességétől függ
 public bool MakeMove(GridModel grid, Position pos)
 {
     return(grid.MakeMove(pos.IPos, pos.JPos, this.Mark));
 }
示例#46
0
 public едакторЯчеек_ТекстСМаской(GridModel grid) : base(grid)
 {
     base.AllowFloating = false;
 }
示例#47
0
    public GridModel Read(int take, int skip) 
    {
        using (var northwind = new Northwind())
        {
            IQueryable<ProductViewModel> data = northwind.Products
                // Use a view model to avoid serializing internal Entity Framework properties as JSON
                .Select(p => new ProductViewModel
                {
                    ProductID = p.ProductID,
                    ProductName = p.ProductName,
                    UnitPrice = p.UnitPrice,
                    UnitsInStock = p.UnitsInStock,
                    Discontinued = p.Discontinued
                });
            var total = data.Count();

            var gridModel = new GridModel()
            {
                 Data = data.OrderBy(p=>p.ProductID).Skip(skip)
                            .Take(take)
                            .ToList(),
                 Total = total
            };

            return gridModel;
        }
    }
示例#48
0
 public override Direction ComputeNextMove(GridModel grid)
 {
     return(Direction.Up);
 }
 private void ExportHelper(IWorksheet Sheet, GridModel gridModel, GridStyleInfo Style, RowColumnIndex RowColIndex)
 {
     if (Sheet != null)
     {
         int ivalue; double dvalue; bool bvalue;
         try
         {
             IRange range = Sheet.Range[RowColIndex.RowIndex, RowColIndex.ColumnIndex];
             if (!range.HasFormula || Style.Text.Length == 0 || (Style.Text.Length > 0 && Style.Text[0] != '='))
             {
                 //To new Save Formula
                 if (Style.CellValue != null && Style.CellValue.ToString() != string.Empty && Style.CellValue.ToString()[0] == '=')
                 {
                     if (Style.CellValue.ToString().Contains('!'))
                     {
                         range.Formula = ExcelLikeFormula(gridModel, Style.CellValue.ToString());
                     }
                     else
                     {
                         range.Formula = Style.CellValue.ToString().ToUpper();
                     }
                     if (int.TryParse(Style.FormattedText, out ivalue))
                     {
                         Style.HorizontalAlignment           = System.Windows.HorizontalAlignment.Right;
                         range.CellStyle.HorizontalAlignment = ExcelHAlign.HAlignRight;
                     }
                     else if (double.TryParse(Style.FormattedText, out dvalue))
                     {
                         Style.HorizontalAlignment           = System.Windows.HorizontalAlignment.Right;
                         range.CellStyle.HorizontalAlignment = ExcelHAlign.HAlignRight;
                     }
                 }
                 else
                 {
                     string cellvalue = string.Empty;
                     if (Style.CellValue != null)
                     {
                         cellvalue = Style.CellValue.ToString();
                     }
                     if (Style.CellType == "FormulaCell" && !string.IsNullOrEmpty(Style.Text) && Style.Text[0] == '=')
                     {
                         cellvalue = Style.FormattedText;
                     }
                     //To Save RichText
                     else if (Style.CellType == "RichText")
                     {
                         RichTextBoxHelper.SetRichTextValue(range, Style.CellValue as FlowDocument, Style.FormattedText);
                         return;
                     }
                     //To Save Number
                     if (int.TryParse(cellvalue, out ivalue))
                     {
                         range.Number = ivalue;
                     }
                     else if (double.TryParse(cellvalue, out dvalue))
                     {
                         range.Number = dvalue;
                     }
                     //To Save Boolean value
                     else if (bool.TryParse(cellvalue, out bvalue))
                     {
                         range.Boolean = bvalue;
                         if (bvalue)
                         {
                             Style.CellValue = "TRUE";
                         }
                         else
                         {
                             Style.CellValue = "FALSE";
                         }
                     }
                     //To Save other value
                     else
                     {
                         range.Value = cellvalue;
                     }
                 }
             }
             //To Save Formula
             else
             {
                 if (Style.FormulaTag != null && Style.CellValue != null && Style.CellValue.ToString() != string.Empty && Style.CellValue.ToString()[0] == '=')
                 {
                     if (!range.HasFormula)
                     {
                         if (Style.CellValue.ToString().Contains('!'))
                         {
                             range.Formula = ExcelLikeFormula(gridModel, Style.CellValue.ToString());
                         }
                         else
                         {
                             range.Formula = Style.CellValue.ToString().ToUpper();
                         }
                     }
                     else
                     {
                         range.Formula = ExcelLikeFormula(gridModel, Style.CellValue.ToString());
                     }
                 }
                 else if (!range.HasFormula)
                 {
                     range.Text = Style.FormattedText;
                 }
             }
         }
         catch (Exception)
         {
         }
     }
 }
示例#50
0
        private GridModel GetSecondNestedGridWithSharedRowsModel()
        {
            GridModel model = new GridModel();

            Pen gridLinePen = new Pen(Brushes.DarkGray, 1);

            gridLinePen.Freeze();

            model.Options.AllowSelection       = GridSelectionFlags.Cell;
            model.ColumnWidths.DefaultLineSize = 40;
            model.ColumnWidths.HeaderLineCount = 1;
            model.ColumnCount = 8;

            model.RowHeights.HeaderLineCount = 1;
            model.RowHeights.FooterLineCount = 1;
            model.RowCount = 121; // make sure this matched covered cell size ...

            Color clr         = Color.FromArgb(128, 0, 0, 128);
            Brush headerBrush = new SolidColorBrush(clr);

            headerBrush.Freeze();

            Color clr2        = Color.FromArgb(128, 0, 128, 0);
            Brush footerBrush = new SolidColorBrush(clr2);

            footerBrush.Freeze();

            for (int n = 0; n < model.RowCount; n++)
            {
                for (int c = 0; c < model.ColumnCount; c++)
                {
                    GridStyleInfo ci = new GridStyleInfo();
                    ci.CellType             = "TextBox";
                    ci.CellValue            = String.Format("{0}:{1}", n, c);
                    ci.BorderMargins.Top    = gridLinePen.Thickness;
                    ci.BorderMargins.Left   = gridLinePen.Thickness;
                    ci.BorderMargins.Right  = gridLinePen.Thickness / 2;
                    ci.BorderMargins.Bottom = gridLinePen.Thickness / 2;
                    ci.Borders.Right        = gridLinePen;
                    ci.Background           = null;// Brushes.White;
                    ci.Borders.Bottom       = gridLinePen;
                    model.Data[n, c]        = ci.Store;

                    if (c == 0 || n == 0)
                    {
                        ci.CellType   = "Static";
                        ci.Background = headerBrush;
                    }

                    if (n == model.RowCount - 1)
                    {
                        ci.CellType   = "Static";
                        ci.Background = footerBrush;
                    }
                }
            }

            GridModel nestedGridWithSharedRowsModel = GetThirdNestedGridWithSharedRowsModel();

            model[15, 2].CellType = "ShareRowLayoutGrid";
            //model[15, 2].CellRenderer = shareRowLayoutGridRenderer;
            model[15, 2].BorderMargins.Top    = 0;
            model[15, 2].BorderMargins.Left   = 0;
            model[15, 2].BorderMargins.Right  = 0;
            model[15, 2].BorderMargins.Bottom = 0;
            model[15, 2].Background           = Brushes.Wheat;
            model[15, 2].CellValue            = nestedGridWithSharedRowsModel;
            model.CoveredCells.Add(new CoveredCellInfo(15, 2, 15 + nestedGridWithSharedRowsModel.RowCount - 1, 5));
            model.SelectedCells = GridRangeInfo.Empty;


            return(model);
        }
示例#51
0
 public DropDownGridCellModel(GridModel grid)
     : base(grid)
 {
 }
示例#52
0
 public void RowStart_action_should_be_stored_when_rendered_old_syntax()
 {
     var model = new GridModel<Person>();
     _grid.WithModel(model).RowStart((p) => {});
     _grid.ToString();
     ((IGridModel<Person>)model).Sections.Row
         .StartSectionRenderer(
             new GridRowViewData<Person>(new Person(), true),
             GridRendererTester.FakeRenderingContext()
         ).ShouldBeTrue();
 }
        public ActionResult Update()
        {
            try
            {
                GridModel m = new GridModel();
                List<Transaction<CompanyBranchUser>> transactions = m.LoadTransactions<CompanyBranchUser>(HttpContext.Request.Form["ig_transactions"]);

                foreach (Transaction<CompanyBranchUser> t in transactions)
                {
                    if (t.type == "newrow")
                    {
                        db.CompanyBranchUsers.Add(t.row);
                        db.SaveChanges();
                    }
                    else if (t.type == "editrow")
                    {
                        db.Entry(t.row).State = EntityState.Modified;
                        db.SaveChanges();
                    }
                    else if (t.type == "deleterow")
                    {
                        db.Entry(t.row).State = EntityState.Modified;
                        db.SaveChanges();
                    }
                }
                JsonResult result = new JsonResult();
                Dictionary<string, bool> response = new Dictionary<string, bool>();
                response.Add("Success", true);
                result.Data = response;
                return result;
            }
            catch
            {
                return View();
            }
        }
示例#54
0
 public DateTimeCellModel(GridModel grid)
     : base(grid)
 {
 }
示例#55
0
 public void Columns_should_be_stored()
 {
     var model = new GridModel<Person>();
     _grid.WithModel(model).Columns(col => col.For(x => x.Name));
     ((IGridModel<Person>)model).Columns.Count.ShouldEqual(1);
 }
        public static GridModel ToGridModel(this IQueryable queryable, int page, int pageSize, IList <SortDescriptor> sortDescriptors, IEnumerable <IFilterDescriptor> filterDescriptors,
                                            IEnumerable <GroupDescriptor> groupDescriptors)
        {
            IQueryable data = queryable;

#if MVC3
            if (queryable.ElementType.IsDynamicObject())
            {
                var firstItem = queryable.Cast <object>().FirstOrDefault();
                if (firstItem != null)
                {
                    if (filterDescriptors.Any())
                    {
                        filterDescriptors.SetMemberTypeFrom(firstItem);
                    }

                    if (groupDescriptors.Any())
                    {
                        groupDescriptors.SetMemberTypeFrom(firstItem);
                    }
                }
            }
#endif

            if (filterDescriptors.Any())
            {
                data = data.Where(filterDescriptors);
            }

            GridModel result = new GridModel();

            result.Total = data.Count();
            IList <SortDescriptor> temporarySortDescriptors = new List <SortDescriptor>();

            if (!sortDescriptors.Any() && queryable.Provider.IsEntityFrameworkProvider())
            {
                // The Entity Framework provider demands OrderBy before calling Skip.
                SortDescriptor sortDescriptor = new SortDescriptor
                {
                    Member = queryable.ElementType.FirstSortableProperty()
                };
                sortDescriptors.Add(sortDescriptor);
                temporarySortDescriptors.Add(sortDescriptor);
            }

            if (groupDescriptors.Any())
            {
                groupDescriptors.Reverse().Each(groupDescriptor =>
                {
                    SortDescriptor sortDescriptor = new SortDescriptor
                    {
                        Member        = groupDescriptor.Member,
                        SortDirection = groupDescriptor.SortDirection
                    };

                    sortDescriptors.Insert(0, sortDescriptor);
                    temporarySortDescriptors.Add(sortDescriptor);
                });
            }

            if (sortDescriptors.Any())
            {
                data = data.Sort(sortDescriptors);
            }

            var notPagedData = data;

            data = data.Page(page - 1, pageSize);

            if (groupDescriptors.Any())
            {
                data = data.GroupBy(notPagedData, groupDescriptors);
            }

            result.Data = data;

            temporarySortDescriptors.Each(sortDescriptor => sortDescriptors.Remove(sortDescriptor));

            return(result);
        }
#pragma warning disable 1998
        public async Task<HttpResponseMessage> GetByDispensary(InventoryDataTableParams filter)
        {
            var query =
                HGContext.DispensaryProducts.AsNoTracking()
                    .Include(p => p.DispensaryProductVariants.Select(v => v.Photos))
                    .Where(x => !x.IsDeleted && !x.Dispensary.IsDeleted);

            if (filter.dispensaryId > 0)
                query = query.Where(i => i.DispensaryId == filter.dispensaryId);

            if (filter.categoryId > 0)
                query = query.Where(i => i.ProductCategory.Id == filter.categoryId);

            if (!String.IsNullOrEmpty(filter.name))
                query = query.Where(i => i.Name.Contains(filter.name));


            if (filter.iSortCol_0 == 0)
                query = filter.sSortDir_0 == "desc" ? query.OrderByDescending(d => d.Product.Name) : query.OrderBy(d => d.Product.Name);
            if (filter.iSortCol_0 == 1)
                query = filter.sSortDir_0 == "desc" ? query.OrderByDescending(d => d.Product.ProductCategory.Name) : query.OrderBy(d => d.Product.ProductCategory.Name);
            if (filter.iSortCol_0 == 2)
                query = filter.sSortDir_0 == "desc" ? query.OrderByDescending(d => d.Product.Description) : query.OrderBy(d => d.Product.Description);


            var list = query.Skip(filter.iDisplayStart).Take(filter.iDisplayLength);
            var count = query.Count();
            var mappedlist = list.Select(item => new DispensaryProductModel()
            {
                Id = item.Id,
                Name = item.Name,
                Description = item.Description,
                ProductCategory = item.ProductCategory == null ? null : new ProductCategoryModel() { Id = item.ProductCategory.Id, Name = item.ProductCategory.Name },
                DispensaryProductVariants =
                    item.DispensaryProductVariants.Select(v => new DispensaryProductVariantModel()
                    {
                        Id = v.Id,
                        IsMasterVariant = v.IsMasterVariant,
                        DisplayOrder = v.DisplayOrder,
                        Name = v.Name,
                        Photos = v.Photos.Select(p => new FileModel() { Id = p.Id }),
                        IsPricedByWeight = v.IsPricedByWeight,
                        VariantQuantity = v.VariantQuantity,
                        VariantPricingJSON = v.VariantPricing
                    }),
                Effects = item.Effects.Select(e => new EffectModel() { Id = e.Id, Name = e.Name }),
                Symptoms = item.Symptoms.Select(e => new SymptomModel() { Id = e.Id, Name = e.Name }),
                IsAvailable = item.IsAvailable,
                IsDiscounted = item.IsDiscounted,
                IsPopular = item.IsPopular,
                Slug = item.Slug,
                YouTubeVideoUrl = item.YouTubeVideoUrl
            }).ToList();

            foreach (DispensaryProductModel product in mappedlist)
            {
                foreach (DispensaryProductVariantModel variant in product.DispensaryProductVariants)
                {
                    variant.VariantPricing = Mapper.Map<List<VariantPricing>>(variant.VariantPricingJSON);
                }
            }

            GridModel<DispensaryProductModel> gritItems = new GridModel<DispensaryProductModel>()
            {
                aaData = mappedlist,
                iTotalDisplayRecords = count,
                iTotalRecords = count,
                sEcho = filter.sEcho
            };

            return Request.CreateResponse(HttpStatusCode.OK, gritItems);
        }
示例#58
0
        public Form1()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();
            //
            // TODO: Add any constructor code after InitializeComponent call
            //

            #region Style settings
            GridModel model = gridControl1.Model;
            model.Options.FloatCellsMode = GridFloatCellsMode.OnDemandCalculation;

            GridFontInfo boldFont = new GridFontInfo();
            boldFont.Bold      = true;
            boldFont.Size      = 10;
            boldFont.Underline = true;

            int rowIndex = 2;
            int colIndex = 1;

            gridControl1.Rows.DefaultSize += 2;
            int boldfontRowHeight = gridControl1.Rows.DefaultSize + 6;

            model.Options.ControllerOptions         = GridControllerOptions.All;
            model.Options.DataObjectConsumerOptions = GridDataObjectConsumerOptions.All;

            GridStyleInfo standard  = model.BaseStylesMap["Standard"].StyleInfo;
            GridStyleInfo header    = model.BaseStylesMap["Header"].StyleInfo;
            GridStyleInfo rowHeader = model.BaseStylesMap["Row Header"].StyleInfo;
            GridStyleInfo colHeader = model.BaseStylesMap["Column Header"].StyleInfo;

            header.Interior    = new BrushInfo(SystemColors.Control);
            rowHeader.Interior = new BrushInfo(SystemColors.Control);

            standard.Font.Facename     = "Segoe UI";
            standard.VerticalAlignment = GridVerticalAlignment.Middle;

            #endregion

            #region Number Formats
            model.CoveredRanges.Add(GridRangeInfo.Cells(rowIndex, 1, rowIndex, 2));
            model[rowIndex, 1].Text    = "Number Formats";
            model[rowIndex, 1].Font    = boldFont;
            model.RowHeights[rowIndex] = boldfontRowHeight;
            rowIndex++;

            colIndex = 1;
            rowIndex++;
            foreach (string format in new string[]
            {
                "0.00",
                "C",
                "0.00;(0.00)",
                "###0.##%",
                "#0.#E+00",
                "10:##,##0.#"
            })
            {
                model[rowIndex - 1, colIndex].Text      = format;
                model[rowIndex, colIndex].Format        = format;
                model[rowIndex, colIndex].CellValue     = Math.PI;
                model[rowIndex, colIndex].CellValueType = typeof(double);
                colIndex++;
            }
            #endregion

            #region Date Formats

            rowIndex++;
            rowIndex++;

            colIndex = 1;

            model.CoveredRanges.Add(GridRangeInfo.Cells(rowIndex, 1, rowIndex, 2));
            model[rowIndex, 1].Text    = "DateTime Formats";
            model[rowIndex, 1].Font    = boldFont;
            model.RowHeights[rowIndex] = boldfontRowHeight;
            rowIndex++;

            colIndex = 1;
            rowIndex++;
            foreach (string format in new string[]
            {
                "d",
                "D",
                "f",
                "dddd, dd MMMM yyyy",
                "t",
                "s"
            })
            {
                model[rowIndex - 1, colIndex].Text      = format;
                model[rowIndex, colIndex].Format        = format;
                model[rowIndex, colIndex].CellValue     = DateTime.Now;
                model[rowIndex, colIndex].CellValueType = typeof(DateTime);
                colIndex++;
            }

            rowIndex++;
            rowIndex++;
            #endregion

            #region Validation
            model.CoveredRanges.Add(GridRangeInfo.Cells(rowIndex, 1, rowIndex, 2));
            model[rowIndex, 1].Text    = "Validation";
            model[rowIndex, 1].Font    = boldFont;
            model.RowHeights[rowIndex] = boldfontRowHeight;
            rowIndex++;

            model[rowIndex, 1].Text = "Positive numbers";
            model.RowStyles[rowIndex].ValidateValue.NumberRequired = true;
            model.RowStyles[rowIndex].ValidateValue.Minimum        = 0;
            model.RowStyles[rowIndex].ValidateValue.Maximum        = float.NaN;
            model.RowStyles[rowIndex].ValidateValue.ErrorMessage   = "Please enter a number greater than 0!";
            rowIndex++;

            model[rowIndex, 1].Text = "Validation (1-100 valid range)";
            model.RowStyles[rowIndex].ValidateValue = new GridCellValidateValueInfo(true, 1, 100, "Please enter a number between 1 and 100!");
            rowIndex++;
            rowIndex++;

            model[rowIndex, 1].Text = "Validation (allow strings to be entered into cells with CellValueType = typeof(double)";
            rowIndex++;
            model.RowStyles[rowIndex].CellValueType   = typeof(double);
            model.RowStyles[rowIndex].CellValue       = 1;
            model.RowStyles[rowIndex].Format          = "C";
            model.RowStyles[rowIndex].StrictValueType = false;
            rowIndex++;
            rowIndex++;

            model[rowIndex, 1].Text = "Validation (do not allow strings to be entered)";
            rowIndex++;
            model.RowStyles[rowIndex].CellValueType   = typeof(double);
            model.RowStyles[rowIndex].CellValue       = 1;
            model.RowStyles[rowIndex].Format          = "C";
            model.RowStyles[rowIndex].StrictValueType = true;
            rowIndex++;
            rowIndex++;

            model[rowIndex, 1].Text = "Validation (change CellValueType when strings is entered)";
            rowIndex++;
            model.RowStyles[rowIndex].CellValueType = typeof(double);
            model.RowStyles[rowIndex].CellValue     = 1;
            model.RowStyles[rowIndex].Format        = "C";
            model.RowStyles[rowIndex].Tag           = "Custom";
            rowIndex++;
            rowIndex++;
            #endregion

            #region TableStyle
            model.RowHeights.ResizeToFit(GridRangeInfo.Rows(2, rowIndex));
            this.gridControl1.DefaultRowHeight       = 18;
            this.gridControl1.DefaultColWidth        = 70;
            this.gridControl1.DefaultGridBorderStyle = GridBorderStyle.Solid;
            this.gridControl1.Font = new System.Drawing.Font("Segoe UI", 8.5F);
            #endregion

            this.GridSettings();
        }
 public void Setup()
 {
     _model = new GridModel<Person>();
     _people = new List<Person> {new Person {Id = 1, Name = "Jeremy", DateOfBirth = new DateTime(1987, 4, 19)}};
     _viewEngine = MockRepository.GenerateMock<IViewEngine>();
     _engines = new ViewEngineCollection(new List<IViewEngine> { _viewEngine });
     _writer = new StringWriter();
 }
示例#60
0
 public PictureBoxCellModel(GridModel grid)
     : base(grid)
 {
     PictureBoxStyleProperties.Initialize();
 }