public void TransactionCurrencySearchCommand(string term, Action <EntityCollection> callback)
        {
            // Get the option set values

            string fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                              <entity name='transactioncurrency'>
                                <attribute name='transactioncurrencyid' />
                                <attribute name='currencyname' />
                                <attribute name='isocurrencycode' />
                                <attribute name='currencysymbol' />
                                <attribute name='exchangerate' />
                                <attribute name='currencyprecision' />
                                <order attribute='currencyname' descending='false' />
                                <filter type='and'>
                                  <condition attribute='currencyname' operator='like' value='%{0}%' />
                                </filter>
                              </entity>
                            </fetch>";

            fetchXml = string.Format(fetchXml, XmlHelper.Encode(term));
            OrganizationServiceProxy.BeginRetrieveMultiple(fetchXml, delegate(object result)
            {
                EntityCollection fetchResult = OrganizationServiceProxy.EndRetrieveMultiple(result, typeof(Entity));
                callback(fetchResult);
            });
        }
示例#2
0
        public static void RunReport(string reportName, string recordId, string etc)
        {
            // Get the name of the workflow
            string fetch = String.Format(@"<fetch count='1'>
                       <entity name='report'>
                           <attribute name='reportid'/>
                           <filter type='and'>
                               <condition attribute='name' operator='eq' value='{0}'/>
                           </filter>
                       </entity>
                   </fetch>", reportName);


            OrganizationServiceProxy.BeginRetrieveMultiple(fetch, delegate(object state)
            {
                EntityCollection results = OrganizationServiceProxy.EndRetrieveMultiple(state, typeof(Entity));

                foreach (Entity row in results.Entities)
                {
                    string id        = row.Id;
                    string orgUrl    = Page.Context.GetClientUrl();
                    string reportUrl = orgUrl +
                                       "/crmreports/viewer/viewer.aspx?action=run&id=%7b" +
                                       id.EncodeUriComponent() +
                                       "%7d&records=%7b" + recordId + "%7d&recordstype=" + etc;;
                    Window.Open(reportUrl);

                    break;
                }
            }
                                                           );
        }
示例#3
0
        public static void RunDialog(string name, string entityId, string entityLogicalName)
        {
            // Get the name of the workflow
            string fetch = String.Format(@"<fetch count='1'>
                       <entity name='workflow'>
                           <attribute name='workflowid'/>
                           <filter type='and'>
                               <condition attribute='name' operator='eq' value='{0}'/>
                               <condition attribute='ondemand' operator='eq' value='true'/>
                               <condition attribute='statuscode' operator='eq' value='2'/> 
                               <condition attribute='type' operator='eq' value='1'/>     
                           </filter>
                       </entity>
                   </fetch>", name, entityLogicalName);


            OrganizationServiceProxy.BeginRetrieveMultiple(fetch, delegate(object state)
            {
                EntityCollection results = OrganizationServiceProxy.EndRetrieveMultiple(state, typeof(Entity));

                foreach (Entity row in results.Entities)
                {
                    string url = Page.Context.GetClientUrl() +
                                 "/cs/dialog/rundialog.aspx?DialogId=" +
                                 row.GetAttributeValueGuid("workflowid").ToString() + "&EntityName=" +
                                 entityLogicalName + "&ObjectId=" +
                                 entityId;
                    Window.Open(url);
                    return;
                }
            });
        }
示例#4
0
        public static void RunWorkflow(string name, string entityId, string completeCallback, string errorCallback)
        {
            // Get the name of the workflow
            string fetch = String.Format(@"<fetch count='1'>
                       <entity name='workflow'>
                           <attribute name='workflowid'/>
                           <filter type='and'>
                               <condition attribute='name' operator='eq' value='{0}'/>
                               <condition attribute='ondemand' operator='eq' value='true'/>
                               <condition attribute='statuscode' operator='eq' value='2'/> 
                               <condition attribute='type' operator='eq' value='1'/>     
                           </filter>
                       </entity>
                   </fetch>", name);


            OrganizationServiceProxy.BeginRetrieveMultiple(fetch, delegate(object state)
            {
                EntityCollection results = OrganizationServiceProxy.EndRetrieveMultiple(state, typeof(Entity));
                if (results.Entities.Count == 0)
                {
                    Page.Ui.SetFormNotification("Workflow " + name + " is not published", FormNotificationLevel.Error, "RibbonWorkflowError");
                }
                bool isError = false;
                foreach (Entity row in results.Entities)
                {
                    // Run Workflow
                    ExecuteWorkflowRequest request = new ExecuteWorkflowRequest();
                    request.EntityId   = entityId.Replace("{", "").Replace("}", "");
                    request.WorkflowId = row.GetAttributeValueString("workflowid");
                    OrganizationServiceProxy.BeginExecute(request, delegate(object executeState)
                    {
                        try
                        {
                            ExecuteWorkflowResponse response =
                                (ExecuteWorkflowResponse)OrganizationServiceProxy.EndExecute(executeState);
                            if (completeCallback != null)
                            {
                                if (response.Id == Guid.Empty.Value)
                                {
                                    Script.Eval(completeCallback);
                                }
                                else
                                {
                                    // Query until completed
                                    WaitForWorkflowToComplete(response.Id, completeCallback, errorCallback, null);
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            string stackTrace = e.StackTrace;
                            Script.Literal("console.log(stackTrace)");
                            Script.Eval(errorCallback);
                        }
                    });
                    break;
                }
            });
        }
        public void ActivitySearchCommand(string term, Action <EntityCollection> callback)
        {
            // Get the option set values

            string fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                              <entity name='activitypointer'>
                                <attribute name='activitytypecode' />
                                <attribute name='subject' />
                                <attribute name='activityid' />
                                <attribute name='instancetypecode' />
                                <order attribute='modifiedon' descending='false' />
                                <filter type='and'>
                                  <condition attribute='ownerid' operator='eq-userid' />
                                    <condition attribute='subject' operator='like' value='%{0}%' />
                                </filter>
                              </entity>
                            </fetch>";

            fetchXml = string.Format(fetchXml, XmlHelper.Encode(term));
            OrganizationServiceProxy.BeginRetrieveMultiple(fetchXml, delegate(object result)
            {
                EntityCollection fetchResult = OrganizationServiceProxy.EndRetrieveMultiple(result, typeof(Entity));
                callback(fetchResult);
            });
        }
示例#6
0
        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);
                }
            });
        }
