public static Column AddColumn(List <Column> cols, string displayName, int width, string field) { Column col = NewColumn(field, displayName, width); ArrayEx.Add(cols, col); return(col); }
/// <summary> /// Formats a duration in minutes to a string /// </summary> /// <param name="hours"></param> /// <param name="minutes"></param> /// <returns></returns> public static string FormatDuration(int?totalMinutes) { if (totalMinutes != null) { int?toatalSeconds = totalMinutes * 60; int? days = Math.Floor(toatalSeconds / 86400); int? hours = Math.Floor((toatalSeconds % 86400) / 3600); int? minutes = Math.Floor(((toatalSeconds % 86400) % 3600) / 60); int? seconds = ((toatalSeconds % 86400) % 3600) % 60; List <string> formatString = new List <string>(); if (days > 0) { ArrayEx.Add(formatString, "{0}d"); } if (hours > 0) { ArrayEx.Add(formatString, "{1}h"); } if (minutes > 0) { ArrayEx.Add(formatString, "{2}m"); } return(String.Format(ArrayEx.Join((Array)formatString, " "), days, hours, minutes)); } else { return(""); } }
public bool Add(T item) { if (Bound.Contains(item.Position)) { if (m_childs.Length == 0) { if (Depth < MaxDepth) { Subdivide(); } else { item.Node = this; ArrayEx.Add(ref m_items, ref m_items_size, item); return(true); } } for (int index = 0; index < m_childs.Length; index++) { if (m_childs[index].Add(item)) { return(true); } } } return(Parent?.Add(item) ?? false); }
public T AddManager <T>() where T : BaseManager { var manager = New <T> .Create(); ArrayEx.Add(ref m_managers, ref m_managers_size, manager); return(manager); }
private void PulseWithCallbacks() { _pulseSource->Pulse(); if (_insertIdx >= _callbackQueue.Length || _callbackQueue[_insertIdx] != _callbacks) { _insertIdx = _callbackQueue.Length; _callbackQueue.Add(_callbacks); } }
public void AddComponent <T>(T component) where T : ObjectComponent { if (_initialized) { throw new NotImplementedException(); } ArrayEx.Add(ref _components, ref _componentsLength, component); }
private void DeleteBulkDeleteJobs(Guid scheduledJobId, Action callback) { IsBusyMessage.SetValue("Deleting existing schedule..."); // Get each bulk delete using the name = Scheduled Job {xxxx} string fetchXml = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" + "<entity name='bulkdeleteoperation'>" + "<attribute name='name' />" + "<attribute name='asyncoperationid' />" + "<link-entity name='asyncoperation' alias='a0' to='asyncoperationid' from='asyncoperationid'>" + "<attribute name='statecode' alias='asyncoperation_statecode'/>" + "<attribute name='statuscode' alias='asyncoperation_statuscode'/>" + "</link-entity>" + "<filter type='and'>" + "<condition attribute='name' operator='like' value='%" + scheduledJobId.ToString() + "%' />" + "</filter>" + "</entity>" + "</fetch>"; OrganizationServiceProxy.BeginRetrieveMultiple(fetchXml, delegate(object fetchJobsResponse) { try { // For each item, delete EntityCollection jobs = OrganizationServiceProxy.EndRetrieveMultiple(fetchJobsResponse, typeof(BulkDeleteOperation)); List <PendingDelete> deleteItems = new List <PendingDelete>(); IsBusyProgress.SetValue(0); foreach (BulkDeleteOperation item in jobs.Entities) { // First delete the job PendingDelete deleteJobOperationRequest = new PendingDelete(); deleteJobOperationRequest.entityName = BulkDeleteOperation.EntityLogicalName; deleteJobOperationRequest.id = item.BulkDeleteOperationId; ArrayEx.Add(deleteItems, deleteJobOperationRequest); // then the async operation PendingDelete deleteAsyncOperationRequest = new PendingDelete(); deleteAsyncOperationRequest.entityName = asyncoperation.EntityLogicalName; deleteAsyncOperationRequest.id = item.AsyncOperationId.Id; // if the job is suspended/waiting then cancel deleteAsyncOperationRequest.cancelFirst = (item.AsyncOperation_StateCode.Value == 1); ArrayEx.Add(deleteItems, deleteAsyncOperationRequest); } // Delete each in turn DeleteJob(deleteItems, callback); } catch (Exception ex) { ReportError(ex); } }); }
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 = 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); }); return(grid); }
public bool CRUDTests() { string timeStamp = DateTime.Now.ToISOString() + DateTime.Now.ToTimeString(); // Create a contact Entity contact1 = new Entity("contact"); contact1.SetAttributeValue("lastname", "Test Contact1 " + timeStamp); contact1.Id = OrganizationServiceProxy.Create(contact1).ToString(); Entity contact2 = new Entity("contact"); contact2.SetAttributeValue("lastname", "Test Contact2 " + timeStamp); contact2.Id = OrganizationServiceProxy.Create(contact2).ToString(); // Create the BCC list Entity recipient = new Entity("activityparty"); recipient.SetAttributeValue("partyid", contact1.ToEntityReference()); // Create email List <Entity> recipients = new List <Entity>(); ArrayEx.Add(recipients, recipient); Entity email = new Entity("email"); email.SetAttributeValue("to", new EntityCollection(recipients)); email.SetAttributeValue("subject", "Unit Test email " + timeStamp); email.SetAttributeValue("id", OrganizationServiceProxy.Create(email)); email.Id = email.GetAttributeValue("id").ToString(); // Retrieve Email Entity email2 = OrganizationServiceProxy.Retrieve("email", email.Id, new string[] { "to", "subject" }); EntityCollection to = (EntityCollection)email2.GetAttributeValue("to"); Debug.Assert(to.Entities.Count == 1); // Update recipients Entity recipient2 = new Entity("activityparty"); recipient2.SetAttributeValue("partyid", contact2.ToEntityReference()); List <Entity> toRecipients = to.Entities.Items(); ArrayEx.Add(toRecipients, recipient2); OrganizationServiceProxy.Update(email2); // Tidy up OrganizationServiceProxy.Delete_(email.LogicalName, new Guid(email.Id)); OrganizationServiceProxy.Delete_(contact1.LogicalName, new Guid(contact1.Id)); OrganizationServiceProxy.Delete_(contact2.LogicalName, new Guid(contact2.Id)); return(true); }
public MyArraySample() { Random rnd = new Random(); ArrayEx <int> _array = new ArrayEx <int>(); for (int i = 0; i < 20; ++i) { _array.Add(rnd.Next(100)); } Array = _array; }
public static string Serialise(ScheduledJob scheduledJob) { List <string> parts = new List <string>(); ArrayEx.Add(parts, "FREQ=" + scheduledJob.Recurrance.GetValue().Value); ArrayEx.Add(parts, "INTERVAL=" + scheduledJob.RecurEvery.GetValue().ToString()); if (scheduledJob.Recurrance.GetValue().Value == RecurranceFrequencyNames.WEEKLY) { List <string> days = new List <string>(); if (scheduledJob.Monday.GetValue()) { days.Add(DayNames.Monday); } if (scheduledJob.Tuesday.GetValue()) { days.Add(DayNames.Tuesday); } if (scheduledJob.Wednesday.GetValue()) { days.Add(DayNames.Wednesday); } if (scheduledJob.Thursday.GetValue()) { days.Add(DayNames.Thursday); } if (scheduledJob.Friday.GetValue()) { days.Add(DayNames.Friday); } if (scheduledJob.Saturday.GetValue()) { days.Add(DayNames.Saturday); } if (scheduledJob.Sunday.GetValue()) { days.Add(DayNames.Sunday); } if (days.Count > 0) { ArrayEx.Add(parts, "BYDAY=" + days.Join(",")); } } if (!scheduledJob.NoEndDate.GetValue()) { ArrayEx.Add(parts, "COUNT=" + scheduledJob.Count.GetValue()); } string pattern = parts.Join(";"); return(pattern); }
public static List <Column> ParseLayout(string layout) { string[] layoutParts = layout.Split(','); List <Column> cols = new List <Column>(); for (int i = 0; i < layoutParts.Length; i = i + 3) { string field = layoutParts[i + 1]; string name = layoutParts[i]; int width = int.Parse(layoutParts[i + 2]); Column col = NewColumn(field, name, width); ArrayEx.Add(cols, col); } return(cols); }
public static Column AddColumn(List <Column> cols, string displayName, int width, string field) { Column col = new Column(); col.Id = field; col.Name = displayName; // TODO: Multi-language col.Field = field; col.Width = width; col.Options = true; col.MaxWidth = width; col.MinWidth = width; col.Sortable = true; ArrayEx.Add(cols, col); return(col); }
public static EntityCollection DeSerialise(XmlNode node) { List <Entity> entities = new List <Entity>(); EntityCollection collection = new EntityCollection(entities); collection.EntityName = XmlHelper.SelectSingleNodeValue(node, "EntityName"); XmlNode entitiesNode = XmlHelper.SelectSingleNodeDeep(node, "Entities"); foreach (XmlNode entityNode in entitiesNode.ChildNodes) { Entity entity = new Entity(collection.EntityName); entity.DeSerialise(entityNode); ArrayEx.Add(entities, entity); } return(collection); }
private void Initialize() { int index = 0; Array.Resize(ref _components, _componentsLength); foreach (var component in _components) { if (component is IUpdatable) { ArrayEx.Add(ref _updatable, ref index, (IUpdatable)component); } } Array.Resize(ref _updatable, index); OnInitialize?.Invoke(); _initialized = true; }
public RetrieveUserPrivilegesResponse(XmlNode response) { XmlNode results = XmlHelper.SelectSingleNode(response, "Results"); foreach (XmlNode nameValuePair in results.ChildNodes) { XmlNode key = XmlHelper.SelectSingleNode(nameValuePair, "key"); if (XmlHelper.GetNodeTextValue(key) == "RolePrivileges") { XmlNode value = XmlHelper.SelectSingleNode(nameValuePair, "value"); this.RolePrivileges = new List <RolePrivilege>(); foreach (XmlNode privNode in value.ChildNodes) { RolePrivilege priv = new RolePrivilege(); priv.PrivilegeId = new Guid(XmlHelper.SelectSingleNodeValue(privNode, "PrivilegeId")); ArrayEx.Add(RolePrivileges, priv); } } } }
/// <summary> /// Formats a duration in minutes to a string /// </summary> /// <param name="hours"></param> /// <param name="minutes"></param> /// <returns></returns> public static string FormatDuration(int?totalMinutes) { if (totalMinutes != null) { int?toatalSeconds = totalMinutes * 60; int? days = Math.Floor(toatalSeconds / 86400); int? hours = Math.Floor((toatalSeconds % 86400) / 3600); int? minutes = Math.Floor(((toatalSeconds % 86400) % 3600) / 60); int? seconds = ((toatalSeconds % 86400) % 3600) % 60; List <string> formatString = new List <string>(); if (days > 0) { ArrayEx.Add(formatString, "{0}d"); } if (hours > 0) { ArrayEx.Add(formatString, "{1}h"); } if (minutes > 0) { ArrayEx.Add(formatString, "{2}m"); } // LED: 9/26/2013: If days and hours are 0 and minutes are 0 we want to at least show 0m so the value can be editited. if (days == 0 && hours == 0 && minutes == 0) { ArrayEx.Add(formatString, "{2}m"); } return(String.Format(ArrayEx.Join((Array)formatString, " "), days, hours, minutes)); } else { return(""); } }
public void LoadData() { List <string> someDates = new List <string>("01/01/2009", "02/02/2009", "03/03/2009"); List <Project> data = new List <Project>(); // prepare the data for (int i = 0; i < 100; i++) { Project d = new Project(); ArrayEx.Add(data, d); d.id = "id_" + i; d.num = i; d.title = "Task " + i; d.duration = Math.Round(Math.Random() * 14); d.percentComplete = Math.Round(Math.Random() * 100); d.start = someDates[Math.Floor((Math.Random() * 2))]; d.finish = someDates[Math.Floor((Math.Random() * 2))]; d.cost = Math.Round(Math.Random() * 10000) / 100; d.effortDriven = (i % 5 == 0); } Projects.SetItems(data); }
public override void Refresh() { //if (_suspendRefresh) // return; _suspendRefresh = true; // check if we have loaded this page yet int firstRowIndex = (int)paging.PageNum * (int)paging.PageSize; // If we have deleted all rows, we don't want to refresh the grid on the first page bool allDataDeleted = (paging.TotalRows == 0) && (DeleteData != null) && (DeleteData.Count > 0); List <int> rows = new List <int>(); if (firstRowIndex >= _pageLoaded) { this.OnDataLoading.Notify(null, null, null); string orderBy = ApplySorting(); // We need to load the data from the server int?fetchPageSize; fetchPageSize = this.paging.PageSize; if (String.IsNullOrEmpty(_fetchXml)) { return; } string parameterisedFetchXml = String.Format(_fetchXml, fetchPageSize, XmlHelper.Encode(this.paging.extraInfo), this.paging.PageNum + 1, orderBy); OrganizationServiceProxy.BeginRetrieveMultiple(parameterisedFetchXml, delegate(object result) { try { EntityCollection results = OrganizationServiceProxy.EndRetrieveMultiple(result, _entityType); // Set data int i = firstRowIndex; if (_lazyLoadPages) { // We are returning just one page - so add it into the data foreach (Entity e in results.Entities) { _data[i] = (Entity)e; ArrayEx.Add(rows, i); i = i + 1; } } else { // We are returning all results in one go _data = results.Entities.Items(); } // Notify DataLoadedNotifyEventArgs args = new DataLoadedNotifyEventArgs(); args.From = firstRowIndex; args.To = firstRowIndex + (int)paging.PageSize - 1; this.paging.TotalRows = results.TotalRecordCount; this.paging.extraInfo = results.PagingCookie; this.paging.FromRecord = firstRowIndex + 1; this.paging.TotalPages = Math.Ceil(results.TotalRecordCount / this.paging.PageSize); this.paging.ToRecord = Math.Min(results.TotalRecordCount, firstRowIndex + paging.PageSize); if (this._itemAdded) { this.paging.TotalRows++; this.paging.ToRecord++; this._itemAdded = false; } this.OnPagingInfoChanged.Notify(GetPagingInfo(), null, null); this.OnDataLoaded.Notify(args, null, null); } catch (Exception ex) { this.ErrorMessage = ex.Message; DataLoadedNotifyEventArgs args = new DataLoadedNotifyEventArgs(); args.ErrorMessage = ex.Message; this.OnDataLoaded.Notify(args, null, null); } }); } else { // We already have the data DataLoadedNotifyEventArgs args = new DataLoadedNotifyEventArgs(); args.From = 0; args.To = (int)paging.PageSize - 1; this.paging.FromRecord = firstRowIndex + 1; this.paging.ToRecord = Math.Min(this.paging.TotalRows, firstRowIndex + paging.PageSize); this.OnPagingInfoChanged.Notify(GetPagingInfo(), null, null); this.OnDataLoaded.Notify(args, null, null); this._itemAdded = false; } OnRowsChangedEventArgs refreshArgs = new OnRowsChangedEventArgs(); refreshArgs.Rows = rows; this.OnRowsChanged.Notify(refreshArgs, null, this); _suspendRefresh = false; }
public static List <Column> ParseLayout(string layout) { string[] layoutParts = layout.Split(','); List <Column> cols = new List <Column>(); for (int i = 0; i < layoutParts.Length; i = i + 3) { Column col = new Column(); col.Id = layoutParts[i]; col.MinWidth = 10; col.Name = layoutParts[i + 1]; col.Width = int.Parse(layoutParts[i + 2]); col.MinWidth = col.Width; //col.MaxWidth = col.Width; // This forces the column to stay the same size when resizing col.Field = layoutParts[i]; col.Sortable = true; col.Formatter = delegate(int row, int cell, object value, Column columnDef, object dataContext) { string typeName = value.GetType().Name; switch (typeName) { case "String": return(value.ToString()); case "bool": return(value + "bool"); case "Date": DateTime dateValue = (DateTime)value; string dateFormat = "dd/mm/yy"; string timeFormat = "hh:MM"; if (OrganizationServiceProxy.UserSettings != null) { dateFormat = OrganizationServiceProxy.UserSettings.DateFormatString; timeFormat = OrganizationServiceProxy.UserSettings.TimeFormatString; } return(DateTimeEx.FormatDateSpecific(dateValue, dateFormat) + " " + DateTimeEx.FormatTimeSpecific(dateValue, timeFormat)); case "decimal": return(value.ToString()); case "double": return(value.ToString()); case "int": return(value.ToString()); case "Guid": return(value.ToString()); case AttributeTypes.EntityReference: EntityReference refValue = (EntityReference)value; return(@"<a href=""#"">" + refValue.Name + "</a>"); case AttributeTypes.OptionSetValue: OptionSetValue optionValue = (OptionSetValue)value; return(optionValue.Name); default: return("null"); } }; ArrayEx.Add(cols, col); } return(cols); }
public RibbonMenuSection AddButton(RibbonControl button) { // We use this because the standard script# array extension functions break the CRM code ArrayEx.Add(Buttons, button); return(this); }
public override void AddItem(object item) { ArrayEx.Add(Books, item); Refresh(); }
private void CreateBulkDeleteJobs(ScheduledJob job) { IsBusyMessage.SetValue("Creating new schedule..."); IsBusyProgress.SetValue(0); // Convert bulk delete fetch into QueryExpression string fetchxml = "<fetch distinct='false' no-lock='false' mapping='logical'><entity name='lead'><attribute name='fullname' /><attribute name='statuscode' /><attribute name='createdon' /><attribute name='subject' /><attribute name='leadid' /><filter type='and'><condition attribute='ownerid' operator='eq-userid' /><condition attribute='statecode' operator='eq' value='0' /><condition attribute='address1_county' operator='eq' value='deleteme' /></filter><order attribute='createdon' descending='true' /></entity></fetch>"; FetchXmlToQueryExpressionRequest convertRequest = new FetchXmlToQueryExpressionRequest(); convertRequest.FetchXml = fetchxml; OrganizationServiceProxy.BeginExecute(convertRequest, delegate(object state) { FetchXmlToQueryExpressionResponse response = (FetchXmlToQueryExpressionResponse)OrganizationServiceProxy.EndExecute(state); List <BulkDeleteRequest> bulkDeleteRequests = new List <BulkDeleteRequest>(); // If the recurrance is minutely, hourly, weekly we need to schedule multiple jobs if (job.Recurrance.GetValue().Value != RecurranceFrequencyNames.DAILY) { DateTime startDate = DateTimeEx.UTCToLocalTimeFromSettings(job.StartDate.GetValue(), OrganizationServiceProxy.GetUserSettings()); DateInterval interval = DateInterval.Days; int incrementAmount = 1; int dayInterval = 1; int recurranceCount = 0; int totalCount = 0; string freq = RecurranceFrequencyNames.DAILY; switch (job.Recurrance.GetValue().Value) { case RecurranceFrequencyNames.MINUTELY: interval = DateInterval.Minutes; incrementAmount = job.RecurEvery.GetValue(); dayInterval = 1; recurranceCount = (60 * 24) / incrementAmount; break; case RecurranceFrequencyNames.HOURLY: interval = DateInterval.Hours; incrementAmount = job.RecurEvery.GetValue(); dayInterval = 1; recurranceCount = 24 / incrementAmount; break; case RecurranceFrequencyNames.WEEKLY: case RecurranceFrequencyNames.YEARLY: // To schedule weekly, me must create a job per week day for the whole year, and set recurrance to every 365 days // but this doesn't deal with leap years, so we can't do it! throw new Exception("The selected schedule interval is currently not supported due to the limitation of bulk delete"); } if (incrementAmount < 0) { throw new Exception("Invalid schedule"); } // Increment in the recurrency frequence for (int i = 0; i < recurranceCount; i++) { BulkDeleteRequest request = new BulkDeleteRequest(); request.QuerySet = response.Query.Replace(@"<d:anyType ", @"<d:anyType xmlns:e=""http://www.w3.org/2001/XMLSchema"" "); request.SendEmailNotification = false; request.StartDateTime = startDate; request.RecurrencePattern = "FREQ=DAILY;INTERVAL=" + dayInterval.ToString(); request.JobName = "Scheduled Job " + i.Format("0000") + " " + job.ScheduledJobId.GetValue().Value; ArrayEx.Add(bulkDeleteRequests, request); startDate = DateTimeEx.DateAdd(interval, incrementAmount, startDate); } } else { // Just a single request BulkDeleteRequest request = new BulkDeleteRequest(); request.QuerySet = response.Query.Replace(@"<d:anyType ", @"<d:anyType xmlns:e=""http://www.w3.org/2001/XMLSchema"" "); request.SendEmailNotification = false; request.StartDateTime = job.StartDate.GetValue(); request.RecurrencePattern = RecurrancePatternMapper.Serialise(job); request.JobName = "Scheduled Job " + job.ScheduledJobId.GetValue().Value; ArrayEx.Add(bulkDeleteRequests, request); } BatchCreateBulkDeleteJobs(bulkDeleteRequests, delegate() { IsBusy.SetValue(false); JobsViewModel.Reset(); JobsViewModel.Refresh(); }); }); }
/// <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; CheckboxSelectColumn checkBoxSelector = null; if (AddCheckBoxSelectColumn) { CheckboxSelectColumnOptions checkboxOptions = new CheckboxSelectColumnOptions(); checkboxOptions.cssClass = "sparkle-checkbox-column"; // Add check box column 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); }
public RibbonMenu AddSection(RibbonMenuSection section) { // We use this because the standard script# array extension functions break the CRM code ArrayEx.Add(Sections, section); return(this); }
public override void Refresh() { int requestedPage = paging.PageNum.Value; int pageLoadState = _pagesLoaded[requestedPage]; if (_suspendRefresh == true) { return; } _suspendRefresh = true; // If we have deleted all rows, we don't want to refresh the grid on the first page bool allDataDeleted = (paging.TotalRows == 0) && (DeleteData != null) && (DeleteData.Count > 0); List <int> rows = new List <int>(); int firstRowIndex = requestedPage * (int)paging.PageSize; if (pageLoadState != LOADING && pageLoadState != LOADED) { if (String.IsNullOrEmpty(_fetchXml)) { _suspendRefresh = false; return; } _pagesLoaded[requestedPage] = LOADING; this.OnDataLoading.Notify(null, null, null); string orderBy = ApplySorting(); // We need to load the data from the server int?fetchPageSize; fetchPageSize = this.paging.PageSize; string parameterisedFetchXml = String.Format(_fetchXml, fetchPageSize, XmlHelper.Encode(this.paging.extraInfo), requestedPage + 1, orderBy); OrganizationServiceProxy.BeginRetrieveMultiple(parameterisedFetchXml, delegate(object result) { try { EntityCollection results = OrganizationServiceProxy.EndRetrieveMultiple(result, _entityType); // Set data int i = firstRowIndex; if (_lazyLoadPages) { // We are returning just one page - so add it into the data foreach (Entity e in results.Entities) { _data[i] = (Entity)e; ArrayEx.Add(rows, i); i = i + 1; } } else { // We are returning all results in one go _data = results.Entities.Items(); } _pagesLoaded[requestedPage] = LOADED; this.paging.TotalRows = results.TotalRecordCount; this.paging.extraInfo = results.PagingCookie; this.paging.FromRecord = firstRowIndex + 1; this.paging.TotalPages = Math.Ceil(results.TotalRecordCount / this.paging.PageSize); this.paging.ToRecord = Math.Min(results.TotalRecordCount, firstRowIndex + paging.PageSize); if (this._itemAdded) { this.paging.TotalRows++; this.paging.ToRecord++; this._itemAdded = false; } this.OnPagingInfoChanged.Notify(GetPagingInfo(), null, null); // Notify DataLoadedNotifyEventArgs args = new DataLoadedNotifyEventArgs(); args.From = firstRowIndex; args.To = firstRowIndex + (int)paging.PageSize - 1; this.OnDataLoaded.Notify(args, null, null); FinishSuspend(); } catch (Exception ex) { // Issue #40 - Check for Quick Find Limit bool quickFindLimit = ex.Message.IndexOf("QuickFindQueryRecordLimit") > -1; _pagesLoaded[requestedPage] = LOADED; this.paging.TotalRows = 5001; this.OnPagingInfoChanged.Notify(GetPagingInfo(), null, null); DataLoadedNotifyEventArgs args = new DataLoadedNotifyEventArgs(); if (!quickFindLimit) { this.ErrorMessage = ex.Message; args.ErrorMessage = ex.Message; } this.OnDataLoaded.Notify(args, null, null); //_pendingRefresh = false; FinishSuspend(); } }); } else if (pageLoadState == LOADED) { // We already have the data DataLoadedNotifyEventArgs args = new DataLoadedNotifyEventArgs(); args.From = 0; args.To = (int)paging.PageSize - 1; this.paging.FromRecord = firstRowIndex + 1; this.paging.ToRecord = Math.Min(this.paging.TotalRows, firstRowIndex + paging.PageSize); this.OnPagingInfoChanged.Notify(GetPagingInfo(), null, null); this.OnDataLoaded.Notify(args, null, null); this._itemAdded = false; FinishSuspend(); } }