当前位置: 首页>>代码示例>>C#>>正文


C# IOrganizationService.Delete方法代码示例

本文整理汇总了C#中IOrganizationService.Delete方法的典型用法代码示例。如果您正苦于以下问题:C# IOrganizationService.Delete方法的具体用法?C# IOrganizationService.Delete怎么用?C# IOrganizationService.Delete使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在IOrganizationService的用法示例。


在下文中一共展示了IOrganizationService.Delete方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: UpdateWorkflows

        private void UpdateWorkflows(IOrganizationService service, AttributeMetadata att)
        {
            Trace("Checking for Workflow Dependencies");
            var depends = ((RetrieveDependenciesForDeleteResponse)service.Execute(new RetrieveDependenciesForDeleteRequest
            {
                ComponentType = (int)ComponentType.Attribute,
                ObjectId = att.MetadataId.GetValueOrDefault()
            })).EntityCollection.ToEntityList<Dependency>().Where(d => d.DependentComponentTypeEnum == ComponentType.Workflow).ToList();

            if (!depends.Any())
            {
                Trace("No Workflow Dependencies Found");
                return;
            }

            foreach (var workflow in service.GetEntitiesById<Workflow>(depends.Select(d => d.DependentComponentObjectId.GetValueOrDefault())))
            {
                Trace("Updating {0} - {1} ({2})", workflow.CategoryEnum.ToString(), workflow.Name, workflow.Id);
                workflow.Xaml = RemoveParentXmlNodesWithTagValue(workflow.Xaml, "mxswa:ActivityReference AssemblyQualifiedName=\"Microsoft.Crm.Workflow.Activities.StepComposite,", "mcwb:Control", "DataFieldName", att.LogicalName, "mxswa:ActivityReference");
                var unsupportedXml = RemoveXmlNodesWithTagValue(workflow.Xaml, "mxswa:GetEntityProperty", "Attribute", att.LogicalName);
                if (workflow.Xaml != unsupportedXml)
                {
                    throw new NotImplementedException("Attribute is used in a Business Rules Get Entity Property.  This is unsupported for manual deletion.  Delete the Business Rule " + workflow.Name + " manually to be able to delete the attribute.");
                }
                
                var activate = workflow.StateCode == WorkflowState.Activated;
                if (activate)
                {
                    service.Execute(new SetStateRequest
                    {
                        EntityMoniker = workflow.ToEntityReference(),
                        State = new OptionSetValue((int)WorkflowState.Draft),
                        Status = new OptionSetValue((int)Workflow_StatusCode.Draft)
                    });
                }
                try
                {
                    var triggers = service.GetEntities<ProcessTrigger>(ProcessTrigger.Fields.ProcessId,
                        workflow.Id,
                        ProcessTrigger.Fields.ControlName,
                        att.LogicalName);

                    foreach (var trigger in triggers)
                    {
                        Trace("Deleting Trigger {0} for Workflow", trigger.Id);
                        service.Delete(ProcessTrigger.EntityLogicalName, trigger.Id);
                    }

                    service.Update(workflow);
                }
                finally
                {
                    if (activate)
                    {
                        service.Execute(new SetStateRequest()
                        {
                            EntityMoniker = workflow.ToEntityReference(),
                            State = new OptionSetValue((int) WorkflowState.Activated),
                            Status = new OptionSetValue((int) Workflow_StatusCode.Activated)
                        });
                    }
                }

            }
        }
开发者ID:daryllabar,项目名称:DLaB.Xrm.XrmToolBoxTools,代码行数:65,代码来源:DeleteLogic.cs