示例#7
0
        private void SearchRecords(string term, Action <EntityCollection> callback, string entityType)
        {
            string fetchXml = _queryParser.GetFetchXmlForQuery(entityType, "QuickFind", term, SearchTermOptions.PrefixWildcard | SearchTermOptions.SuffixWildcard);


            OrganizationServiceProxy.BeginRetrieveMultiple(fetchXml, delegate(object result)
            {
                EntityCollection fetchResult = OrganizationServiceProxy.EndRetrieveMultiple(result, typeof(Entity));
                fetchResult.EntityName       = entityType;
                callback(fetchResult);
            });
        }
        private void SearchRecords(string term, Action <EntityCollection> callback, string entityType, string entityNameAttribute)
        {
            string fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false' no-lock='true' count='25'>
                              <entity name='{1}'>
                                <attribute name='{2}' alias='name' />
                                <order attribute='{2}' descending='false' />
                                <filter type='and'>
                                  <condition attribute='{2}' operator='like' value='%{0}%' />
                                </filter>
                              </entity>
                            </fetch>";

            fetchXml = string.Format(fetchXml, XmlHelper.Encode(term), entityType, entityNameAttribute);
            OrganizationServiceProxy.BeginRetrieveMultiple(fetchXml, delegate(object result)
            {
                EntityCollection fetchResult = OrganizationServiceProxy.EndRetrieveMultiple(result, typeof(Entity));
                callback(fetchResult);
            });
        }
示例#9
0
        public void UoMSearchCommand(string term, Action <EntityCollection> callback)
        {
            string fetchXml = @" <fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                                  <entity name='uom'>
                                    <attribute name='uomid' />
                                    <attribute name='name' />
                                    <order attribute='name' descending='false' />
                                    <filter type='and'>
                                      <condition attribute='name' operator='like' value='%{0}%' />
                                    </filter>
                                  </entity>
                                </fetch>";

            fetchXml = string.Format(fetchXml, XmlHelper.Encode(term));
            OrganizationServiceProxy.BeginRetrieveMultiple(fetchXml, delegate(object result)
            {
                EntityCollection fetchResult = OrganizationServiceProxy.EndRetrieveMultiple(result, typeof(Entity));
                callback(fetchResult);
            });
        }
