Example #1
0
 public void Init(Grid grid) {
     
     _grid = grid;
     _grid.OnClick.Subscribe(HandleGridClick);
     //_grid.OnKeyDown.Subscribe(handleGridKeyDown);
     
 }
        public static void init()
        {
            MultiSearchViewModel2013 vm = new MultiSearchViewModel2013();
           

            // Create Grids
            FetchQuerySettings[] searches = vm.Config.GetItems();
            jQueryObject searchResultsDiv = jQuery.Select("#searchResults");
            jQuery.Window.Resize(delegate(jQueryEvent e)
            {
                OnResizeSearchResults(searchResultsDiv);
            });
            OnResizeSearchResults(searchResultsDiv);
            jQuery.Select(".sparkle-xrm").Bind("onmousewheel mousewheel DOMMouseScroll", OnSearchResultsMouseScroll);
            
            int i = 0;
            foreach (FetchQuerySettings config in searches)
            {
                
                

                List<Column> cardColumn = new List<Column>(new Column(ColumnProperties.Id, "card-column", ColumnProperties.Options,config.Columns, ColumnProperties.Name, "Name", ColumnProperties.Width, 290, ColumnProperties.CssClass, "card-column-cell"));
               
                cardColumn[0].Formatter = RenderCardColumnCell;
                cardColumn[0].DataType = "PrimaryNameLookup";
                config.Columns[0].DataType = "PrimaryNameLookup"; // This is so that clicking on the column opens the record
                GridDataViewBinder dataViewBinder = new GridDataViewBinder();
                GridOptions gridOptions = new GridOptions();
                gridOptions.EnableCellNavigation = true;
                gridOptions.AutoEdit = false;
                gridOptions.Editable = false;
                gridOptions.EnableAddRow = false;
                // Set height to the number of columns
                int columns = config.Columns.Count;             
                gridOptions.RowHeight = (columns>3? 3 : columns) * 16; ;
                if (gridOptions.RowHeight < 70) gridOptions.RowHeight = 70;
                gridOptions.HeaderRowHeight = 0;
                
                string gridId = "grid" + i.ToString() + "container";
                DataViewBase dataView = config.DataView;

                Grid grid = new Grid("#" + gridId, dataView, cardColumn, gridOptions);
                grids[i] = grid;
                AddResizeEventHandlers(grid, gridId);
                dataViewBinder.DataBindEvents(grid, dataView, gridId);
                dataViewBinder.BindClickHandler(grid);
                i++;

              
            
        
            }
           
            
            // Data Bind
            ViewBase.RegisterViewModel(vm);

        }
Example #3
0
 public CrmPagerControl(DataViewBase dataView, Grid grid, jQueryObject container)
 {
     _dataView = dataView;
     _grid = grid;
     _container = container;
     jQuery.OnDocumentReady(delegate()
     {
         init();
     });
 }
Example #4
0
        private static void InitLocalisedContent()
        {
            Dictionary<string, string> entityTypes;
            string id;
            string logicalName;

            #if DEBUG
            id = "C489707F-B5E2-E411-80D5-080027846324";
            logicalName = "account";
            entityTypes = new Dictionary<string, string>();
            entityTypes["account"] = "name";
            entityTypes["contact"] = "fullname";
            entityTypes["opportunity"] = "name";
            #else
            entityTypes = PageEx.GetWebResourceData(); // The allowed lookup types for the connections - e.g. account, contact, opportunity. This must be passed as a data parameter to the webresource 'account=name&contact=fullname&opportunity=name
            id = ParentPage.Data.Entity.GetId();
            logicalName =  ParentPage.Data.Entity.GetEntityName();
            #endif
            EntityReference parent = new EntityReference(new Guid(id), logicalName, null);
            vm = new ConnectionsViewModel(parent, entityTypes);
            // Bind Connections grid
            GridDataViewBinder contactGridDataBinder = new GridDataViewBinder();
            List<Column> columns = GridDataViewBinder.ParseLayout(String.Format("{0},record1id,250,{1},record1roleid,250", ResourceStrings.ConnectTo, ResourceStrings.Role));

            // Role2Id Column
            XrmLookupEditor.BindColumn(columns[1], vm.RoleSearchCommand, "connectionroleid", "name", "");

            connectionsGrid = contactGridDataBinder.DataBindXrmGrid(vm.Connections, columns, "container", "pager", true, false);

            connectionsGrid.OnActiveCellChanged.Subscribe(delegate(EventData e, object data)
            {
                OnCellChangedEventData eventData = (OnCellChangedEventData)data;
                vm.SelectedConnection.SetValue((Connection)connectionsGrid.GetDataItem(eventData.Row));
            });

            // Let's not use a hover button because it get's n the way of the editable grid!
            //RowHoverPlugin rowButtons = new RowHoverPlugin("gridButtons");
            //connectionsGrid.RegisterPlugin(rowButtons);

            ViewBase.RegisterViewModel(vm);

            OverrideMetadata();

            jQuery.Window.Resize(OnResize);
            jQuery.OnDocumentReady(delegate()
            {
                OnResize(null);
                vm.Search();
            });
        }
