Example #1
0
        /// <summary>
        /// Deletes the custom entity record that was created for this sample.
        /// <param name="prompt">Indicates whether to prompt the user
        /// to delete the entity created in this sample.</param>
        /// </summary>
        public void DeleteRequiredRecords(bool prompt)
        {
            bool deleteRecords = true;

            if (prompt)
            {
                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)
            {
                //delete Web Resources
                foreach (Guid id in _webResourceIds)
                {
                    _serviceProxy.Delete(WebResource.EntityLogicalName, id);
                }
                Console.WriteLine("Web Resource records have been deleted.");
                //Delete Solution

                _serviceProxy.Delete(Solution.EntityLogicalName, _importWebResourcesSampleSolutionId);
                Console.WriteLine("Solution has been deleted.");

                //
                if (_createdPublisher)
                {
                    // Delete the publisher
                    _serviceProxy.Delete(Publisher.EntityLogicalName, _crmSdkPublisherId);
                    Console.WriteLine("Publisher has been deleted.");
                }
            }
        }
Example #2
0
        /// <summary>
        /// Deletes the custom entity record that was created for this sample.
        /// <param name="prompt">Indicates whether to prompt the user
        /// to delete the entity created in this sample.</param>
        /// </summary>
        public static void DeleteRequiredRecords(CrmServiceClient service, bool prompt)
        {
            bool deleteRecords = true;

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

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

            if (deleteRecords)
            {
                // TODO Delete entity records
                // Delete all records created in this sample.
                _serviceProxy.Delete("goal", _firstChildGoalId);
                _serviceProxy.Delete("goal", _secondChildGoalId);
                _serviceProxy.Delete("goal", _parentGoalId);
                _serviceProxy.Delete("goalrollupquery", _rollupQueryIds[0]);
                _serviceProxy.Delete("goalrollupquery", _rollupQueryIds[1]);
                _serviceProxy.Delete("account", _accountId);
                _serviceProxy.Delete("phonecall", _phoneCallId);
                _serviceProxy.Delete("phonecall", _phoneCall2Id);
                _serviceProxy.Delete("rollupfield", _actualId);
                _serviceProxy.Delete("metric", _metricId);
                Console.WriteLine("Entity records have been deleted.");
            }
        }