示例#10
0
        public static void RoleSearch(string term, Action <EntityCollection> callback, string typeName)
        {
            string recordTypeFilter = string.Empty;

            if (typeName != null)
            {
                // find the entity type code from the type name
                int?etc = GetEntityTypeCodeFromName(typeName);
                // Filter by the currently select role
                recordTypeFilter = String.Format(@"
                                        <filter type='or'>
                                            <condition attribute='associatedobjecttypecode' operator='eq' value='{0}' />
                                            <condition attribute='associatedobjecttypecode' operator='eq' value='0' />
                                        </filter>", etc);
            }
            string fetchXml = @"
                            <fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false' no-lock='true' >
                                <entity name='connectionrole' >
                                    <attribute name='category' />
                                    <attribute name='name' />
                                    <attribute name='connectionroleid' />
                                    <attribute name='statecode' />
                                    <order attribute='name' descending='false' />
                                    <link-entity name='connectionroleobjecttypecode' from='connectionroleid' to='connectionroleid' >
                                    {1}
                                    </link-entity>
                                    <filter type='and'>                                     
                                        <condition attribute='name' operator='like' value='%{0}%' />
                                    </filter>
                                </entity>
                            </fetch>";

            fetchXml = string.Format(fetchXml, XmlHelper.Encode(term), recordTypeFilter);
            OrganizationServiceProxy.BeginRetrieveMultiple(fetchXml, delegate(object result)
            {
                EntityCollection fetchResult = OrganizationServiceProxy.EndRetrieveMultiple(result, typeof(Entity));
                callback(fetchResult);
            });
        }
示例#11
0
        public override void Refresh()
        {
            if (weeks[WeekStart.GetTime()] == null)
            {
                this.OnDataLoading.Notify(null, null, null);

                // We need to load the data from the server
                OrganizationServiceProxy.BeginRetrieveMultiple(String.Format(Queries.SessionsByWeekStartDate, DateTimeEx.ToXrmString(WeekStart), DateTimeEx.ToXrmString(WeekEnd)), delegate(object result)
                {
                    try
                    {
                        EntityCollection results = OrganizationServiceProxy.EndRetrieveMultiple(result, typeof(dev1_session));

                        // Set data
                        List <dev1_session> sessions = new List <dev1_session>();
                        weeks[WeekStart.GetTime()]   = sessions;
                        foreach (Entity e in results.Entities)
                        {
                            AddSession(sessions, (dev1_session)e);
                        }

                        RefreshActivityView();
                    }
                    catch (Exception ex)
                    {
                        // Show error
                        Script.Alert("There was an error loading the Timesheet sessions\n" + ex.Message);
                    }
                });
            }
            else
            {
                RefreshActivityView();
            }
            // Only show the selected
        }
示例#12
0
        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 void RegardingObjectSearchCommand(string term, Action <EntityCollection> callback)
        {
            string regardingAccountFetchXml     = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                                  <entity name='account'>
                                    <attribute name='name' />
                                    <attribute name='accountid' />
                                    <order attribute='name' descending='false' />
                                    <filter type='and'>
                                      <condition attribute='statecode' operator='eq' value='0' />
                                      <condition attribute='name' operator='like' value='%{0}%' />
                                      {1}
                                    </filter>
                                   </entity>
                                </fetch>";
            string regardingOpportunityFetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                                                  <entity name='opportunity'>
                                                    <attribute name='name' />
                                                    <attribute name='opportunityid' />
                                                    <order attribute='name' descending='false' />
                                                    <filter type='and'>
                                                      <condition attribute='statecode' operator='eq' value='0' />
                                                      <condition attribute='name' operator='like' value='%{0}%' />
                                                     {1}
                                                    </filter>
                                                  </entity>
                                                </fetch>";

            string regardingIncidentFetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                                              <entity name='incident'>
                                                <attribute name='title' />
                                                <attribute name='incidentid' />
                                                <order attribute='title' descending='false' />
                                                <filter type='and'>
                                                  <condition attribute='title' operator='like' value='%{0}%' />
                                                  {1}
                                                </filter>
                                              </entity>
                                            </fetch>";

            string   accountCriteriaFetchXml = @"<condition attribute='{0}' operator='eq' value='{1}' />";
            DayEntry selectedItem            = this.Days.SelectedItems[0];


            List <Entity> unionedResults = new List <Entity>();

            // We need to union the activities regarding the account directly with those that are regarding related records
            Action <string, string, string, Action, Action> unionSearch = delegate(string fetchXml, string nameAttribute, string accountAttribute, Action completeCallBack, Action errorCallBack)
            {
                // Add Account filter if an account is selected
                string additionalCriteria = "";
                if (selectedItem != null && selectedItem.Account != null)
                {
                    additionalCriteria = string.Format(accountCriteriaFetchXml, accountAttribute, selectedItem.Account.Id.Value);
                }
                string queryFetchXml = string.Format(fetchXml, XmlHelper.Encode(term), additionalCriteria);
                OrganizationServiceProxy.BeginRetrieveMultiple(queryFetchXml, delegate(object result)
                {
                    EntityCollection fetchResult = OrganizationServiceProxy.EndRetrieveMultiple(result, typeof(ActivityPointer));
                    // Adjust the entity types
                    foreach (Entity a in fetchResult.Entities)
                    {
                        // Set name
                        a.SetAttributeValue("displayName", a.GetAttributeValueString(nameAttribute));
                        unionedResults.Add(a);
                    }

                    completeCallBack();
                });
            };

            TaskIterrator tasks = new TaskIterrator();

            // Add Searches
            tasks.AddTask(delegate(Action completeCallBack, Action errorCallBack) { unionSearch(regardingAccountFetchXml, "name", "accountid", completeCallBack, errorCallBack); });
            tasks.AddTask(delegate(Action completeCallBack, Action errorCallBack) { unionSearch(regardingOpportunityFetchXml, "name", "customerid", completeCallBack, errorCallBack); });
            tasks.AddTask(delegate(Action completeCallBack, Action errorCallBack) { unionSearch(regardingIncidentFetchXml, "title", "customerid", completeCallBack, errorCallBack); });

            Action queryComplete = delegate()
            {
                //  Sort Alphabetically
                unionedResults.Sort(delegate(Entity a, Entity b) { return(Entity.SortDelegate("displayName", a, b)); });
                // Completed the queryies, so sort then and add to Entity Collection
                EntityCollection results = new EntityCollection(unionedResults);

                callback(results);
            };

            // Start processing queue
            tasks.Start(queryComplete, null);
        }
        public void ActivitySearchCommand(string term, Action <EntityCollection> callback)
        {
            // Get the option set values

            string fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                                  <entity name='activitypointer'>
                                    <attribute name='activitytypecode' />
                                    <attribute name='subject' />
                                    <attribute name='activityid' />
                                    <attribute name='instancetypecode' />
                                    <attribute name='regardingobjectid' />
                                    <order attribute='modifiedon' descending='false' />
                                    <filter type='and'>
                                      <condition attribute='ownerid' operator='eq-userid' />
                                        <condition attribute='subject' operator='like' value='%{0}%' />
                                          <condition attribute='activitytypecode' operator='in'>
                                            <value>4202</value>
                                            <value>4207</value>
                                            <value>4210</value>
                                            <value>4212</value>
                                          </condition>
                                            {2}
                                    </filter>
                                    {1}
                                  </entity>
                                </fetch>";
            // Get the account to filter on if there is one
            string regardingObjectIdFilterFetchXml = @"<condition attribute='regardingobjectid' operator='eq' value='{0}'/>";

            string opportunityAccountFilterFetchXml = @"<link-entity name='opportunity' from='opportunityid' to='regardingobjectid' visible='false' link-type='inner' alias='opportunity' >
                                        <attribute name='customerid' />
                                        <filter type='and' >
                                            <condition attribute='customerid' operator='eq' value='{0}' />
                                        </filter>
                                        </link-entity>";

            string incidentAccountFilterFetchXml = @" <link-entity name='incident' from='incidentid' to='regardingobjectid' visible='false' link-type='inner' alias='incident' >
                                        <attribute name='customerid' />
                                        <filter type='and' >
                                            <condition attribute='customerid' operator='eq' value='{0}' />
                                        </filter>
                                        </link-entity>";

            string contractAccountFilterFetchXml = @" <link-entity name='contract' from='contractid' to='regardingobjectid' visible='false' link-type='inner' alias='contract' >
                                        <attribute name='customerid' />
                                        <filter type='and' >
                                            <condition attribute='customerid' operator='eq' value='{0}' />
                                        </filter>
                                        </link-entity>";

            string regardingAccountFilterFetchXml = @" <link-entity name='account' from='accountid' to='regardingobjectid' visible='false' link-type='inner' alias='account' >
                                        <attribute name='accountid'/>
                                        <attribute name='name'/>
                                        <filter type='and' >
                                            <condition attribute='accountid' operator='eq' value='{0}' />
                                        </filter>
                                        </link-entity>";

            DayEntry selectedItem             = this.Days.SelectedItems[0];
            string   regardingObjectFilter    = String.Empty;
            string   regardingAccountFilter   = String.Empty;
            string   opportunityAccountFilter = String.Empty;
            string   incidentAccountFilter    = String.Empty;
            string   contractAccountFilter    = String.Empty;

            if (selectedItem != null && selectedItem.RegardingObjectId != null)
            {
                regardingObjectFilter = string.Format(regardingObjectIdFilterFetchXml, selectedItem.RegardingObjectId.Id.Value);
            }

            if (selectedItem != null && selectedItem.Account != null)
            {
                // Add in the regarding account filter
                regardingAccountFilter   = string.Format(regardingAccountFilterFetchXml, selectedItem.Account.Id.Value);
                opportunityAccountFilter = string.Format(opportunityAccountFilterFetchXml, selectedItem.Account.Id.Value);
                incidentAccountFilter    = string.Format(incidentAccountFilterFetchXml, selectedItem.Account.Id.Value);
                contractAccountFilter    = string.Format(contractAccountFilterFetchXml, selectedItem.Account.Id.Value);
            }

            List <Entity> unionedResults = new List <Entity>();

            // We need to union the activities regarding the account directly with those that are regarding related records
            Action <string, string, Action, Action> unionSearch = delegate(string additionalFilter, string additionalCriteria, Action completeCallBack, Action errorCallBack)
            {
                string queryFetchXml = string.Format(fetchXml, XmlHelper.Encode(term), additionalFilter, additionalCriteria);
                OrganizationServiceProxy.BeginRetrieveMultiple(queryFetchXml, delegate(object result)
                {
                    EntityCollection fetchResult = OrganizationServiceProxy.EndRetrieveMultiple(result, typeof(ActivityPointer));
                    // Adjust the entity types
                    foreach (ActivityPointer a in fetchResult.Entities)
                    {
                        a.UpdateCalculatedFields();
                        unionedResults.Add(a);
                    }

                    completeCallBack();
                });
            };

            TaskIterrator tasks = new TaskIterrator();

            // Default Search
            tasks.AddTask(delegate(Action completeCallBack, Action errorCallBack) { unionSearch(regardingAccountFilter, regardingObjectFilter, completeCallBack, errorCallBack); });

            // Associated record searches
            if (opportunityAccountFilter != String.Empty)
            {
                tasks.AddTask(delegate(Action completeCallBack, Action errorCallBack) { unionSearch(opportunityAccountFilter, String.Empty, completeCallBack, errorCallBack); });
            }
            if (incidentAccountFilter != String.Empty)
            {
                tasks.AddTask(delegate(Action completeCallBack, Action errorCallBack) { unionSearch(incidentAccountFilter, String.Empty, completeCallBack, errorCallBack); });
            }
            if (contractAccountFilter != String.Empty)
            {
                tasks.AddTask(delegate(Action completeCallBack, Action errorCallBack) { unionSearch(contractAccountFilter, String.Empty, completeCallBack, errorCallBack); });
            }


            Action queryComplete = delegate()
            {
                // Sort
                unionedResults.Sort(delegate(Entity a, Entity b) { return(Entity.SortDelegate("subject", a, b)); });
                // Completed the queryies, so sort then and add to Entity Collection
                EntityCollection results = new EntityCollection(unionedResults);

                callback(results);
            };

            // Start processing queue
            tasks.Start(queryComplete, null);
        }
示例#15
0
        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();
            }
        }