Example #5
0
        public void Init(Grid grid)
        {
            _grid = grid;
            _hoverButtons = jQuery.Select("#" + _containerId);
            _hoverButtons.MouseEnter(delegate(jQueryEvent e)
            {
                // Stop the mouse out when hovering over the button
                _mouseOut = false;
            });
            jQuery.Select("#grid").Find(".slick-viewport").Append(_hoverButtons); ;


            ((Event)Script.Literal("{0}.onMouseEnter", _grid)).Subscribe(HandleMouseEnter);
            ((Event)Script.Literal("{0}.onMouseLeave", _grid)).Subscribe(HandleMouseLeave);

        }
        public static void SetUpGrids(ScheduledJobsEditorViewModel vm)
        {
         
            // Create Scheduled Jobs Grid
            GridDataViewBinder jobsDataBinder = new GridDataViewBinder();

            List<Column> jobCols = GridDataViewBinder.ParseLayout("dev1_name,Name,300,dev1_recurrancepattern,Pattern,300,createdon,Created On, 300");
            jobsGrid = jobsDataBinder.DataBindXrmGrid(vm.JobsViewModel, jobCols, "jobsGrid", "jobsGridPager",false,false);

            GridDataViewBinder bulkDeleteDataBinder = new GridDataViewBinder();
            List<Column> bulkDeleteCols = GridDataViewBinder.ParseLayout("name,Name,300,asyncoperation_statuscode,Status,100,asyncoperation_postponeuntil,Next Run,150,asyncoperation_recurrencepattern,Pattern,150,createdon,Created On,150");
            bulkDeleteJobsGrid = bulkDeleteDataBinder.DataBindXrmGrid(vm.bulkDeleteJobsViewModel,bulkDeleteCols, "bulkDeleteJobGrid", "bulkDeleteJobGridPager",false, false);

            // Load first page
            vm.JobsViewModel.Refresh();


        }
 private static void FreezeColumns(Grid grid, bool freeze)
 {
     // Columns are added initially with their max and min width the same so they are not stretched to fit the width
     // Now we restore column resizing
     Column[] cols = grid.GetColumns();
     for (int i = 0; i < cols.Length - 1; i++)
     {
         Column col = cols[i];
         if (freeze)
         {
             col.MaxWidth = col.Width;
             col.MinWidth = col.Width;
         }
         else
         {
             col.MaxWidth = null;
             col.MinWidth = null;
         }
     }
 }
        /// <summary>
        /// DataBinds a DataView that inherits from DataViewBase
        /// 
        /// </summary>
        /// <param name="dataView"></param>
        /// <param name="columns"></param>
        /// <param name="gridId"></param>
        /// <param name="pagerId"></param>
        /// <param name="editable"></param>
        /// <param name="allowAddNewRow"></param>
        /// <returns></returns>
        public Grid DataBindXrmGrid(DataViewBase dataView, List<Column> columns, string gridId, string pagerId,bool editable, bool allowAddNewRow )
        {
            // Always add an empty column on the end for reszing purposes
            ArrayEx.Add(columns, new Column());

            GridOptions gridOptions = new GridOptions();
            gridOptions.EnableCellNavigation = true;
            gridOptions.AutoEdit = editable;
            gridOptions.Editable = editable;
            gridOptions.EnableAddRow = allowAddNewRow;

            // Set non-variable options
            gridOptions.RowHeight = PageEx.MajorVersion==2013 ? 30 : 20;
            gridOptions.HeaderRowHeight = 25;
            //gridOptions.ForceFitColumns = true;
            gridOptions.EnableColumnReorder = false;

            CheckboxSelectColumnOptions checkboxOptions = new CheckboxSelectColumnOptions();
            checkboxOptions.cssClass = "sparkle-checkbox-column";

            // Add check box column
            CheckboxSelectColumn checkBoxSelector = new CheckboxSelectColumn(checkboxOptions);
            Column checkBoxColumn = checkBoxSelector.GetColumnDefinition();
            columns.Insert(0, checkBoxColumn);

            Grid grid = new Grid("#" + gridId, dataView, columns, gridOptions);

            grid.RegisterPlugin(checkBoxSelector);
            this.DataBindSelectionModel(grid, dataView);
            if (!string.IsNullOrEmpty(pagerId))
            {
                CrmPagerControl pager = new CrmPagerControl(dataView, grid, jQuery.Select("#" + pagerId));
            }
            DataBindEvents(grid, dataView, gridId);
            AddValidation(grid, dataView);
            AddRefreshButton(gridId, dataView);

            // Add resize event
            jQuery.Window.Resize(delegate(jQueryEvent e){
                // Set each column to be non resizable while we do the resize
                FreezeColumns(grid, true);
                grid.ResizeCanvas();
                // Restore the resizing
                FreezeColumns(grid, false);
            });

            dataView.OnDataLoaded.Subscribe(delegate(EventData e, object o)
            {
                FreezeColumns(grid,false);
            });
            _grid = grid;
            return grid;
        }
        public void DataBindSelectionModel(Grid grid, DataViewBase dataView)
        {
            // Set up selection model if needed
            // Create selection model

            RowSelectionModelOptions selectionModelOptions = new RowSelectionModelOptions();
            selectionModelOptions.SelectActiveRow = true;
            RowSelectionModel selectionModel = new RowSelectionModel(selectionModelOptions);

            // Bind two way sync of selected rows
            // NOTE: the row index on the grid is not the row index in the data view due to paging
            bool inHandler = false;
            selectionModel.OnSelectedRangesChanged.Subscribe(delegate(EventData e, object args)
            {
                if (inHandler)
                    return;
                inHandler = true;
                dataView.RaiseOnSelectedRowsChanged((SelectedRange[])args);
                inHandler = false;
            });
            dataView.OnSelectedRowsChanged+=delegate()
            {
                if (inHandler)
                    return;
                inHandler = true;
                SelectedRange[] ranges = dataView.GetSelectedRows();
                int[] selectedRows = new int[ranges.Length];
                for (int i=0;i<selectedRows.Length;i++)
                {
                    selectedRows[i] = ranges[i].FromRow.Value;
                }

                grid.SetSelectedRows(selectedRows);

                inHandler = false;
            };
            grid.SetSelectionModel(selectionModel);
        }
        public void DataBindEvents(Grid grid,DataViewBase dataView,string gridContainerDivId)
        {
            // Data Sorting
            grid.OnSort.Subscribe(delegate(EventData o, Object item)
            {
                SortColData sorting = (SortColData)item;
                dataView.Sort(sorting);
                grid.Invalidate();
                grid.Render();

            });

            // Session Grid DataBinding
            grid.OnAddNewRow.Subscribe(delegate(EventData o, Object item)
            {
                EditEventData data = (EditEventData)item;
                dataView.AddItem(data.item);

                Column column = data.column;
                grid.InvalidateRow(dataView.GetLength() - 1);

                grid.UpdateRowCount();
                grid.Render();

            });

            dataView.OnRowsChanged.Subscribe(delegate(EventData e, object a)
            {

                OnRowsChangedEventArgs args = (OnRowsChangedEventArgs)a;
                if (args != null && args.Rows != null)
                {
                    grid.InvalidateRows(args.Rows);
                    grid.Render();
                }
                else
                {
                    // Assume that a new row has been added
                    grid.InvalidateRow(dataView.GetLength());
                    grid.UpdateRowCount();
                    grid.Render();
                }

            });

            jQueryObject loadingIndicator = null;

            // Wire up the validation error
            jQueryObject validationIndicator = null;
            Action<EventData, object> clearValidationIndicator = delegate(EventData e, object a)
            {
                if (validationIndicator != null)
                {
                    validationIndicator.Hide();
                    validationIndicator.Remove();
                }
            };

            grid.OnCellChange.Subscribe(clearValidationIndicator);
            grid.OnActiveCellChanged.Subscribe(clearValidationIndicator);
            grid.OnBeforeCellEditorDestroy.Subscribe(clearValidationIndicator);

            grid.OnValidationError.Subscribe(delegate(EventData e, object a)
            {
                ValidationEventArgs args = (ValidationEventArgs)a;
                ValidationResult validationResult = (ValidationResult)args.ValidationResults;
                jQueryObject activeCellNode = (jQueryObject)args.CellNode;
                object editor = args.Editor;
                string errorMessage = "";
                if (validationResult.Message != null)
                    errorMessage = validationResult.Message;
                bool valid_result = validationResult.Valid;

                // Add the message to the tooltip on the cell
                if (!valid_result)
                {
                    jQuery.FromObject(activeCellNode).Attribute("title", errorMessage);
                    clearValidationIndicator(e,a);
                    validationIndicator = jQuery.FromHtml("<div class='popup-box-container'><div width='16px' height='16px' class='sparkle-imagestrip-inlineedit_warning popup-box-icon' alt='Error' id='icon'/><div class='popup-box validation-text'/></div>").AppendTo(Document.Body);
                    validationIndicator.Find(".validation-text").Text(errorMessage);

                    Script.Literal(@"{0}.position({{
                                            my: 'left bottom',
                                            at: 'left top',
                                            collision: 'fit fit',
                                            of: {1}
                                        }})
                                        .show({{
                                        effect: 'blind'
                                        }})
                                        .delay( 500000 )
                                        .hide({{
                                            effect: 'fade',
                                            duration: 'slow',
                                        }},
                                            function() {{
                                                $( this ).remove();

                                            }});
                                        ", validationIndicator, activeCellNode);

                }
                else
                {
                    clearValidationIndicator(e, a);
                    jQuery.FromObject(activeCellNode).Attribute("title", "");
                }
            });

            // Wire up the loading spinner
            dataView.OnDataLoading.Subscribe(delegate(EventData e, object a)
            {

                loadingIndicator = ShowLoadingIndicator(loadingIndicator, gridContainerDivId);
                foreach (Column col in grid.GetColumns())
                {
                    if (col.MaxWidth != null)
                        col.MaxWidth = 400;
                }

            });

            dataView.OnDataLoaded.Subscribe(delegate(EventData e, object a)
            {

                DataLoadedNotifyEventArgs args = (DataLoadedNotifyEventArgs)a;
                if (args.ErrorMessage == null)
                {
                    for (int i = args.From; i <= args.To; i++)
                    {
                        grid.InvalidateRow(i);
                    }
                    grid.UpdateRowCount();
                    grid.Render();
                }
                else
                    Script.Alert("There was a problem refreshing the grid.\nPlease contact your system administrator:\n" + args.ErrorMessage);

                if (loadingIndicator != null)
                    loadingIndicator.Plugin<jQueryBlockUI>().Unblock();
            });

            // Wire up edit complete to property changed
            grid.OnCellChange.Subscribe(delegate(EventData e, object data)
            {
                OnCellChangedEventData eventData = (OnCellChangedEventData)data;
                dataView.RaisePropertyChanged("");

            });
        }
        /// <summary>
        /// Data Binds the standard Slick.DataView
        /// </summary>
        /// <param name="columns"></param>
        /// <param name="dataView"></param>
        /// <returns></returns>
        public Grid DataBindDataViewGrid(DataView dataView, List<Column> columns, string gridId, string pagerId, bool editable, bool allowAddNewRow)
        {
            // Always add an empty column on the end for reszing purposes
            ArrayEx.Add(columns, new Column());

            GridOptions gridOptions = new GridOptions();
            gridOptions.EnableCellNavigation = true;
            gridOptions.AutoEdit = editable;
            gridOptions.Editable = editable;
            gridOptions.EnableAddRow = allowAddNewRow;

            // Set non-variable options
            gridOptions.RowHeight = 20;
            gridOptions.HeaderRowHeight = 25;
            gridOptions.EnableColumnReorder = false;

            CheckboxSelectColumnOptions checkboxOptions = new CheckboxSelectColumnOptions();
            checkboxOptions.cssClass = "sparkle-checkbox-column";

            // Add check box column
            CheckboxSelectColumn checkBoxSelector = new CheckboxSelectColumn(checkboxOptions);
            Column checkBoxColumn = checkBoxSelector.GetColumnDefinition();
            columns.Insert(0, checkBoxColumn);

            Grid grid = new Grid("#" + gridId, dataView, columns, gridOptions);

            grid.RegisterPlugin(checkBoxSelector);

            dataView.OnRowsChanged.Subscribe(delegate(EventData e, object a)
            {
                // Only invalided the rows that have changed
                OnRowsChangedEventArgs args = (OnRowsChangedEventArgs)a;
                if (args != null && args.Rows != null)
                {
                    grid.InvalidateRows(args.Rows);
                    grid.Render();
                }
            });

            //AddValidation(grid, dataView);

            // Add resize event
            jQuery.Window.Resize(delegate(jQueryEvent e)
            {
                // Set each column to be non resizable while we do the resize
                GridDataViewBinder.FreezeColumns(grid, true);
                grid.ResizeCanvas();
                // Restore the resizing
                GridDataViewBinder.FreezeColumns(grid, false);
            });

            // Add Reset binding
            Action reset = delegate() { };

            Script.Literal("{0}.reset={1}", dataView, reset);

            // Add Refresh button
            AddRefreshButton(gridId, (DataViewBase)(object)dataView);

            // Add Selection Model
            RowSelectionModelOptions selectionModelOptions = new RowSelectionModelOptions();
            selectionModelOptions.SelectActiveRow = true;
            RowSelectionModel selectionModel = new RowSelectionModel(selectionModelOptions);
            grid.SetSelectionModel(selectionModel);

            // Set sorting
            Action<EventData,object> onSort = delegate (EventData e, object a)
            {
                SortColData args = (SortColData)a;
                //SortDir = args.SortAsc ? 1 : -1;
                _sortColumnName = args.SortCol.Field;
                dataView.Sort(Comparer, args.SortAsc);
            };
            grid.OnSort.Subscribe(onSort);

            return grid;
        }
        /// <summary>
        /// Binds the click handler for opening records from the grid attributes -see the formatters for attributes provided
        /// </summary>
        /// <param name="grid"></param>
        public void BindClickHandler(Grid grid)
        {
            Action<string, string> openEntityRecord = delegate(string logicalName, string id)
            {
                Utility.OpenEntityForm(logicalName, id, null);
            };
            grid.OnClick.Subscribe(delegate(EventData e, object sender)
            {
                CellSelection cell = (CellSelection)sender;

                bool handled = false;
                Element element = e.SrcElement;
                object logicalName = element.GetAttribute("logicalName");
                object id = element.GetAttribute("id");
                object primaryNameLookup = element.GetAttribute("primaryNameLookup");
                if (logicalName != null & id != null)
                {
                    // Open the related record
                    handled = true;

                }
                else if (primaryNameLookup != null)
                {
                    // Open the primary entity record
                    handled = true;
                    Entity entity = (Entity)cell.Grid.GetDataItem(cell.Row.Value);
                    logicalName = entity.LogicalName;
                    // If there is an activitytypecode then use that
                    string activitytypecode = entity.GetAttributeValueString("activitytypecode");
                    if (activitytypecode != null)
                        logicalName = activitytypecode;
                    id = entity.Id;
                }

                if (handled)
                {
                    openEntityRecord((string)logicalName, (string)id);
                    e.StopImmediatePropagation();
                    e.StopPropagation();
                }

            });
            grid.OnDblClick.Subscribe(delegate(EventData e, object sender)
            {

                CellSelection cell = (CellSelection)sender;
                Entity entity = (Entity)cell.Grid.GetDataItem(cell.Row.Value);
                string logicalName = entity.LogicalName;
                // If there is an activitytypecode then use that
                string activitytypecode = entity.GetAttributeValueString("activitytypecode");
                if (activitytypecode != null)
                    logicalName = activitytypecode;
                openEntityRecord(logicalName, entity.Id);
                e.StopImmediatePropagation();
                e.StopPropagation();
            });
        }