示例2: DeleteInternal

        private static BulkDeleteResult DeleteInternal(IOrganizationService service, QueryExpression[] querySets)
        {
            BulkDeleteResult result = new BulkDeleteResult();

            // Create the bulk delete request
            BulkDeleteRequest bulkDeleteRequest = new BulkDeleteRequest()
            {
                // Set the request properties
                JobName = "Temp Bulk Delete " + DateTime.Now,
                QuerySet = querySets,
                ToRecipients = new Guid[0],
                CCRecipients = new Guid[0],
                RecurrencePattern = string.Empty
            };

            // Submit the bulk delete job.
            // NOTE: Because this is an asynchronous operation, the response will be immediate.
            BulkDeleteResponse response = (BulkDeleteResponse)service.Execute(bulkDeleteRequest);

            Guid asyncId = response.JobId;
            var bulkOperation = GetBulkDeleteOperation(service, asyncId);

            // Monitor the async operation through polling until it is complete or max polling time expires.
            int secondsTicker = MaxAsynchronousRequestTimeout;
            while (secondsTicker > 0)
            {
                // Make sure that the async operation was retrieved.
                if (bulkOperation != null && bulkOperation.StateCode.Value == BulkDeleteOperationState.Completed)
                {
                    result.TimedOut = false;
                    break;
                }

                // Wait a second for async operation to become active.
                System.Threading.Thread.Sleep(1000);
                secondsTicker--;

                // Retrieve the entity again
                bulkOperation = GetBulkDeleteOperation(service, asyncId);
            }

            if (result.TimedOut == null)
            {
                result.TimedOut = true;
            }

            // Validate that the operation was completed.
            if (bulkOperation == null)
            {
                result.Result = "The Bulk Operation for Async " + asyncId + " was not found.";
            }
            else
            {
                result.DeletedCount = bulkOperation.SuccessCount ?? 0;
                result.DeleteFailedCount = bulkOperation.FailureCount ?? 0;
                if (bulkOperation.StateCode.Value != BulkDeleteOperationState.Completed ||
                    bulkOperation.StatusCode.Value != (int)bulkdeleteoperation_statuscode.Succeeded)
                {
                    // This happens if it took longer than the polling time allowed 
                    // for this operation to finish.
                    result.Result = "The operation took longer than the polling time allowed for this operation to finish.";
                }
                else if (result.DeleteFailedCount > 0)
                {
                    result.Result = string.Format("The opertion had {0} failures and {1} successful deletions",
                            result.DeletedCount, result.DeleteFailedCount);
                }
                else
                {
                    result.Result = string.Format("The operation had {0} successful deletions",
                        result.DeletedCount);
                }
            }

            service.Delete(BulkDeleteOperation.EntityLogicalName, bulkOperation.Id);

            // We have to update the AsyncOperation to be in a Completed state before we can delete it.
            service.InitializeEntity<Entities.AsyncOperation>(bulkOperation.AsyncOperationId.Id,
                    a => { a.StateCode = AsyncOperationState.Completed; });

            // Not sure if the status code needs to be set...
            //a.StatusCode = new OptionSetValue((int)asyncoperation_statuscode.Succeeded) });
            service.Delete(Entities.AsyncOperation.EntityLogicalName, bulkOperation.AsyncOperationId.Id);
            return result;
        }
开发者ID:ganpathv,项目名称:DLaB.Xrm.XrmToolBoxTools,代码行数:85,代码来源:BulkDelete.cs

示例3: UpdateMappings

        private void UpdateMappings(IOrganizationService service, AttributeMetadata att)
        {
            Trace("Looking up Mappings");
            var mappings = service.GetEntities<AttributeMap>(AttributeMap.Fields.SourceAttributeName,
                att.LogicalName,
                LogicalOperator.Or,
                AttributeMap.Fields.TargetAttributeName,
                att.LogicalName);
            foreach (var mapping in mappings.Where(m => !m.IsManaged.GetValueOrDefault() && !m.IsSystem.GetValueOrDefault()))
            {
                Trace("Deleting Attribute Mapping: " + mapping.Id);
                service.Delete(mapping.LogicalName, mapping.Id);
            }

            if (mappings.Count == 0)
            {
                Trace("No Mappings Found");
            }
        }
开发者ID:daryllabar,项目名称:DLaB.Xrm.XrmToolBoxTools,代码行数:19,代码来源:DeleteLogic.cs