Example #3
0
        /// <summary>
        /// Deletes/Reverts the record that was created/changed for this sample.
        /// <param name="prompt">Indicates whether to prompt the user to delete
        /// the records created in this sample.</param>
        /// </summary>
        public void DeleteRequiredRecords(bool prompt)
        {
            bool deleteRecords = true;

            if (prompt)
            {
                Console.WriteLine("\nDo you want these entity records and attribute to be deleted? (y/n)");
                String answer = Console.ReadLine();

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

            if (deleteRecords)
            {
                //Delete all records and attributes created for this sample.

                _serviceProxy.Delete(Account.EntityLogicalName, _account1ID);
                _serviceProxy.Delete(Account.EntityLogicalName, _account2ID);

                DeleteAttributeRequest deleteAttribute = new DeleteAttributeRequest
                {
                    EntityLogicalName = Account.EntityLogicalName,
                    LogicalName       = dtAttribute.SchemaName.ToLower()
                };
                _serviceProxy.Execute(deleteAttribute);

                Console.WriteLine("Deleted all records and attribute created for this sample.");
            }
        }
Example #4
0
        private void DeleteRecords(bool prompt)
        {
            bool toBeDeleted = true;

            if (prompt)
            {
                // Ask the user if the created entities should be deleted.
                Console.Write("\nDo you want these entity records deleted? (y/n) [y]: ");
                String answer = Console.ReadLine();
                if (answer.StartsWith("y") ||
                    answer.StartsWith("Y") ||
                    answer == String.Empty)
                {
                    toBeDeleted = true;
                }
                else
                {
                    toBeDeleted = false;
                }
            }

            if (toBeDeleted)
            {
                // Deleting the accounts will delete all of their related records, and then
                // only the leads will be left.
                _serviceProxy.Delete(Account.EntityLogicalName, _accountId);
                _serviceProxy.Delete(Account.EntityLogicalName, _leadAccountId);

                _serviceProxy.Delete(Lead.EntityLogicalName, _lead1Id);
                _serviceProxy.Delete(Lead.EntityLogicalName, _lead2Id);
            }
        }
        /// <summary>
        /// Deletes any entity records that were created for this sample.
        /// <param name="prompt">Indicates whether to prompt the user
        /// to delete the records created in this sample.</param>
        /// </summary>
        public void DeleteRequiredRecords(bool prompt)
        {
            bool deleteRecords = true;

            if (prompt)
            {
                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)
            {
                SetStateRequest setStateRequest = new SetStateRequest()
                {
                    EntityMoniker =
                        new EntityReference(Workflow.EntityLogicalName, _workflowId),
                    State  = new OptionSetValue((int)WorkflowState.Draft),
                    Status = new OptionSetValue(1)
                };
                _serviceProxy.Execute(setStateRequest);

                _serviceProxy.Delete(Workflow.EntityLogicalName, _workflowId);
                _serviceProxy.Delete(Lead.EntityLogicalName, _leadId);
                _serviceProxy.Delete(AsyncOperation.EntityLogicalName, _asyncOperationId);
                Console.WriteLine("Entity records have been deleted.");
            }
        }
Example #6
0
        /// <summary>
        /// Deletes the entity record that was created for this sample.
        /// <param name="prompt">Indicates whether to prompt the user
        /// to delete the entity created in this sample.</param>
        /// </summary>
        public void DeleteRequiredRecords(bool prompt)
        {
            bool deleteRecords = true;

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

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

            if (deleteRecords)
            {
                // Delete action doesn't work on the UserQueryVisualization instance if it is assigned
                // to a user other than current user.
                // So as a workaround, we are impersonating the actual owner of
                // the UserQueryVisualization instance to complete the delete action.
                // To impersonate another user, set the OrganizationServiceProxy.CallerId
                // property to the ID of the other user.
                _serviceProxy.CallerId = _otherUserId;

                _serviceProxy.Delete(UserQueryVisualization.EntityLogicalName, _userOwnedVisualizationId);
                _serviceProxy.Delete(Account.EntityLogicalName, _accountId);
                Console.WriteLine("Entity records have been deleted.");
            }
        }
        /// <summary>
        /// Deletes any entity records that were created for this sample.
        /// <param name="prompt">Indicates whether to prompt the user to delete the records created in this sample.</param>
        /// </summary>
        public void DeleteRequiredRecords(bool prompt)
        {
            bool deleteRecords = true;

            if (prompt)
            {
                Console.WriteLine("\nDo you want these entity records deleted? (y/n)");
                String answer = Console.ReadLine();
                deleteRecords = (answer.StartsWith("y") || answer.StartsWith("Y"));
            }

            if (deleteRecords)
            {
                Console.WriteLine("Deleting entity records... please wait!");

                _serviceProxy.Delete(ProductAssociation.EntityLogicalName, _product1AssociationId);
                _serviceProxy.Delete(ProductAssociation.EntityLogicalName, _product2AssociationId);
                _serviceProxy.Delete(ProductPriceLevel.EntityLogicalName, _priceListItem1Id);
                _serviceProxy.Delete(ProductPriceLevel.EntityLogicalName, _priceListItem2Id);
                _serviceProxy.Delete(ProductPriceLevel.EntityLogicalName, _priceListItem3Id);
                _serviceProxy.Delete(Product.EntityLogicalName, _bundleId);
                _serviceProxy.Delete(Product.EntityLogicalName, _product1Id);
                _serviceProxy.Delete(Product.EntityLogicalName, _product2Id);
                _serviceProxy.Delete(PriceLevel.EntityLogicalName, _priceListId);
                _serviceProxy.Delete(UoMSchedule.EntityLogicalName, _unitGroupId);

                Console.WriteLine("Entity records have been deleted.");
            }
        }
Example #8
0
        /// <summary>
        /// Deletes/Reverts the record that was created/changed for this sample.
        /// <param name="prompt">Indicates whether to prompt the user to delete
        /// the records created in this sample.</param>
        /// </summary>
        public void DeleteRequiredRecords(bool prompt)
        {
            bool toBeDeleted = true;

            if (prompt)
            {
                // Ask the user if the created entities should be deleted.
                Console.Write("\nDo you want these entity records deleted? (y/n) [y]: ");
                String answer = Console.ReadLine();
                if (answer.StartsWith("y") ||
                    answer.StartsWith("Y") ||
                    answer == String.Empty)
                {
                    toBeDeleted = true;
                }
                else
                {
                    toBeDeleted = false;
                }
            }

            if (toBeDeleted)
            {
                // Delete all records created in this sample.
                for (int i = 0; i < _accountIdArray.Length; i++)
                {
                    _serviceProxy.Delete(Account.EntityLogicalName, _accountIdArray[i]);
                }
                _serviceProxy.Delete(List.EntityLogicalName, _newListId);
                _serviceProxy.Delete(BulkOperation.EntityLogicalName, _qcBOId);
                Console.WriteLine("Entity record(s) have been deleted.");
            }
        }
Example #9
0
        public void DeleteRequiredRecords(bool prompt)
        {
            bool toBeDeleted = true;

            if (prompt)
            {
                // Ask the user if the created entities should be deleted.
                Console.Write("\nDo you want these entity records deleted? (y/n) [y]: ");
                String answer = Console.ReadLine();
                if (answer.StartsWith("y") ||
                    answer.StartsWith("Y") ||
                    answer == String.Empty)
                {
                    toBeDeleted = true;
                }
                else
                {
                    toBeDeleted = false;
                }
            }

            if (toBeDeleted)
            {
                // Delete all records created in this sample.
                Console.WriteLine("Deleting the offline filter and offline template");
                _serviceProxy.Delete(SavedQuery.EntityLogicalName, _offlineFilter);
                _serviceProxy.Delete(SavedQuery.EntityLogicalName, _offlineTemplate);

                Console.WriteLine("Entity record(s) have been deleted.");
            }
        }
        /// <summary>
        /// Deletes any entity records that were created for this sample.
        /// <param name="prompt">Indicates whether to prompt the user
        /// to delete the records created in this sample.</param>
        /// </summary>
        public void DeleteRequiredRecords(bool prompt)
        {
            bool toBeDeleted = true;

            if (prompt)
            {
                // Ask the user if the created entities should be deleted.
                Console.Write("\nDo you want these entity records deleted? (y/n) [y]: ");
                String answer = Console.ReadLine();
                if (answer.StartsWith("y") ||
                    answer.StartsWith("Y") ||
                    answer == String.Empty)
                {
                    toBeDeleted = true;
                }
                else
                {
                    toBeDeleted = false;
                }
            }

            if (toBeDeleted)
            {
                _serviceProxy.Delete(Connection.EntityLogicalName, _connectionId);
                _serviceProxy.Delete(Account.EntityLogicalName, _accountId);
                _serviceProxy.Delete(Contact.EntityLogicalName, _contactId);
                _serviceProxy.Delete(ConnectionRole.EntityLogicalName, _connectionRoleId);

                Console.WriteLine("Entity records have been deleted.");
            }
        }
Example #11
0
        /// <summary>
        /// Update and delete records that this sample requires.
        /// </summary>
        public void UpdateRecords()
        {
            Console.WriteLine("Adding ten more records....");
            // Create another 10 Account records for demo.
            for (int i = 10; i < 20; i++)
            {
                Entity book = new Entity("sample_book");
                book["sample_name"]     = "Demo Book " + i.ToString();
                book["sample_bookcode"] = "BookCode" + i.ToString();
                book["sample_author"]   = "Author" + i.ToString();
                _serviceProxy.Create(book);
            }

            // Update a record.
            Console.WriteLine("Updating an existing record");
            Entity updatebook = new Entity(_customBooksEntityName.ToLower(), "sample_bookcode", "BookCode0");

            updatebook["sample_name"] = "Demo Book 0 updated";

            _serviceProxy.Update(updatebook);

            // Delete a record.
            Console.WriteLine("Deleting the {0} record....", bookIdtoDelete);
            _serviceProxy.Delete(_customBooksEntityName.ToLower(), bookIdtoDelete);
        }
        /// <summary>
        /// Deletes any entity records that were created for this sample.
        /// <param name="prompt">Indicates whether to prompt the user
        /// to delete the records created in this sample.</param>
        /// </summary>
        public void DeleteRequiredRecords(bool prompt)
        {
            bool toBeDeleted = true;

            if (prompt)
            {
                // Ask the user if the created entities should be deleted.
                Console.Write("\nDo you want these entity records deleted? (y/n) [y]: ");
                String answer = Console.ReadLine();
                if (answer.StartsWith("y") ||
                    answer.StartsWith("Y") ||
                    answer == String.Empty)
                {
                    toBeDeleted = true;
                }
                else
                {
                    toBeDeleted = false;
                }
            }

            if (toBeDeleted)
            {
                // Delete all records created in this sample.
                _serviceProxy.Delete(List.EntityLogicalName, _staticListId);
                _serviceProxy.Delete(List.EntityLogicalName, _dynamicListId);
                _serviceProxy.Delete("campaignactivity", _campaignActivityId);
                _serviceProxy.Delete("campaign", _campaignId);
                _serviceProxy.Delete("account", _accountId);

                Console.WriteLine("Entity record(s) have been deleted.");
            }
        }
Example #13
0
        /// <summary>
        /// Deletes any entity records that were created for this sample.
        /// <param name="prompt">Indicates whether to prompt the user to delete
        /// the records created in this sample.</param>
        /// </summary>
        public void DeleteRequiredRecords(bool prompt)
        {
            bool toBeDeleted = true;

            if (prompt)
            {
                // Ask the user if the created entities should be deleted.
                Console.Write("\nDo you want these entity records deleted? (y/n) [y]: ");
                String answer = Console.ReadLine();
                if (answer.StartsWith("y") ||
                    answer.StartsWith("Y") ||
                    answer == String.Empty)
                {
                    toBeDeleted = true;
                }
                else
                {
                    toBeDeleted = false;
                }
            }

            if (toBeDeleted)
            {
                _serviceProxy.Delete(Letter.EntityLogicalName, _letterId);
                _serviceProxy.Delete(Queue.EntityLogicalName, _sourceQueueId);
                _serviceProxy.Delete(Queue.EntityLogicalName, _destinationQueueId);

                Console.WriteLine("Entity records have been deleted.");
            }
        }
Example #14
0
        private void DeleteRequiredRecords(bool prompt)
        {
            bool toBeDeleted = true;

            if (prompt)
            {
                // Ask the user if the created entities should be deleted.
                Console.Write("\nDo you want these entity records deleted? (y/n) [y]: ");
                String answer = Console.ReadLine();
                if (answer.StartsWith("y") ||
                    answer.StartsWith("Y") ||
                    answer == String.Empty)
                {
                    toBeDeleted = true;
                }
                else
                {
                    toBeDeleted = false;
                }
            }

            if (toBeDeleted)
            {
                // Delete records created in this sample.
                _serviceProxy.Delete(Team.EntityLogicalName, _teamId);
                // Deleting the lead will delete its associated activities.
                _serviceProxy.Delete(Lead.EntityLogicalName, _leadId);

                Console.WriteLine("Entity record(s) have been deleted.");
            }
        }
Example #15
0
        private void DeleteRequiredRecords(bool prompt)
        {
            var toBeDeleted = true;

            if (prompt)
            {
                // Ask the user if the created entities should be deleted.
                Console.Write("\nDo you want these entity records deleted? (y/n) [y]: ");
                String answer = Console.ReadLine();
                if (answer.StartsWith("y") ||
                    answer.StartsWith("Y") ||
                    answer == String.Empty)
                {
                    toBeDeleted = true;
                }
                else
                {
                    toBeDeleted = false;
                }
            }

            if (toBeDeleted)
            {
                // Handle reverting the configurations appropriately - delete them
                // if they did not exist before.  Otherwise update them to their
                // original values.  Lead must be reverted first since it must be deleted
                // first if systemuser is to be deleted.
                RevertPostConfig(_originalLeadConfig, _leadConfig);
                RevertPostConfig(_originalSystemUserConfig, _systemuserConfig);

                // Revert the form changes.
                PublishSystemUserAndLead();

                // Delete the leads.
                DeleteFromContext(_lead1);
                DeleteFromContext(_lead2);
                DeleteFromContext(_lead3);
                var saveResult = _serviceContext.SaveChanges();
                Console.WriteLine("  The leads have been deleted.");

                Console.WriteLine("  The post follow records were deleted with the leads.");
                Console.WriteLine("  Posts that were related to leads were deleted with the leads.");

                // Delete posts that aren't regarding entities that were deleted.
                DeleteFromContext(_post1);
                DeleteFromContext(_post2);
                DeleteFromContext(_post3);
                DeleteFromContext(_post4);
                _serviceContext.SaveChanges();
                Console.WriteLine("  Posts that weren't regarding deleted entities were deleted.");

                // Delete the generated entities.
                foreach (var entityRef in _generatedEntities)
                {
                    _serviceProxy.Delete(entityRef.LogicalName, entityRef.Id);
                }
                Console.WriteLine("  All generated entities have been deleted.");
            }
        }
Example #16
0
        /// <summary>
        /// Deletes any entity records that were created for this sample.
        /// <param name="prompt">Indicates whether to prompt the user
        /// to delete the records created in this sample.</param>
        /// </summary>
        public void DeleteRequiredRecords(bool prompt)
        {
            // Two of the contracts, their associated account and the contract template
            // records that were created and used in this sample will continue to exist
            // on your system because contracts that have been invoiced cannot be deleted
            // in Microsoft Dynamics CRM. They can only be put on hold or canceled.

            bool toBeDeleted = true;

            if (prompt)
            {
                // Ask the user if the created entities should be deleted.
                Console.Write("\nDo you want these entity records deleted? (y/n) [y]: ");
                String answer = Console.ReadLine();
                if (answer.StartsWith("y") ||
                    answer.StartsWith("Y") ||
                    answer == String.Empty)
                {
                    toBeDeleted = true;
                }
                else
                {
                    toBeDeleted = false;
                }
            }

            if (toBeDeleted)
            {
                _serviceProxy.Delete(Contract.EntityLogicalName, _secondCloneId);
                _serviceProxy.Delete(Contract.EntityLogicalName, _renewedId);
                _serviceProxy.Delete(Contract.EntityLogicalName, _contractId);
                SetStateRequest setStateRequest = new SetStateRequest()
                {
                    EntityMoniker = new EntityReference
                    {
                        Id          = _firstCloneId,
                        LogicalName = Contract.EntityLogicalName
                    },
                    State  = new OptionSetValue((int)ContractState.Invoiced),
                    Status = new OptionSetValue(3)
                };
                _serviceProxy.Execute(setStateRequest);
                setStateRequest = new SetStateRequest()
                {
                    EntityMoniker = new EntityReference
                    {
                        Id          = _firstCloneId,
                        LogicalName = Contract.EntityLogicalName
                    },
                    State  = new OptionSetValue((int)ContractState.Canceled),
                    Status = new OptionSetValue(5)
                };
                _serviceProxy.Execute(setStateRequest);
                _serviceProxy.Delete(Contract.EntityLogicalName, _firstCloneId);
                _serviceProxy.Delete(Account.EntityLogicalName, _accountId);
                Console.WriteLine("Entity record(s) have been deleted.");
            }
        }
Example #17
0
        internal void DeleteProductInfo()
        {
            //取要刪除的產品系列與無產品系列的產品
            QueryExpression productsQuery = new QueryExpression
            {
                EntityName = "product",
                ColumnSet  = new ColumnSet("productid", "name"),
            };

            productsQuery.Criteria.AddCondition("name", ConditionOperator.Equal, "觸控面板烤爐");
            productsQuery.Criteria.AddCondition("name", ConditionOperator.Equal, "Single Product");
            productsQuery.Criteria.FilterOperator = LogicalOperator.Or;

            var products = _orgService.RetrieveMultiple(productsQuery).Entities;

            //刪除產品
            foreach (Product product in products)
            {
                onLog(string.Format("Get Delete Product Id => {0}", product.Id));
                _orgService.Delete(Product.EntityLogicalName, product.Id);
                onLog("Delete Product of Product Family Success :) ");
            }

            //取得要刪除的單位群組
            QueryExpression uomsQuery = new QueryExpression
            {
                EntityName = UoMSchedule.EntityLogicalName,
                ColumnSet  = new ColumnSet("uomscheduleid", "name"),
            };

            uomsQuery.Criteria.AddCondition("name", ConditionOperator.Equal, "觸控面板單位");

            var uoms = (UoMSchedule)_orgService.RetrieveMultiple(uomsQuery).Entities[0];

            //刪除單位群組
            onLog(string.Format("Get Delete UoMSchedule => {0}", uoms.Id));
            _orgService.Delete(UoMSchedule.EntityLogicalName, uoms.Id);
            onLog("Delete UoMSchedule Success :) ");

            //取得要刪除的售價表
            QueryExpression priceLevelQuery = new QueryExpression
            {
                EntityName = PriceLevel.EntityLogicalName,
                ColumnSet  = new ColumnSet("pricelevelid", "name"),
            };

            priceLevelQuery.Criteria.AddCondition("name", ConditionOperator.Equal, "觸控面板單位官網定價");

            var pricelevel = (PriceLevel)_orgService.RetrieveMultiple(priceLevelQuery).Entities[0];

            //刪除售價表
            onLog(string.Format("Get Delete PriceLevel => {0}", pricelevel.Id));
            _orgService.Delete(PriceLevel.EntityLogicalName, pricelevel.Id);
            onLog("Delete PriceLevel Success :) ");
        }
Example #18
0
        /// <summary>
        /// Deletes the custom entity record that was created for this sample.
        /// <param name="prompt">Indicates whether to prompt the user
        /// to delete the entity created in this sample.</param>
        /// </summary>
        public static void DeleteRequiredRecords(CrmServiceClient service, bool prompt)
        {
            bool deleteRecords = true;

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

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

            if (deleteRecords)
            {
                // TODO Delete entity records
                #region Delete incidents, accounts and units of measure

                _serviceProxy.Delete(Incident.EntityLogicalName, _incident.Id);

                _serviceProxy.Delete(Product.EntityLogicalName, _product.Id);

                _serviceProxy.Delete(Account.EntityLogicalName, _account.Id);

                _serviceProxy.Delete(UoMSchedule.EntityLogicalName, _uomSchedule.Id);

                #endregion

                #region Unpublish articles

                foreach (var article in _articles)
                {
                    _serviceProxy.Execute(new SetStateRequest
                    {
                        EntityMoniker = article.ToEntityReference(),
                        Status        = new OptionSetValue((int)kbarticle_statuscode.Unapproved),
                        State         = new OptionSetValue((int)KbArticleState.Unapproved)
                    });
                }

                #endregion

                #region Delete articles

                foreach (var article in _articles)
                {
                    _serviceProxy.Delete(KbArticle.EntityLogicalName, article.Id);
                }

                #endregion
                Console.WriteLine("Entity records have been deleted.");
            }
        }
Example #19
0
        /// <summary>
        /// Deletes records that were created in the sample.
        /// </summary>
        /// <param name="prompt">whether or not to prompt the user for deletion.</param>
        private void DeleteRecords(bool prompt)
        {
            var toBeDeleted = true;

            if (prompt)
            {
                // Ask the user if the created entities should be deleted.
                Console.Write("\nDo you want these entity records deleted? (y/n) [y]: ");
                String answer = Console.ReadLine();
                if (answer.StartsWith("y") ||
                    answer.StartsWith("Y") ||
                    answer == String.Empty)
                {
                    toBeDeleted = true;
                }
                else
                {
                    toBeDeleted = false;
                }
            }

            if (toBeDeleted)
            {
                // Delete the bulk delete operation so that it won't clutter the
                // database.
                _serviceProxy.Delete(
                    BulkDeleteOperation.EntityLogicalName, _bulkDeleteOperationId);

                var asyncOperationEntity = _serviceProxy.Retrieve(
                    AsyncOperation.EntityLogicalName,
                    _asyncOperationId,
                    new ColumnSet("statecode", "asyncoperationid"));
                var asyncOperation = asyncOperationEntity.ToEntity <AsyncOperation>();

                if (asyncOperation.StateCode != AsyncOperationState.Completed)
                {
                    // We have to update the AsyncOperation to be in a Completed state
                    // before we can delete it.
                    asyncOperation.StateCode = AsyncOperationState.Completed;
                    _serviceProxy.Update(asyncOperation);
                }

                _serviceProxy.Delete(
                    AsyncOperation.EntityLogicalName, _asyncOperationId);

                Console.WriteLine("  The AsyncOperation and BulkDeleteOperation have been deleted.");
            }
        }
Example #20
0
        /// <summary>
        /// Deletes any entity records that were created for this sample.
        /// <param name="prompt">Indicates whether to prompt the user
        /// to delete the records created in this sample.</param>
        /// </summary>
        public void DeleteRequiredRecords(bool prompt)
        {
            bool deleteRecords = true;

            if (prompt)
            {
                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)
            {
                // Deactivate the dialog, and then delete it.
                SetStateRequest deactivateRequest = new SetStateRequest
                {
                    EntityMoniker = new EntityReference(Workflow.EntityLogicalName, _dialogId),
                    State         = new OptionSetValue((int)WorkflowState.Draft),
                    Status        = new OptionSetValue(1),
                };
                _serviceProxy.Execute(deactivateRequest);
                _serviceProxy.Delete(Workflow.EntityLogicalName, _dialogId);
                Console.WriteLine("Entity records have been deleted.");
            }
        }
Example #21
0
        /// <summary>
        /// Delete all remaining entity records that were created by this sample.
        /// <param name="prompt">When true, the user is prompted whether
        /// the records created in this sample should be deleted; otherwise, false.</param>
        /// </summary>
        public void DeleteEntityRecords(OrganizationServiceProxy service,
                                        EntityReferenceCollection records, bool prompt)
        {
            bool deleteRecords = true;

            if (prompt)
            {
                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)
            {
                while (records.Count > 0)
                {
                    EntityReference entityRef = records[records.Count - 1];
                    Console.WriteLine("Deleting {0} '{1}' ...", entityRef.LogicalName, entityRef.Name);
                    service.Delete(entityRef.LogicalName, entityRef.Id);
                    records.Remove(entityRef);
                }

                Console.WriteLine("Entity records have been deleted.");
            }
        }
Example #22
0
        /// <summary>
        /// Create and configure the organization service proxy.
        /// Initiate the method to create any data that this sample requires.
        /// Delete a new queue instance.
        /// Optionally delete any entity records that were created for this sample.
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>

        /// </summary>
        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))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    CreateRequiredRecords();



                    //<snippetDeleteQueue1>
                    // Delete the queue instance.
                    _serviceProxy.Delete(Queue.EntityLogicalName, _queueId);

                    //</snippetDeleteQueue1>

                    Console.WriteLine("Deleted a queue instance.");
                }
            }
            // 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;
            }
        }