Example #13
0
        private static void InitLocalisedContent()
        {
            
            Dictionary<string, string> parameters;
            string id;
            string logicalName;
            int pageSize = 10;
            string defaultView=null;            

#if DEBUG
            id = "C489707F-B5E2-E411-80D5-080027846324";
            logicalName = "account";
            parameters = new Dictionary<string, string>();         
           
#else
            parameters = PageEx.GetWebResourceData(); // The allowed lookup types for the connections - e.g. account, contact, opportunity. This must be passed as a data parameter to the webresource 'account=name&contact=fullname&opportunity=name
            id = ParentPage.Data.Entity.GetId();  
            logicalName =  ParentPage.Data.Entity.GetEntityName();
            ParentPage.Data.Entity.AddOnSave(CheckForSaved);
#endif
            EntityReference parent = new EntityReference(new Guid(id), logicalName, null);
            string entities = "account,contact,opportunity,systemuser";
            foreach (string key in parameters.Keys)
            {
                switch (key.ToLowerCase())
                {
                    case "entities":
                        entities = parameters[key];
                        break;
                    case "pageSize":
                        pageSize = int.Parse(parameters[key]);
                        break;
                    case "view":
                        defaultView = parameters[key];
                        break;
                    case "category":
                        category = int.Parse(parameters[key]);
                        break;
                }
            }
           
            // Get the view
            QueryParser queryParser = new QueryParser(new string[] {"connection"});
            queryParser.GetView("connection", defaultView);
            queryParser.QueryMetadata();
            EntityQuery connectionViews = queryParser.EntityLookup["connection"];
            string viewName = connectionViews.Views.Keys[0];
            FetchQuerySettings view = connectionViews.Views[viewName];

            vm = new ConnectionsViewModel(parent, entities.Split(","), pageSize, view);
            
            // Bind Connections grid
            GridDataViewBinder connectionsGridDataBinder = new GridDataViewBinder();
            List<Column> columns = view.Columns;

            // Role2Id Column - provided it is in the view!
            foreach (Column col in columns)
            {
                switch (col.Field)
                {
                    case "record2roleid":
                        XrmLookupEditor.BindColumn(col, vm.RoleSearchCommand, "connectionroleid", "name,category", "");
                        break;
                    case "description":
                        XrmTextEditor.BindColumn(col);
                        break;
                    case "effectivestart":
                    case "effectiveend":
                        XrmDateEditor.BindColumn(col, true);
                        break;
                }
            }
           

            connectionsGrid = connectionsGridDataBinder.DataBindXrmGrid(vm.Connections, columns, "container", "pager", true, false);

            connectionsGrid.OnActiveCellChanged.Subscribe(delegate(EventData e, object data)
            {
                OnCellChangedEventData eventData = (OnCellChangedEventData)data;
                vm.SelectedConnection.SetValue((Connection)connectionsGrid.GetDataItem(eventData.Row));
            });

            connectionsGridDataBinder.BindClickHandler(connectionsGrid);
            // Let's not use a hover button because it get's in the way of the editable grid!
            //RowHoverPlugin rowButtons = new RowHoverPlugin("gridButtons");
            //connectionsGrid.RegisterPlugin(rowButtons);

            ViewBase.RegisterViewModel(vm);

            OverrideMetadata();

            jQuery.Window.Resize(OnResize);
            jQuery.OnDocumentReady(delegate()
            {
                OnResize(null);
                vm.Search();
            });
        }
 private static void AddResizeEventHandlers(Grid grid,string containerName)
 {
     // Add resize height event
     jQuery.Window.Resize(delegate(jQueryEvent e)
     {
         ResizeGrid(grid, containerName);
     });
     jQuery.OnDocumentReady(delegate()
     {
         ResizeGrid(grid, containerName);
     });
 }