示例4: Run

        /// <summary>
        /// Create and configure the organization service proxy.
        /// Create an account record
        /// Retrieve the account record
        /// Update the account record
        /// Optionally delete any entity records that were created for this sample.
       /// </summary>
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptForDelete">When True, the user will be prompted to delete
        /// all created entities.</param>
        public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
        {
            try
            {

                // Connect to the Organization service. 
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    _service = (IOrganizationService)_serviceProxy;

                    //<snippetCRUDOperationsDE1>
                    // Instaniate an account object.
                    Entity account = new Entity("account");

                    // Set the required attributes. For account, only the name is required. 
                    // See the Entity Metadata topic in the SDK documentatio to determine 
                    // which attributes must be set for each entity.
                    account["name"] = "Fourth Coffee";

                    // Create an account record named Fourth Coffee.
                    _accountId = _service.Create(account);

                    Console.Write("{0} {1} created, ", account.LogicalName, account.Attributes["name"]);

                    // Create a column set to define which attributes should be retrieved.
                    ColumnSet attributes = new ColumnSet(new string[] { "name", "ownerid" });

                    // Retrieve the account and its name and ownerid attributes.
                    account = _service.Retrieve(account.LogicalName, _accountId, attributes);
                    Console.Write("retrieved, ");

                    // Update the postal code attribute.
                    account["address1_postalcode"] = "98052";

                    // The address 2 postal code was set accidentally, so set it to null.
                    account["address2_postalcode"] = null;

                    // Shows use of Money.
                    account["revenue"] = new Money(5000000);

                    // Shows use of boolean.
                    account["creditonhold"] = false;

                    // Update the account.
                    _service.Update(account);
                    Console.WriteLine("and updated.");

                    // Delete the account.
                    bool deleteRecords = true;

                    if (promptForDelete)
                    {
                        Console.WriteLine("\nDo you want these entity records deleted? (y/n) [y]: ");
                        String answer = Console.ReadLine();

                        deleteRecords = (answer.StartsWith("y") || answer.StartsWith("Y") || answer == String.Empty);
                    }

                    if (deleteRecords)
                    {
                        _service.Delete("account", _accountId);

                        Console.WriteLine("Entity record(s) have been deleted.");
                    }

                    //</snippetCRUDOperationsDE1>
                }
            }

            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>)
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
开发者ID:cesugden,项目名称:Scripts,代码行数:87,代码来源:CRUDOperationsDE.cs

示例5: FakeDelete

        /// <summary>
        /// Fakes the delete method. Very similar to the Retrieve one
        /// </summary>
        /// <param name="context"></param>
        /// <param name="fakedService"></param>
        protected static void FakeDelete(XrmFakedContext context, IOrganizationService fakedService)
        {
            A.CallTo(() => fakedService.Delete(A<string>._, A<Guid>._))
                .Invokes((string entityName, Guid id) =>
                {
                    if (string.IsNullOrWhiteSpace(entityName))
                    {
                        throw new InvalidOperationException("The entity logical name must not be null or empty.");
                    }

                    if (id == Guid.Empty)
                    {
                        throw new InvalidOperationException("The id must not be empty.");
                    }

                    if (!context.Data.ContainsKey(entityName))
                        throw new InvalidOperationException(string.Format("The entity logical name {0} is not valid.", entityName));

                    //Entity logical name exists, so , check if the requested entity exists
                    if (context.Data[entityName] != null
                        && context.Data[entityName].ContainsKey(id))
                    {
                        //Entity found => return only the subset of columns specified or all of them
                        context.Data[entityName].Remove(id);
                    }
                    else
                    {
                        //Entity not found in the context => throw not found exception
                        //The entity record was not found, return a CRM-ish update error message
                        throw new FaultException<OrganizationServiceFault>(new OrganizationServiceFault(),
                            string.Format("{0} with Id {1} Does Not Exist", entityName, id));
                    }
                });
        }
开发者ID:ccellar,项目名称:fake-xrm-easy,代码行数:39,代码来源:XrmFakedContext.Crud.cs

示例6: Invoke_Delete

        public void Invoke_Delete(IOrganizationService service)
        {
            // Arrange
            Action fail = () =>
            {
                service.Delete("fail", Guid.Empty);
            };

            // Act
            service.Delete(string.Empty, Guid.Empty);

            // Assert
            fail.ShouldThrow<InvalidPluginExecutionException>();

            ((CuteService)service).Provider.Calls.Where(x => x.Message == MessageName.Delete).Count().Should().Be(2, because: "two `Delete` call was executed already");
        }
开发者ID:Innofactor,项目名称:CUTE,代码行数:16,代码来源:ServiceTestCases.cs