Example #23
0
        /// <summary>
        /// Deletes any entity records that were created for this sample.
        /// <param name="prompt">Indicates whether to prompt the user
        /// to delete the records created in this sample.</param>
        /// </summary>
        public void DeleteRequiredRecords(bool prompt)
        {
            bool toBeDeleted = true;

            if (prompt)
            {
                // Ask the user if the created entities should be deleted.
                Console.Write("\nDo you want these entity records deleted? (y/n) [y]: ");
                String answer = Console.ReadLine();
                if (answer.StartsWith("y") ||
                    answer.StartsWith("Y") ||
                    answer == String.Empty)
                {
                    toBeDeleted = true;
                }
                else
                {
                    toBeDeleted = false;
                }
            }

            if (toBeDeleted)
            {
                // Delete the workflow.
                _serviceProxy.Delete(Workflow.EntityLogicalName, _workflowId);
                Console.WriteLine("The workflow has been deleted.");
            }
        }
Example #24
0
        /// <summary>
        /// Deletes the entity record that was created for this sample.
        /// <param name="prompt">Indicates whether to prompt the user
        /// to delete the entity created in this sample.</param>
        /// The system user named "Kevin Cook" that was created by this sample will
        /// continue to exist on your system because system users cannot be deleted
        /// in Microsoft Dynamics CRM. They can only be enabled or disabled.

        /// </summary>
        public void DeleteRequiredRecords(bool prompt)
        {
            if (!prompt)
            {
                return;
            }

            // Ask the user if the created entities should be deleted.
            Console.Write("\nDo you want these entity records deleted? (y/n) [y]: ");
            String answer = Console.ReadLine();

            if (answer.StartsWith("y") || answer.StartsWith("Y") || answer == String.Empty)
            {
                // Delete action doesn't work on the UserForm instance if it is assigned
                // to a user other than current user.
                // So as a workaround, we are impersonating the actual owner of
                // the UserForm instance to complete the delete action.
                // To impersonate another user, set the OrganizationServiceProxy.CallerId
                // property to the ID of the other user.
                _serviceProxy.CallerId = _otherUserId;

                _serviceProxy.Delete(UserForm.EntityLogicalName, _userDashboardId);
                Console.WriteLine("Entity records have been deleted.");
            }
        }