Example #15
0
 private static void AddResizeEventHandlers(Grid grid,string containerName)
 {
     // Add resize height event
     jQuery.Window.Resize(delegate(jQueryEvent e)
     {
         ResizeGrid(grid, containerName);
     });
     jQuery.OnDocumentReady(delegate()
     {
         ResizeGrid(grid, containerName);
     });
     //jQuery.Select("#" + containerName).Bind("onmousewheel mousewheel DOMMouseScroll", OnGridMouseScroll);
 }
Example #16
0
        public static void SetUpGrids(TimeSheetViewModel vm)
        {
            GridOptions daysGridOpts = new GridOptions();
            daysGridOpts.EnableCellNavigation = true;
            daysGridOpts.EnableColumnReorder = false;
            daysGridOpts.AutoEdit = false;
            daysGridOpts.Editable = true;
            daysGridOpts.RowHeight = 20;
            daysGridOpts.HeaderRowHeight = 25;
            daysGridOpts.ForceFitColumns = false;
            daysGridOpts.EnableAddRow = true;

            // Create Timesheet Grid
            DataViewBase daysDataView = vm.Days;

            List<Column> columns = new List<Column>();
            GridDataViewBinder.BindRowIcon(GridDataViewBinder.AddColumn(columns, "", 50, "icon"), "activity");
            XrmLookupEditor.BindColumn(GridDataViewBinder.AddColumn(columns, "Activity", 300, "activity"), vm.ActivitySearchCommand, "activityid", "subject", "activitytypecode");

            GridDataViewBinder.AddColumn(columns, "Mon", 50, "day0");
            GridDataViewBinder.AddColumn(columns, "Tue", 50, "day1");
            GridDataViewBinder.AddColumn(columns, "Wed", 50, "day2");
            GridDataViewBinder.AddColumn(columns, "Thu", 50, "day3");
            GridDataViewBinder.AddColumn(columns, "Fri", 50, "day4");
            GridDataViewBinder.AddColumn(columns, "Sat", 50, "day5");
            GridDataViewBinder.AddColumn(columns, "Sun", 50, "day6");

            daysGrid = new Grid("#timesheetGridContainer", daysDataView, columns, daysGridOpts);

            GridDataViewBinder daysDataBinder = new GridDataViewBinder();
            daysDataBinder.DataBindEvents(daysGrid, daysDataView, "timesheetGridContainer");

            // Set the totals row meta data
            daysDataView.OnGetItemMetaData += delegate(object item)
            {
                DayEntry day = (DayEntry)item;
                if (day != null && day.isTotalRow)
                {
                    ItemMetaData metaData = new ItemMetaData();
                    metaData.Editor = null;
                    metaData.Formatter = delegate(int row, int cell, object value, Column columnDef, object dataContext)
                    {
                        if (columnDef.Field == "activity")
                            return "Total";
                        else
                            return Formatters.DefaultFormatter(row, cell, value, columnDef, dataContext);
                    };
                    metaData.CssClasses = "days_total_row";
                    return metaData;
                }

                else
                    return null;
            };

            daysDataBinder.DataBindSelectionModel(daysGrid, daysDataView);

            // ---------------------------------------
            // Sessions Grid
            // ---------------------------------------
            DataViewBase sessionsDataView = vm.SessionDataView;

            List<Column> sessionGridCols = new List<Column>();

            GridDataViewBinder.AddEditIndicatorColumn(sessionGridCols);

            XrmTextEditor.BindColumn(GridDataViewBinder.AddColumn(sessionGridCols, "Description", 200, "dev1_description"));

            XrmDateEditor.BindColumn(GridDataViewBinder.AddColumn(sessionGridCols, "Date", 200, "dev1_starttime"), true);

            XrmTimeEditor.BindColumn(GridDataViewBinder.AddColumn(sessionGridCols, "Start", 100, "dev1_starttime")).Validator =
                delegate(object value, object item)
                {
                    dev1_session session = (dev1_session)item;
                    DateTime newStartTime = (DateTime)value;
                    ValidationResult result = new ValidationResult();

                    if (session.dev1_EndTime != null)
                    {

                        result.Valid = true;
                        string valueText = (string)value;
                        // Check if the end time is before the start time

                        bool isValid = DateTimeEx.GetTimeDuration(newStartTime) < DateTimeEx.GetTimeDuration(session.dev1_EndTime);

                        result.Valid = isValid;
                        result.Message = "The start time must be before the end time";

                    }
                    else
                        result.Valid = true;
                    return result;

                };

            XrmTimeEditor.BindColumn(GridDataViewBinder.AddColumn(sessionGridCols, "End", 100, "dev1_endtime")).Validator =
                delegate(object value, object item)
                {
                    dev1_session session = (dev1_session)item;
                    DateTime newEndTime = (DateTime)value;

                    ValidationResult result = new ValidationResult();

                    if (session.dev1_StartTime != null)
                    {
                        result.Valid = true;
                        string valueText = (string)value;
                        // Check if the end time is before the start time

                        bool isValid = DateTimeEx.GetTimeDuration(session.dev1_StartTime) < DateTimeEx.GetTimeDuration(newEndTime);

                        result.Valid = isValid;
                        result.Message = "The end time must be after the start time";
                    }
                    else
                        result.Valid = true;

                    return result;

                };

            XrmDurationEditor.BindColumn(GridDataViewBinder.AddColumn(sessionGridCols, "Duration", 200, "dev1_duration"));

            GridDataViewBinder sessionsDataBinder = new GridDataViewBinder();
            sessionsGrid = sessionsDataBinder.DataBindXrmGrid(sessionsDataView, sessionGridCols, "sessionsGridContainer", null, true, true);
            sessionsDataBinder.DataBindSelectionModel(sessionsGrid, sessionsDataView);

            daysGrid.OnActiveCellChanged.Subscribe(delegate(EventData e, object args)
            {
                CellSelection activeCell = daysGrid.GetActiveCell();
                if (activeCell != null)
                {
                    if (activeCell.Cell < 2)
                    {
                        // Whole activity is selected
                        vm.Days.SelectedDay = null;

                    }
                    else
                    {
                        vm.Days.SelectedDay = activeCell.Cell - 1;

                    }
                }
            });
        }