示例7: createOrUpdateBudgetLineItems

        private void createOrUpdateBudgetLineItems(FundCentreParamaters param, IOrganizationService service, Entity preEntity, Entity entity)
        {
            //using (var ctx = new OrganizationServiceContext(service)) {
                OrganizationServiceContext ctx = new OrganizationServiceContext(service);
                FaultException ex1 = new FaultException();

             //DELETE existing budget lines
                QueryExpression existingFundCentreBudgets = new QueryExpression
                {
                    EntityName = "gcbase_fundcentrebudget",
                    ColumnSet = new ColumnSet("gcbase_fundcentre", "gcbase_fiscalyear"),
                    Criteria = new FilterExpression
                    {
                        Conditions = {
                     new ConditionExpression {
                        AttributeName = "gcbase_fundcentre",
                        Operator = ConditionOperator.Equal,
                        Values = { param.id }
                     }
                   }
                    }
                };

                if (param.startdate.HasValue && param.enddate.HasValue) {

                    int[] fiscalYears = new FiscalYear(param.startdate.Value, param.enddate.Value).getFiscalYears();

                    DataCollection<Entity> fundCentreBudgetsToDelete = service.RetrieveMultiple(existingFundCentreBudgets).Entities;
                    if (fundCentreBudgetsToDelete.Count > 0)
                    {
                        // here we should validate if we have projects pending instead of deleting budgets

                       var currentYears = fundCentreBudgetsToDelete.Select(s => (int)s.GetAttributeValue<OptionSetValue>("gcbase_fiscalyear").Value).ToArray();
                        var newYears = fiscalYears.ToArray();
                        //newYears.Except(currentYears);

                        var illegalYears = currentYears.Except(newYears);

                        if (illegalYears.Count() > 0)
                        {
                            throw new InvalidPluginExecutionException(@"Cannot save your new start and end dates because there are budgets entered in
                        fiscal years that fall outside of those dates. If you want to revise the dates please first delete the budgets in
                        fiscal years: " + string.Join("-", illegalYears) + " and try again!", ex1);
                        }
                        else
                        {
                            foreach (Entity fcb in fundCentreBudgetsToDelete)
                            {
                                service.Delete("gcbase_fundcentrebudget", fcb.Id);
                            }
                        }
                    }

                    Array values = Enum.GetValues(typeof(goal_fiscalyear));
                    string[] fys = new string[fiscalYears.Count()];
                    int index = 0;

                    //QueryExpression fundTypeQry = new QueryExpression
                    //{
                    //    EntityName = "gcbase_fundtype",
                    //    ColumnSet = new ColumnSet("gcbase_name"),
                    //    Criteria = new FilterExpression
                    //    {
                    //        Conditions = {
                    //            new ConditionExpression("gcbase_name", ConditionOperator.Equal, "Contribution")
                    //        }
                    //    }
                    //};
                    //DataCollection<Entity> fundTypes = service.RetrieveMultiple(fundTypeQry).Entities;
                    //Guid contribution = new Guid();

                    //foreach (var ft in fundTypes)
                    //{
                    //    if (ft.Attributes["gcbase_name"].ToString() != "Grant")
                    //    {
                    //        contribution = ft.Id;
                    //    }
                    //}

                    // throw new InvalidPluginExecutionException(grant.ToString() + contribution.ToString(), ex1);

                    foreach (int year in fiscalYears)
                    {
                        if (param.amount.Value > 0)
                        {
                            Entity fundCentreBudget = new Entity("gcbase_fundcentrebudget");
                            // fundCentreBudget.Id = Guid.NewGuid();
                            fundCentreBudget["gcbase_amount"] = (Money)param.amount;
                            fys[index] = (string)Enum.GetName(typeof(goal_fiscalyear), year);
                            OptionSetValue fy = new OptionSetValue();
                            fy.Value = year;
                            fundCentreBudget["gcbase_fiscalyear"] = fy;

                            EntityReference fundCentre = new EntityReference("gcbase_fundcentre", param.id);
                            fundCentreBudget["gcbase_fundcentre"] = fundCentre;
                            fundCentreBudget["gcbase_name"] = param.name + "-" + fy.Value;
                            // ctx.Attach(fundCentreBudget)
                            ctx.AddObject(fundCentreBudget);
                            ctx.SaveChanges();
                        }
//.........这里部分代码省略.........
开发者ID:fredp613,项目名称:crmPluginsGnC,代码行数:101,代码来源:PreFundCentreUpdate.cs


注:本文中的IOrganizationService.Delete方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。