Example #25
0
        private void DeleteRecords(bool prompt)
        {
            bool toBeDeleted = true;

            if (prompt)
            {
                // Ask the user if the created entities should be deleted.
                Console.Write("\nDo you want these entity records deleted? (y/n) [y]: ");
                String answer = Console.ReadLine();
                if (answer.StartsWith("y") ||
                    answer.StartsWith("Y") ||
                    answer == String.Empty)
                {
                    toBeDeleted = true;
                }
                else
                {
                    toBeDeleted = false;
                }
            }

            if (toBeDeleted)
            {
                // The account is all that needs to be deleted.  Everything else will be
                // deleted with it.
                _serviceProxy.Delete(Account.EntityLogicalName, _accountId);
            }
        }
Example #26
0
        /// <summary>
        /// Deletes any entity records that were created for this sample.
        /// <param name="prompt">Indicates whether to prompt the user to delete
        /// the records created in this sample.</param>
        /// </summary>
        public void DeleteRequiredRecords(bool prompt)
        {
            bool deleteRecords = true;

            if (prompt)
            {
                Console.WriteLine("\nDo you want the records to be deleted? (y/n)");
                String answer = Console.ReadLine();

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

            if (deleteRecords)
            {
                _serviceProxy.Delete(Report.EntityLogicalName, _reportId);

                /* There is no need to delete these records because deleting the report will delete all related records.
                 * _serviceProxy.Delete(ReportCategory.EntityLogicalName, _reportCategoryId);
                 * _serviceProxy.Delete(ReportEntity.EntityLogicalName, _reportEntityId);
                 * _serviceProxy.Delete(ReportLink.EntityLogicalName, _reportLinkId);
                 * _serviceProxy.Delete(ReportVisibility.EntityLogicalName, _reportVisibilityId1);
                 * _serviceProxy.Delete(ReportVisibility.EntityLogicalName, _reportVisibilityId2);
                 * _serviceProxy.Delete(ReportVisibility.EntityLogicalName, _reportVisibilityId3);
                 */
                Console.WriteLine("Entity records have been deleted.");
            }
        }
Example #27
0
        private bool MigrateEntityToLocal(OrganizationServiceProxy localProxy, BinaryStorageOptions.Providers.IBinaryStorageProvider storageProvider, Entity entity, string entityName, string documentBodyKey, string filenameKey)
        {
            if (!entity.Attributes.ContainsKey(documentBodyKey))
            {
                return(true);
            }

            string filename = (string)entity.Attributes[filenameKey];

            Notify(string.Format("Migrating '{0}' with filename '{1}' External -> CRM using {2}.", entityName, entity.Id.ToString() + "_" + filename, storageProvider.GetType().Name));
            if ((string)entity.Attributes[documentBodyKey] == GenericConstants.EmptyBodyContent)
            {
                byte[] data = storageProvider.Read(entity.Id, filename);
                entity.Attributes[documentBodyKey] = Convert.ToBase64String(data);
                localProxy.Update(entity);

                var query = new QueryExpression(GenericConstants.AttachementExtensionEntityName);
                query.ColumnSet = new ColumnSet(false);
                query.Criteria  = new FilterExpression(LogicalOperator.And);
                query.Criteria.AddCondition(GenericConstants.AttachementExtensionEntityNameKey, ConditionOperator.Equal, entity.LogicalName);
                query.Criteria.AddCondition(GenericConstants.AttachementExtensionEntityIdKey, ConditionOperator.Equal, entity.Id.ToString());
                DataCollection <Entity> attachementExtensionEntities = localProxy.RetrieveMultiple(query).Entities;
                if (attachementExtensionEntities != null)
                {
                    foreach (var attachementExtensionEntity in attachementExtensionEntities)
                    {
                        localProxy.Delete(attachementExtensionEntity.LogicalName, attachementExtensionEntity.Id);
                    }
                }
            }
            storageProvider.Delete(entity.Id, filename);
            Notify(string.Format("Migration of '{0}' with id '{1}' DONE.", entityName, entity.Id.ToString() + "_" + filename));
            return(true);
        }
        /// <summary>
        /// Deletes any entity records that were created for this sample.
        /// <param name="prompt">Indicates whether to prompt the user
        /// to delete the records created in this sample.</param>
        /// </summary>
        public void DeleteRequiredRecords(bool prompt)
        {
            bool toBeDeleted = true;

            if (prompt)
            {
                // Ask the user if the created entities should be deleted.
                Console.Write("\nDo you want these entity records deleted? (y/n) [y]: ");
                String answer = Console.ReadLine();
                if (answer.StartsWith("y") ||
                    answer.StartsWith("Y") ||
                    answer == String.Empty)
                {
                    toBeDeleted = true;
                }
                else
                {
                    toBeDeleted = false;
                }
            }

            if (toBeDeleted)
            {
                // Delete the leads
                foreach (Lead lead in _leads)
                {
                    _serviceProxy.Delete(Lead.EntityLogicalName, lead.Id);
                }
                Console.WriteLine("Entity records have been deleted.");
            }
        }
Example #29
0
        /// <summary>
        /// Create and configure the organization service proxy.
        /// Initiate the method to create any data that this sample requires.
        /// Delete a new queue instance.
        /// Optionally delete any entity records that were created for this sample.
        /// <param name="serverConfig">Contains server connection information.</param>
        /// <param name="promptforDelete">When True, the user will be prompted to delete all
        /// created entities.</param>

        /// </summary>
        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))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    CreateRequiredRecords();



                    //<snippetDeleteQueue1> 			
                    // Delete the queue instance.
                    _serviceProxy.Delete(Queue.EntityLogicalName, _queueId);

                    //</snippetDeleteQueue1>

                    Console.WriteLine("Deleted a queue instance.");
                }
            }
            // 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;
            }
        }