Example #17
0
        public static void SetUpGrids(TimeSheetViewModel vm)
        {
           
            // Create Timesheet Grid
            DataViewBase daysDataView = vm.Days;

            List<Column> columns = new List<Column>();
            GridDataViewBinder.BindRowIcon(GridDataViewBinder.AddColumn(columns, "", 50, "icon"), "activity");
            XrmLookupEditor.BindColumn(GridDataViewBinder.AddColumn(columns, "Account", 300, "account"), vm.AccountSeachCommand, "accountid", "name", null);
            XrmLookupEditor.BindColumn(GridDataViewBinder.AddColumn(columns, "Regarding", 300, "regardingObjectId"), vm.RegardingObjectSearchCommand, "id", "displayName", null);
            XrmLookupEditor.BindColumn(GridDataViewBinder.AddColumn(columns, "Activity", 300, "activity"), vm.ActivitySearchCommand, "activityid", "subject", "activitytypecode");

            string[] daysOfWeek = new string[] { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat","Sun","Mon","Tue","Wed","Thu","Fri","Sat" };
            int firstDayOfWeek = OrganizationServiceProxy.OrganizationSettings.WeekStartDayCode.Value.Value;

            GridDataViewBinder.AddColumn(columns, daysOfWeek[firstDayOfWeek], 50, "day0");
            GridDataViewBinder.AddColumn(columns, daysOfWeek[firstDayOfWeek + 1], 50, "day1");
            GridDataViewBinder.AddColumn(columns, daysOfWeek[firstDayOfWeek + 2], 50, "day2");
            GridDataViewBinder.AddColumn(columns, daysOfWeek[firstDayOfWeek + 3], 50, "day3");
            GridDataViewBinder.AddColumn(columns, daysOfWeek[firstDayOfWeek + 4], 50, "day4");
            GridDataViewBinder.AddColumn(columns, daysOfWeek[firstDayOfWeek + 5], 50, "day5");
            GridDataViewBinder.AddColumn(columns, daysOfWeek[firstDayOfWeek + 6], 50, "day6");

            GridDataViewBinder daysDataBinder = new GridDataViewBinder();
            daysDataBinder.SelectActiveRow = true;
            daysDataBinder.AddCheckBoxSelectColumn = false;
            daysGrid = daysDataBinder.DataBindXrmGrid(daysDataView, columns, "timesheetGridContainer", null, true, true);

            // Set the totals row meta data
            daysDataView.OnGetItemMetaData += delegate(object item)
            {
                ItemMetaData metaData = new ItemMetaData();
                DayEntry day = (DayEntry)item;
                if (day != null && day.isTotalRow)
                {

                    metaData.Editor = delegate(EditorArguments args) { return null; };
                    metaData.Columns = new Dictionary<object, Column>();
                    metaData.Columns["Account"] = new Column("editor", null);
                    metaData.Columns["Regarding"] = new Column("editor", null);
                    metaData.Columns["Activity"] = new Column("editor", null);
                    metaData.Formatter = delegate(int row, int cell, object value, Column columnDef, object dataContext)
                    {
                        switch (columnDef.Field)
                        {
                            case "account":
                            case "regardingObjectId":
                                return "";
                            case "activity":
                                return "Total";
                            default:
                                return XrmDurationEditor.Formatter(row, cell, value, columnDef, dataContext);
                        }
                       
                    };
                           
                    metaData.CssClasses = "days_total_row";
                   
                }

                else
                {
                    metaData.Formatter = delegate(int row, int cell, object value, Column columnDef, object dataContext)
                    {
                        switch (columnDef.Field)
                        {
                            case "account":
                            case "regardingObjectId":
                            case "activity":
                                return XrmLookupEditor.Formatter(row, cell, value, columnDef, dataContext);
                            default:
                                return XrmDurationEditor.Formatter(row, cell, value, columnDef, dataContext);
                        }
                    };

                }

                return metaData;
            };
          
            daysDataBinder.DataBindSelectionModel(daysGrid, daysDataView);


            // ---------------------------------------
            // Sessions Grid
            // ---------------------------------------
            DataViewBase sessionsDataView = vm.SessionDataView;

            List<Column> sessionGridCols = new List<Column>();

            GridDataViewBinder.AddEditIndicatorColumn(sessionGridCols);

            XrmTextEditor.BindColumn(GridDataViewBinder.AddColumn(sessionGridCols, "Activity", 300, "activitypointer_subject")).Editor = null;

           

            XrmDateEditor.BindColumn(GridDataViewBinder.AddColumn(sessionGridCols, "Date", 100, "dev1_starttime"), true);

            XrmTimeEditor.BindColumn(GridDataViewBinder.AddColumn(sessionGridCols, "Start", 100, "dev1_starttime")).Validator =
                delegate(object value, object item)
                {
                    dev1_session session = (dev1_session)item;
                    DateTime newStartTime = (DateTime)value;
                    ValidationResult result = new ValidationResult();

                    if (session.dev1_EndTime != null)
                    {

                        result.Valid = true;
                        string valueText = (string)value;
                        // Check if the end time is before the start time

                        bool isValid = DateTimeEx.GetTimeDuration(newStartTime) < DateTimeEx.GetTimeDuration(session.dev1_EndTime);

                        result.Valid = isValid;
                        result.Message = "The start time must be before the end time";

                    }
                    else
                        result.Valid = true;
                    return result;


                };

            XrmTimeEditor.BindColumn(GridDataViewBinder.AddColumn(sessionGridCols, "End", 100, "dev1_endtime")).Validator =
                delegate(object value, object item)
                {
                    dev1_session session = (dev1_session)item;
                    DateTime newEndTime = (DateTime)value;

                    ValidationResult result = new ValidationResult();

                    if (session.dev1_StartTime != null)
                    {
                        result.Valid = true;
                        string valueText = (string)value;
                        // Check if the end time is before the start time

                        bool isValid = DateTimeEx.GetTimeDuration(session.dev1_StartTime) < DateTimeEx.GetTimeDuration(newEndTime);

                        result.Valid = isValid;
                        result.Message = "The end time must be after the start time";
                    }
                    else
                        result.Valid = true;

                    return result;

                };


            XrmDurationEditor.BindColumn(GridDataViewBinder.AddColumn(sessionGridCols, "Duration", 70, "dev1_duration"));
            XrmTextEditor.BindColumn(GridDataViewBinder.AddColumn(sessionGridCols, "Description", 300, "dev1_description"));


            GridDataViewBinder sessionsDataBinder = new GridDataViewBinder();
            sessionsDataBinder.SelectActiveRow = false;
            sessionsDataBinder.AddCheckBoxSelectColumn = true;

            sessionsGrid = sessionsDataBinder.DataBindXrmGrid(sessionsDataView, sessionGridCols, "sessionsGridContainer", null, true, true);
            
            sessionsGrid.OnBeforeEditCell.Subscribe(delegate(EventData e, object args)
            {
             
                // Stop the row from being edited if locked
                Entity item = (Entity)((EditEventData)args).item;
                bool result = sessionsDataView.OnBeforeEdit(item);
                Script.Literal("return {0}", result);
                

            });

            daysGrid.OnActiveCellChanged.Subscribe(delegate(EventData e, object args)
            {
                CellSelection activeCell = daysGrid.GetActiveCell();
                if (activeCell != null)
                {
                    if (activeCell.Cell < StartDaysColumnIndex)
                    {
                        // Whole activity is selected
                        vm.Days.SelectedDay = null;

                    }
                    else
                    {
                        vm.Days.SelectedDay = activeCell.Cell - (StartDaysColumnIndex-1);

                    }
                }
            });




        }
 private static void ResizeGrid(Grid grid,string containerName)
 {
     // Change the height
     int height = jQuery.Window.GetHeight();
     jQuery.Select("#" + containerName).Height(height - 60);
     grid.ResizeCanvas();
 }
Example #19
0
        public void DataBindSelectionModel(Grid grid, DataViewBase dataView)
        {
            // Set up selection model if needed
            // Create selection model

            RowSelectionModelOptions selectionModelOptions = new RowSelectionModelOptions();
            selectionModelOptions.SelectActiveRow = SelectActiveRow;
            selectionModelOptions.MultiRowSelect = this.MultiSelect;
            RowSelectionModel selectionModel = new RowSelectionModel(selectionModelOptions);

            // Bind two way sync of selected rows
            // NOTE: the row index on the grid is not the row index in the data view due to paging
            bool inHandler = false;
            selectionModel.OnSelectedRangesChanged.Subscribe(delegate(EventData e, object args)
            {
                //if (grid.GetEditorLock().IsActive())
                //{
                //    e.StopPropagation();
                //    return;
                //}
                if (inHandler)
                    return;
                inHandler = true;
                // Has the selected row changeD?
                SelectedRange[] selectedRows = dataView.GetSelectedRows();
                SelectedRange[] newSelectedRows = (SelectedRange[])args;
                bool changed = selectedRows.Length!=newSelectedRows.Length;
                if (!changed)
                {
                    // Compare the actual selected rows
                    for (int i = 0; i < selectedRows.Length; i++)
                    {
                        if (selectedRows[i].FromRow!=newSelectedRows[i].FromRow)
                        {
                            changed = true;
                            break;
                        }
                    }

                }

                if (changed)
                {
                    dataView.RaiseOnSelectedRowsChanged(newSelectedRows);
                }
                inHandler = false;
            });
            dataView.OnSelectedRowsChanged+=delegate()
            {
                //if (grid.GetEditorLock().IsActive())
                //    return;
                if (inHandler)
                    return;
                inHandler = true;
                SelectedRange[] ranges = dataView.GetSelectedRows();
                int[] selectedRows = new int[ranges.Length];
                for (int i=0;i<selectedRows.Length;i++)
                {
                    selectedRows[i] = ranges[i].FromRow.Value;
                }

                grid.SetSelectedRows(selectedRows);

                inHandler = false;
            };
            grid.SetSelectionModel(selectionModel);
        }
 public void Init(Grid grid)
 {
     
 }
        public void AddValidation(Grid grid, DataViewBase dataView)
        {
            Action<string, Column> setValidator = delegate(string attributeName, Column col)
            {
                col.Validator = delegate(object value, object item)
                {
                    Func<string,GridValidatorDelegate> indexer = dataView.GridValidationIndexer();
                    GridValidatorDelegate validationRule = indexer(attributeName);
                    if (validationRule != null)
                        return validationRule(value, item);
                    else
                    {
                        ValidationResult result = new ValidationResult();
                        result.Valid = true;
                        return result;
                    }
                };
            };

            if (dataView.GridValidationIndexer() != null)
            {
                foreach (Column col in grid.GetColumns())
                {
                    string fieldName = col.Field;
                    setValidator(fieldName, col);
                }
            }
        }