Example #30
0
        /// <summary>
        /// Deletes any entity records that were created for this sample.
        /// <param name="prompt">Indicates whether to prompt the user
        /// to delete the records created in this sample.</param>
        /// </summary>
        public void DeleteRequiredRecords(bool prompt)
        {
            bool toBeDeleted = true;

            if (prompt)
            {
                // Ask the user if the created entities should be deleted.
                Console.Write("\nDo you want these entity records deleted? (y/n) [y]: ");
                String answer = Console.ReadLine();
                if (answer.StartsWith("y") ||
                    answer.StartsWith("Y") ||
                    answer == String.Empty)
                {
                    toBeDeleted = true;
                }
                else
                {
                    toBeDeleted = false;
                }
            }

            if (toBeDeleted)
            {
                // Deactivate and delete workflow
                SetStateRequest deactivateRequest = new SetStateRequest
                {
                    EntityMoniker = new EntityReference(Workflow.EntityLogicalName, _workflowId),
                    State         = new OptionSetValue((int)WorkflowState.Draft),
                    Status        = new OptionSetValue((int)workflow_statuscode.Draft)
                };
                _serviceProxy.Execute(deactivateRequest);
                _serviceProxy.Delete(Workflow.EntityLogicalName, _workflowId);
                Console.WriteLine("Workflow has been deactivated and deleted.");
            }
        }
        /// <summary>
        /// Deletes the managed solution that was created for this sample.
        /// <param name="prompt"> Indicates whether to prompt the user to delete
        /// the solution created in this sample.</param>
        /// If you choose "y", the managed solution will be deleted including the
        /// sample_product entity and all the data in the entity.
        /// If you choose "n", you must delete the solution manually to return
        /// your organization to the original state.
        /// </summary>
        public void DeleteUpsertSampleSolution(bool prompt)
        {
            bool deleteSolution = true;

            if (prompt)
            {
                Console.WriteLine("\nDo you want to delete the Upsert Sample solution? (y/n)");
                String answer = Console.ReadLine();

                deleteSolution = (answer.StartsWith("y") || answer.StartsWith("Y"));
            }
            if (deleteSolution)
            {
                Console.WriteLine("Deleting the {0} solution....", "Upsert Sample");
                QueryExpression queryImportedSolution = new QueryExpression
                {
                    EntityName = Solution.EntityLogicalName,
                    ColumnSet  = new ColumnSet(new string[] { "solutionid", "friendlyname" }),
                    Criteria   = new FilterExpression()
                };
                queryImportedSolution.Criteria.AddCondition("uniquename", ConditionOperator.Equal, "UpsertSample");

                Solution ImportedSolution = (Solution)_serviceProxy.RetrieveMultiple(queryImportedSolution).Entities[0];

                _serviceProxy.Delete(Solution.EntityLogicalName, (Guid)ImportedSolution.SolutionId);

                Console.WriteLine("Deleted the {0} solution.", ImportedSolution.FriendlyName);
            }
        }
Example #32
0
        /// <summary>
        /// Delete all remaining entity records that were created by this sample.
        /// <param name="prompt">When true, the user is prompted whether 
        /// the records created in this sample should be deleted; otherwise, false.</param>
        /// </summary>
        public void DeleteEntityRecords(OrganizationServiceProxy service,
                                        EntityReferenceCollection records, bool prompt)
        {
            bool deleteRecords = true;

            if (prompt)
            {
                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)
            {
                while (records.Count > 0)
                {
                    EntityReference entityRef = records[records.Count - 1];
                    Console.WriteLine("Deleting {0} '{1}' ...", entityRef.LogicalName, entityRef.Name);
                    service.Delete(entityRef.LogicalName, entityRef.Id);
                    records.Remove(entityRef);
                }

                Console.WriteLine("Entity records have been deleted.");
            }
        }
        /// <summary>
        /// This method connects to the Organization service using an impersonated user
        /// credential. Afterwards, basic create, retrieve, update, and delete entity
        /// operations are performed as the impersonated user.
        /// </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
            {
                //<snippetImpersonateWithOnBehalfOfPrivilege1>
                //<snippetImpersonateWithOnBehalfOfPrivilege2>
                // Connect to the Organization service. 
                // The using statement ensures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    CreateRequiredRecords();

                    // Retrieve the system user ID of the user to impersonate.
                    OrganizationServiceContext orgContext = new OrganizationServiceContext(_serviceProxy);
                    _userId = (from user in orgContext.CreateQuery<SystemUser>()
                              where user.FullName == "Kevin Cook"
                              select user.SystemUserId.Value).FirstOrDefault();

                    // To impersonate another user, set the OrganizationServiceProxy.CallerId
                    // property to the ID of the other user.
                    _serviceProxy.CallerId = _userId;

                    // Instantiate an account object.
                    // See the Entity Metadata topic in the SDK documentation to determine 
                    // which attributes must be set for each entity.
                    Account account = new Account { Name = "Fourth Coffee" };

                    // Create an account record named Fourth Coffee.
                    _accountId = _serviceProxy.Create(account);
                    Console.Write("{0} {1} created, ", account.LogicalName, account.Name);
                    //</snippetImpersonateWithOnBehalfOfPrivilege2>

                    // Retrieve the account containing several of its attributes.
                    // CreatedBy should reference the impersonated SystemUser.
                    // CreatedOnBehalfBy should reference the running SystemUser.
                    ColumnSet cols = new ColumnSet(
                        "name",
                        "createdby",
                        "createdonbehalfby",
                        "address1_postalcode",
                        "lastusedincampaign");

                    Account retrievedAccount =
                        (Account)_serviceProxy.Retrieve(Account.EntityLogicalName,
                            _accountId, cols);
                    Console.Write("retrieved, ");

                    // Update the postal code attribute.
                    retrievedAccount.Address1_PostalCode = "98052";

                    // The address 2 postal code was set accidentally, so set it to null.
                    retrievedAccount.Address2_PostalCode = null;

                    // Shows use of a Money value.
                    retrievedAccount.Revenue = new Money(5000000);

                    // Shows use of a boolean value.
                    retrievedAccount.CreditOnHold = false;

                    // Update the account record.
                    _serviceProxy.Update(retrievedAccount);
                    Console.Write("updated, ");

                    // Delete the account record.
                    _serviceProxy.Delete(Account.EntityLogicalName, _accountId);
                    Console.WriteLine("and deleted.");

                    DeleteRequiredRecords(promptforDelete);
                }
                //</snippetImpersonateWithOnBehalfOfPrivilege1>
            }

            // 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;
            }
        }
Example #34
0
        /// <summary>
        /// Shows how to perform the following tasks with solutions:
        /// - Create a Publisher
        /// - Retrieve the Default Publisher
        /// - Create a Solution
        /// - Retrieve a Solution
        /// - Add an existing Solution Component
        /// - Remove a Solution Component
        /// - Export or Package a Solution
        /// - Install or Upgrade a solution
        /// - Delete a Solution
        /// </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))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    // Call the method to create any data that this sample requires.
                    CreateRequiredRecords();
                    //<snippetWorkWithSolutions1>


                    //Define a new publisher
                    Publisher _crmSdkPublisher = new Publisher
                    {
                        UniqueName = "sdksamples",
                        FriendlyName = "Microsoft CRM SDK Samples",
                        SupportingWebsiteUrl = "http://msdn.microsoft.com/en-us/dynamics/crm/default.aspx",
                        CustomizationPrefix = "sample",
                        EMailAddress = "*****@*****.**",
                        Description = "This publisher was created with samples from the Microsoft Dynamics CRM SDK"
                    };

                    //Does publisher already exist?
                    QueryExpression querySDKSamplePublisher = new QueryExpression
                    {
                        EntityName = Publisher.EntityLogicalName,
                        ColumnSet = new ColumnSet("publisherid", "customizationprefix"),
                        Criteria = new FilterExpression()
                    };

                    querySDKSamplePublisher.Criteria.AddCondition("uniquename", ConditionOperator.Equal, _crmSdkPublisher.UniqueName);
                    EntityCollection querySDKSamplePublisherResults = _serviceProxy.RetrieveMultiple(querySDKSamplePublisher);
                    Publisher SDKSamplePublisherResults = null;

                    //If it already exists, use it
                    if (querySDKSamplePublisherResults.Entities.Count > 0)
                    {
                        SDKSamplePublisherResults = (Publisher)querySDKSamplePublisherResults.Entities[0];
                        _crmSdkPublisherId = (Guid)SDKSamplePublisherResults.PublisherId;
                        _customizationPrefix = SDKSamplePublisherResults.CustomizationPrefix;
                    }
                    //If it doesn't exist, create it
                    if (SDKSamplePublisherResults == null)
                    {
                        _crmSdkPublisherId = _serviceProxy.Create(_crmSdkPublisher);
                        Console.WriteLine(String.Format("Created publisher: {0}.", _crmSdkPublisher.FriendlyName));
                        _customizationPrefix = _crmSdkPublisher.CustomizationPrefix;
                    }



                    //</snippetWorkWithSolutions1>

                    //<snippetWorkWithSolutions2>
                    // Retrieve the Default Publisher

                    //The default publisher has a constant GUID value;
                    Guid DefaultPublisherId = new Guid("{d21aab71-79e7-11dd-8874-00188b01e34f}");

                    Publisher DefaultPublisher = (Publisher)_serviceProxy.Retrieve(Publisher.EntityLogicalName, DefaultPublisherId, new ColumnSet(new string[] {"friendlyname" }));

                    EntityReference DefaultPublisherReference = new EntityReference
                    {
                        Id = DefaultPublisher.Id,
                        LogicalName = Publisher.EntityLogicalName,
                        Name = DefaultPublisher.FriendlyName
                    };
                    Console.WriteLine("Retrieved the {0}.", DefaultPublisherReference.Name);
                    //</snippetWorkWithSolutions2>

                    //<snippetWorkWithSolutions3>
                    // Create a Solution
                    //Define a solution
                    Solution solution = new Solution
                    {
                        UniqueName = "samplesolution",
                        FriendlyName = "Sample Solution",
                        PublisherId = new EntityReference(Publisher.EntityLogicalName, _crmSdkPublisherId),
                        Description = "This solution was created by the WorkWithSolutions sample code in the Microsoft Dynamics CRM SDK samples.",
                        Version = "1.0"
                    };

                    //Check whether it already exists
                    QueryExpression queryCheckForSampleSolution = new QueryExpression
                    {
                        EntityName = Solution.EntityLogicalName,
                        ColumnSet = new ColumnSet(),
                        Criteria = new FilterExpression()
                    };
                    queryCheckForSampleSolution.Criteria.AddCondition("uniquename", ConditionOperator.Equal, solution.UniqueName);

                    //Create the solution if it does not already exist.
                    EntityCollection querySampleSolutionResults = _serviceProxy.RetrieveMultiple(queryCheckForSampleSolution);
                    Solution SampleSolutionResults = null;
                    if (querySampleSolutionResults.Entities.Count > 0)
                    {
                        SampleSolutionResults = (Solution)querySampleSolutionResults.Entities[0];
                        _solutionsSampleSolutionId = (Guid)SampleSolutionResults.SolutionId;
                    }
                    if (SampleSolutionResults == null)
                    {
                        _solutionsSampleSolutionId = _serviceProxy.Create(solution);
                    }
                    //</snippetWorkWithSolutions3>

                    //<snippetWorkWithSolutions4>
                    // Retrieve a solution
                    String solutionUniqueName = "samplesolution";
                    QueryExpression querySampleSolution = new QueryExpression
                    {
                        EntityName = Solution.EntityLogicalName,
                        ColumnSet = new ColumnSet(new string[] { "publisherid", "installedon", "version", "versionnumber", "friendlyname" }),
                        Criteria = new FilterExpression()
                    };

                    querySampleSolution.Criteria.AddCondition("uniquename", ConditionOperator.Equal, solutionUniqueName);
                    Solution SampleSolution = (Solution)_serviceProxy.RetrieveMultiple(querySampleSolution).Entities[0];
                    //</snippetWorkWithSolutions4>

                    //<snippetWorkWithSolutions5>
                    // Add an existing Solution Component
                    //Add the Account entity to the solution
                    RetrieveEntityRequest retrieveForAddAccountRequest = new RetrieveEntityRequest()
                    {
                        LogicalName = Account.EntityLogicalName
                    };
                    RetrieveEntityResponse retrieveForAddAccountResponse = (RetrieveEntityResponse)_serviceProxy.Execute(retrieveForAddAccountRequest);
                    AddSolutionComponentRequest addReq = new AddSolutionComponentRequest()
                    {
                        ComponentType = (int)componenttype.Entity,
                        ComponentId = (Guid)retrieveForAddAccountResponse.EntityMetadata.MetadataId,
                        SolutionUniqueName = solution.UniqueName
                    };
                    _serviceProxy.Execute(addReq);
                    //</snippetWorkWithSolutions5>

                    //<snippetWorkWithSolutions6>
                    // Remove a Solution Component
                    //Remove the Account entity from the solution
                    RetrieveEntityRequest retrieveForRemoveAccountRequest = new RetrieveEntityRequest()
                    {
                        LogicalName = Account.EntityLogicalName
                    };
                    RetrieveEntityResponse retrieveForRemoveAccountResponse = (RetrieveEntityResponse)_serviceProxy.Execute(retrieveForRemoveAccountRequest);

                    RemoveSolutionComponentRequest removeReq = new RemoveSolutionComponentRequest()
                    {
                        ComponentId = (Guid)retrieveForRemoveAccountResponse.EntityMetadata.MetadataId,
                        ComponentType = (int)componenttype.Entity,
                        SolutionUniqueName = solution.UniqueName
                    };
                    _serviceProxy.Execute(removeReq);
                    //</snippetWorkWithSolutions6>

                    //<snippetWorkWithSolutions7>
                    // Export or package a solution
                    //Export an a solution
                    
                    ExportSolutionRequest exportSolutionRequest = new ExportSolutionRequest();
                    exportSolutionRequest.Managed = false;
                    exportSolutionRequest.SolutionName = solution.UniqueName;

                    ExportSolutionResponse exportSolutionResponse = (ExportSolutionResponse)_serviceProxy.Execute(exportSolutionRequest);

                    byte[] exportXml = exportSolutionResponse.ExportSolutionFile;
                    string filename = solution.UniqueName + ".zip";
                    File.WriteAllBytes(outputDir + filename, exportXml);

                    Console.WriteLine("Solution exported to {0}.", outputDir + filename);
                    //</snippetWorkWithSolutions7>

                    //<snippetWorkWithSolutions8>
                    // Install or Upgrade a Solution                  
                    
                    byte[] fileBytes = File.ReadAllBytes(ManagedSolutionLocation);

                    ImportSolutionRequest impSolReq = new ImportSolutionRequest()
                    {
                        CustomizationFile = fileBytes
                    };

                    _serviceProxy.Execute(impSolReq);

                    Console.WriteLine("Imported Solution from {0}", ManagedSolutionLocation);
                    //</snippetWorkWithSolutions8>

                  
                    //<snippetWorkWithSolutions9>
                    // Monitor import success
                    byte[] fileBytesWithMonitoring = File.ReadAllBytes(ManagedSolutionLocation);

                    ImportSolutionRequest impSolReqWithMonitoring = new ImportSolutionRequest()
                    {
                        CustomizationFile = fileBytes,
                        ImportJobId = Guid.NewGuid()
                    };
                    
                    _serviceProxy.Execute(impSolReqWithMonitoring);
                    Console.WriteLine("Imported Solution with Monitoring from {0}", ManagedSolutionLocation);

                    ImportJob job = (ImportJob)_serviceProxy.Retrieve(ImportJob.EntityLogicalName, impSolReqWithMonitoring.ImportJobId, new ColumnSet(new System.String[] { "data", "solutionname" }));
                    

                    System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                    doc.LoadXml(job.Data);

                    String ImportedSolutionName = doc.SelectSingleNode("//solutionManifest/UniqueName").InnerText;
                    String SolutionImportResult = doc.SelectSingleNode("//solutionManifest/result/@result").Value;

                    Console.WriteLine("Report from the ImportJob data");
                    Console.WriteLine("Solution Unique name: {0}", ImportedSolutionName);
                    Console.WriteLine("Solution Import Result: {0}", SolutionImportResult);
                    Console.WriteLine("");

                    // This code displays the results for Global Option sets installed as part of a solution.

                    System.Xml.XmlNodeList optionSets = doc.SelectNodes("//optionSets/optionSet");
                    foreach (System.Xml.XmlNode node in optionSets)
                    {
                        string OptionSetName = node.Attributes["LocalizedName"].Value;
                        string result = node.FirstChild.Attributes["result"].Value;

                        if (result == "success")
                        {
                            Console.WriteLine("{0} result: {1}",OptionSetName, result);
                        }
                        else
                        {
                            string errorCode = node.FirstChild.Attributes["errorcode"].Value;
                            string errorText = node.FirstChild.Attributes["errortext"].Value;

                            Console.WriteLine("{0} result: {1} Code: {2} Description: {3}",OptionSetName, result, errorCode, errorText);
                        }
                    }

                    //</snippetWorkWithSolutions9>

                    //<snippetWorkWithSolutions10>
                    // Delete a solution

                    QueryExpression queryImportedSolution = new QueryExpression
                    {
                        EntityName = Solution.EntityLogicalName,
                        ColumnSet = new ColumnSet(new string[] { "solutionid", "friendlyname" }),
                        Criteria = new FilterExpression()
                    };


                    queryImportedSolution.Criteria.AddCondition("uniquename", ConditionOperator.Equal, ImportedSolutionName);

                    Solution ImportedSolution = (Solution)_serviceProxy.RetrieveMultiple(queryImportedSolution).Entities[0];

                    _serviceProxy.Delete(Solution.EntityLogicalName, (Guid)ImportedSolution.SolutionId);

                    Console.WriteLine("Deleted the {0} solution.", ImportedSolution.FriendlyName);

                    //</snippetWorkWithSolutions10>



                    DeleteRequiredRecords(promptForDelete);
                }
            }

            // 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;
            }
        }
        /// <summary>
        /// This method first creates 3 users, a team, 4 leads and a business unit. 
        /// It assigns two users to the team, and gives each user and the team a lead. 
        /// Then it reassigns all the leads from one of the users to another user using 
        /// the ReassignObjectsSystemUserRequest. Next, it reassigns all the leads from
        /// the team to a user using the ReassignObjectsOwnerRequest. Third, it reassigns
        /// one user from the root business unit to the created business unit, using the
        /// SetBusinessSystemUserRequest message. Fourth, it reassigns all users from 
        /// the created business unit to the root business unit and deletes the created 
        /// business unit. Finally, it removes all users from the created team and 
        /// deletes the team.
        /// </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
            {
//<snippetReassignBusinessUnitMembers1>
                // 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))
                // Using the ServiceContext class provides access to the LINQ provider
                using (_context = new ServiceContext(_serviceProxy))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    CreateRequiredRecords();

                    Console.WriteLine();
                    PrintLeads();

                    var users = from user in _context.SystemUserSet
                                    select new { user.FullName, user.Id };
                    Dictionary<Guid, String> userMapping = new Dictionary<Guid,String>();
                    foreach (var user in users)
                        userMapping.Add(user.Id, user.FullName);

                    #region ReassignObjectsSystemUserRequest
                    
                    // create the request
                    ReassignObjectsSystemUserRequest reassignRequest = 
                        new ReassignObjectsSystemUserRequest()
                    {
                        ReassignPrincipal = 
                            new EntityReference(SystemUser.EntityLogicalName, _users[1]),
                        UserId = _users[2]
                    };

                    // execute the request
                    Console.WriteLine();
                    Console.WriteLine(
                        "  Reassigning leads from {0} to {1}", 
                        userMapping[_users[2]],
                        userMapping[_users[1]]);
                    _serviceProxy.Execute(reassignRequest);
                    
                    // check results
                    PrintLeads();

                    #endregion

                    #region ReassignObjectsOwnerRequest

                    // create the request
                    ReassignObjectsOwnerRequest request = 
                        new ReassignObjectsOwnerRequest()
                    {
                        FromPrincipal = _team.ToEntityReference(),
                        ToPrincipal = 
                            new EntityReference(SystemUser.EntityLogicalName, _users[0])
                    };

                    // execute the request
                    Console.WriteLine();
                    Console.WriteLine(
                        "  Reassigning leads from {0} to {1}", 
                        _team.Name, userMapping[_users[0]]);
                    _serviceProxy.Execute(request);

                    // check results
                    PrintLeads();

                    #endregion

                    #region reassign business unit members

                    Console.WriteLine();
                    Console.WriteLine("  Adding a user to the created business unit");
                    // track what permissions the user had before reassigning to the new
                    // business unit so that the permissions can be restored when the
                    // user is assigned back to the business unit
                    _originalRolesIds = new List<Guid>();
                    var roleIds = from user in _context.SystemUserSet
                                  join systemuserrole in _context.SystemUserRolesSet 
                                    on user.SystemUserId equals systemuserrole.SystemUserId
                                  join role in _context.RoleSet 
                                    on systemuserrole.RoleId equals role.RoleId
                                  where user.SystemUserId.Value == _users[2]
                                  select role.RoleId.Value;

                    foreach (var roleId in roleIds)
                        _originalRolesIds.Add(roleId);

                    // add user to the created business unit
                    _serviceProxy.Execute(new SetBusinessSystemUserRequest()
                    {
                        BusinessId = _buisnessUnit.Id,
                        ReassignPrincipal = new EntityReference(
                            SystemUser.EntityLogicalName,
                            _users[2]),
                        UserId = _users[2]
                    });

                    #endregion

                    #region delete business unit

                    Console.WriteLine();
                    Console.WriteLine("  Deleting created business unit");

                    // remove all users from the business unit, moving them back to the
                    // parent business unit
                    _serviceProxy.Execute(new SetBusinessSystemUserRequest()
                    {
                        BusinessId = _rootBusinessUnit.Id,
                        ReassignPrincipal = new EntityReference(
                            SystemUser.EntityLogicalName, _users[2]),
                        UserId = _users[2]
                    });

                    // give the user back their original security roles
                    foreach (var roleId in roleIds)
                    {
                        _serviceProxy.Associate(
                             SystemUser.EntityLogicalName,
                             _users[2],
                             new Relationship("systemuserroles_association"),
                             new EntityReferenceCollection() { 
                                new EntityReference(
                                    Role.EntityLogicalName,
                                    roleId
                                )
                            }
                         );
                    }

                    // deactivate business unit before deleting it
                    _serviceProxy.Execute(new SetStateRequest()
                    {
                        EntityMoniker = _buisnessUnit.ToEntityReference(),
                        // mark the state as inactive (value 1)
                        State = new OptionSetValue(1),
                        Status = new OptionSetValue(-1)
                    });

                    // delete business unit
                    _serviceProxy.Delete(BusinessUnit.EntityLogicalName,
                        _buisnessUnit.Id);

                    #endregion

                    #region remove users from team

                    var teamMembers = from team in _context.TeamSet
                                      join membership in _context.TeamMembershipSet
                                      on team.TeamId equals membership.TeamId
                                      where team.TeamId == _team.Id
                                      select membership.SystemUserId.Value;

                    _serviceProxy.Execute(new RemoveMembersTeamRequest()
                    {
                        MemberIds = teamMembers.ToArray(),
                        TeamId = _team.Id
                    });

                    #endregion

                    #region delete team

                    Console.WriteLine();
                    Console.WriteLine("  Deleting the team");

                    // Delete the team
                    _serviceProxy.Delete(Team.EntityLogicalName, _team.Id);

                    #endregion

                    DeleteRequiredRecords(promptforDelete);
                }
	 //</snippetReassignBusinessUnitMembers1>
           }

            // 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;
            }
        }
        /// <summary>
        /// This sample creates a role that is not linked to any entity type. All
        /// connection roles that apply to all are found and shown. Then the role is
        /// linked to the account entity and it is demonstrated that the role only works
        /// for accounts at this point, not for all. Subsequently the link to the account
        /// entity is removed and it is shown that the role is now applicable to all 
        /// entities again.
        /// </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
            {
                //<snippetQueryConnectionRolesByEntityTypeCode1>
                // 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))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    // Define some anonymous types to define the range 
                    // of possible connection property values.
                    var Categories = new
                    {
                        Business = 1,
                        Family = 2,
                        Social = 3,
                        Sales = 4,
                        Other = 5
                    };

                    // Create a Connection Role.
                    ConnectionRole setupConnectionRole = new ConnectionRole
                    {
                        Name = "Example Connection Role",
                        Category = new OptionSetValue(Categories.Business),
                    };

                    _connectionRoleId = _serviceProxy.Create(setupConnectionRole);
                    setupConnectionRole.Id = _connectionRoleId;

                    Console.WriteLine("Created {0}.", setupConnectionRole.Name);

                    // Query for all Connection Roles.
                    QueryExpression allQuery = new QueryExpression
                    {
                        EntityName = ConnectionRole.EntityLogicalName,
                        ColumnSet = new ColumnSet("connectionroleid", "name"),
                        Distinct = true,
                        LinkEntities = 
                        {
                            new LinkEntity
                            {
                                LinkToEntityName = 
                                ConnectionRoleObjectTypeCode.EntityLogicalName,
                                LinkToAttributeName = "connectionroleid",
                                LinkFromEntityName = ConnectionRole.EntityLogicalName,
                                LinkFromAttributeName = "connectionroleid",
                                LinkCriteria = new FilterExpression
                                {
                                    FilterOperator = LogicalOperator.And,
                                    // Set a condition to only get connection roles  
                                    // related to all entities (object type code = 0).
                                    Conditions = 
                                    {
                                        new ConditionExpression 
                                        {
                                             AttributeName = "associatedobjecttypecode",
                                             Operator = ConditionOperator.Equal,
                                             Values = { 0 }
                                        }
                                    }
                                }
                            }
                        }
                    };

                    EntityCollection results = _serviceProxy.RetrieveMultiple(allQuery);

                    // Here you could perform operations on all of 
                    // the connectionroles found by the query.

                    Console.WriteLine("Retrieved {0} unassociated connectionrole instance(s).",
                        results.Entities.Count);

                    // Query to find roles which apply only to accounts.
                    QueryExpression accountQuery = new QueryExpression
                    {
                        EntityName = ConnectionRole.EntityLogicalName,
                        ColumnSet = new ColumnSet("connectionroleid", "name"),
                        Distinct = true,
                        LinkEntities = 
                        {
                            new LinkEntity
                            {
                                LinkToEntityName = 
                                ConnectionRoleObjectTypeCode.EntityLogicalName,
                                LinkToAttributeName = "connectionroleid",
                                LinkFromEntityName = ConnectionRole.EntityLogicalName,
                                LinkFromAttributeName = "connectionroleid",
                                LinkCriteria = new FilterExpression
                                {
                                    FilterOperator = LogicalOperator.And,
                                    // Set a condition to only get connection roles  
                                    // related to accounts (object type code = 1).
                                    Conditions = 
                                    {
                                        new ConditionExpression 
                                        {
                                             AttributeName = "associatedobjecttypecode",
                                             Operator = ConditionOperator.In,
                                             Values = { Account.EntityLogicalName }
                                        }
                                    }
                                }
                            }
                        }
                    };

                    results = _serviceProxy.RetrieveMultiple(accountQuery);

                    Console.WriteLine("Retrieved {0} account-only connectionrole instance(s).",
                        results.Entities.Count);

                    // Create a related Connection Role Object Type Code record for 
                    // Account.
                    ConnectionRoleObjectTypeCode setupAccountConnectionRoleTypeCode
                        = new ConnectionRoleObjectTypeCode
                        {
                            ConnectionRoleId = new EntityReference(
                                ConnectionRole.EntityLogicalName, _connectionRoleId),
                            AssociatedObjectTypeCode = Account.EntityLogicalName
                        };

                    setupAccountConnectionRoleTypeCode.Id = 
                        _serviceProxy.Create(setupAccountConnectionRoleTypeCode);

                    Console.Write("Created a related Connection Role Object Type Code");
                    Console.Write(" record for Account.");

                    // Run the query to find unassociated connectionroles again.
                    results = _serviceProxy.RetrieveMultiple(allQuery);
                    
                    Console.WriteLine(@"Retrieved {0} unassociated connectionrole instance(s).",
                        results.Entities.Count);

                    // Run the account-only query again.
                    results = _serviceProxy.RetrieveMultiple(accountQuery);

                    Console.WriteLine("Retrieved {0} account-only connectionrole instance(s).",
                        results.Entities.Count);

                    // Remove the link from account entity.
                    _serviceProxy.Delete(ConnectionRoleObjectTypeCode.EntityLogicalName, 
                        setupAccountConnectionRoleTypeCode.Id);

                    Console.WriteLine("Removed link from connectionrole to account entity.");

                    // Run the query to find unassociated connectionroles again.
                    results = _serviceProxy.RetrieveMultiple(allQuery);

                    Console.WriteLine("Retrieved {0} unassociated connectionrole instance(s).",
                        results.Entities.Count);

                    // Run the account-only query again.
                    results = _serviceProxy.RetrieveMultiple(accountQuery);

                    Console.WriteLine("Retrieved {0} account-only connectionrole instance(s).",
                        results.Entities.Count);

                    DeleteRequiredRecords(promptForDelete);
                }
                //</snippetQueryConnectionRolesByEntityTypeCode1>
            }
            // 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;
            }
        }