/// <summary> /// This method first connects to the Organization service. Afterwards, /// creates/retrieves a system user, /// updates the system user to associate with the salesperson role. /// Note: Creating a user is only supported /// in an on-premises/active directory environment. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user is 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 is properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { _serviceProxy.EnableProxyTypes(); CreateRequiredRecords(); // Find the role. QueryExpression query = new QueryExpression { EntityName = Role.EntityLogicalName, ColumnSet = new ColumnSet("roleid"), Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "name", Operator = ConditionOperator.Equal, Values = { _givenRole } } } } }; // Get the role. EntityCollection roles = _serviceProxy.RetrieveMultiple(query); if (roles.Entities.Count > 0) { Role salesRole = _serviceProxy.RetrieveMultiple(query).Entities[0].ToEntity <Role>(); Console.WriteLine("Role {0} is retrieved for the role assignment.", _givenRole); _roleId = salesRole.Id; // Associate the user with the role. if (_roleId != Guid.Empty && _userId != Guid.Empty) { _serviceProxy.Associate( "systemuser", _userId, new Relationship("systemuserroles_association"), new EntityReferenceCollection() { new EntityReference(Role.EntityLogicalName, _roleId) }); Console.WriteLine("Role is associated with the user."); } } 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 XAML to define the custom workflow. Afterwards, /// it creates the workflow record with this XAML and then activates it. Finally /// it checks if it is activated and, if so, deactivates it. /// </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 = ServerConnection.GetOrganizationProxy(serverConfig)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); CreateRequiredRecords(); // Activate the workflow. Console.WriteLine("\nActivating the workflow..."); //<snippetSetStateWorkflow1> var activateRequest = new SetStateRequest { EntityMoniker = new EntityReference (Workflow.EntityLogicalName, _workflowId), State = new OptionSetValue((int)WorkflowState.Activated), Status = new OptionSetValue((int)workflow_statuscode.Activated) }; _serviceProxy.Execute(activateRequest); //</snippetSetStateWorkflow1> // Verify that the workflow is activated. Workflow retrievedWorkflow = (Workflow)_serviceProxy.Retrieve("workflow", _workflowId, new ColumnSet("statecode", "name")); Console.WriteLine("The state of workflow {0} is: {1}.", retrievedWorkflow.Name, retrievedWorkflow.StateCode); // Deactivate the workflow. if (retrievedWorkflow.StateCode == WorkflowState.Activated) { Console.WriteLine("\nDeactivating the workflow..."); //<snippetSetStateWorkflow2> 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); //</snippetSetStateWorkflow2> } // Verify that the workflow is deactivated (in a draft state). retrievedWorkflow = (Workflow)_serviceProxy.Retrieve("workflow", _workflowId, new ColumnSet("statecode", "name")); Console.WriteLine("The state of workflow {0} is: {1}.", retrievedWorkflow.Name, retrievedWorkflow.StateCode); 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> /// Create and configure the organization service proxy. /// Initiate the method to create any data that this sample requires. /// Link the custom attributes. /// 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)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); // Create a custom string attribute for the appointment instance StringAttributeMetadata customAppointmentInstanceAttribute = new StringAttributeMetadata { LogicalName = "new_customAppInstanceAttribute", DisplayName = new Label("CustomAppInstanceAttribute", 1033), Description = new Label("Sample Custom Appointment Instance Attribute", 1033), MaxLength = 500, RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), SchemaName = "new_customAppInstanceAttribute" }; CreateAttributeRequest instanceAttributeRequest = new CreateAttributeRequest { Attribute = customAppointmentInstanceAttribute, EntityName = "appointment" }; CreateAttributeResponse instanceAttributeResponse = (CreateAttributeResponse)_serviceProxy.Execute(instanceAttributeRequest); _instanceAttributeID = instanceAttributeResponse.AttributeId; // Create a custom string attribute for the recurring appointment master (series) StringAttributeMetadata customAppointmentSeriesAttribute = new StringAttributeMetadata { LogicalName = "new_customAppSeriesAttribute", DisplayName = new Label("CustomAppSeriesAttribute", 1033), Description = new Label("Sample Custom Appointment Series Attribute", 1033), MaxLength = 500, RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), SchemaName = "new_customAppSeriesAttribute", LinkedAttributeId = _instanceAttributeID // Link the custom attribute to the appointment’s custom attribute. }; CreateAttributeRequest seriesAttributeRequest = new CreateAttributeRequest { Attribute = customAppointmentSeriesAttribute, EntityName = "recurringappointmentmaster" }; CreateAttributeResponse seriesAttributeResponse = (CreateAttributeResponse)_serviceProxy.Execute(seriesAttributeRequest); _seriesAttributeID = seriesAttributeResponse.AttributeId; // Publish all the changes to the solution. PublishAllXmlRequest createRequest = new PublishAllXmlRequest(); _serviceProxy.Execute(createRequest); Console.WriteLine("Created a custom string attribute, {0}, for the appointment.", customAppointmentInstanceAttribute.LogicalName); Console.WriteLine("Created a custom string attribute, {0}, for the recurring appointment, and linked it with {1}.", customAppointmentSeriesAttribute.LogicalName, customAppointmentInstanceAttribute.LogicalName); 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 connects to the Organization service. Afterwards, a /// quote is created. This quote is then converted to an order, and the pricing /// is unlocked and relocked. This is followed by the order being converted /// to an invoice, and the pricing is locked then unlocked. /// </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 { //<snippetProcessingQuotesAndSalesOrders1> // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); CreateRequiredRecords(); #region Create Opportunities // Create an opportunity var crmOpportunity = new Opportunity { CustomerId = new EntityReference(Account.EntityLogicalName, _accountId), Name = "Sample", PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId) }; _opportunityId = _serviceProxy.Create(crmOpportunity); crmOpportunity = new Opportunity { CustomerId = new EntityReference(Account.EntityLogicalName, _accountId), Name = "Another Sample", PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId) }; _loseOpportunityId = _serviceProxy.Create(crmOpportunity); Console.WriteLine("Opportunities created."); #endregion #region Win Opportunity //<snippetWinOpportunity> // Close the opportunity as won var winOppRequest = new WinOpportunityRequest { OpportunityClose = new OpportunityClose { OpportunityId = new EntityReference (Opportunity.EntityLogicalName, _opportunityId) }, Status = new OptionSetValue((int)opportunity_statuscode.Won) }; _serviceProxy.Execute(winOppRequest); Console.WriteLine("Opportunity closed as Won."); //</snippetWinOpportunity> #endregion #region Lose Opportunity //<snippetLoseOpportunity> var loseOppRequest = new LoseOpportunityRequest { OpportunityClose = new OpportunityClose { OpportunityId = new EntityReference (Opportunity.EntityLogicalName, _loseOpportunityId) }, Status = new OptionSetValue((int)opportunity_statuscode.Canceled) }; _serviceProxy.Execute(loseOppRequest); Console.WriteLine("Opportunity closed as Lost."); //</snippetLoseOpportunity> #endregion #region Convert Opportunity to a Quote //<snippetGenerateQuoteFromOpportunity> // Convert the opportunity to a quote var genQuoteFromOppRequest = new GenerateQuoteFromOpportunityRequest { OpportunityId = _opportunityId, ColumnSet = new ColumnSet("quoteid", "name") }; var genQuoteFromOppResponse = (GenerateQuoteFromOpportunityResponse) _serviceProxy.Execute(genQuoteFromOppRequest); Quote quote = genQuoteFromOppResponse.Entity.ToEntity <Quote>(); _quoteId = quote.Id; Console.WriteLine("Quote generated from the Opportunity."); //</snippetGenerateQuoteFromOpportunity> #endregion #region Close Quote //<snippetCloseQuote> // convert the opportunity to a quote genQuoteFromOppRequest = new GenerateQuoteFromOpportunityRequest { OpportunityId = _opportunityId, ColumnSet = new ColumnSet("quoteid", "name") }; genQuoteFromOppResponse = (GenerateQuoteFromOpportunityResponse) _serviceProxy.Execute(genQuoteFromOppRequest); Quote closeQuote = genQuoteFromOppResponse.Entity.ToEntity <Quote>(); _closeQuoteId = closeQuote.Id; // Activate the quote SetStateRequest activateQuote = new SetStateRequest() { EntityMoniker = closeQuote.ToEntityReference(), State = new OptionSetValue((int)QuoteState.Active), Status = new OptionSetValue((int)quote_statuscode.InProgress) }; _serviceProxy.Execute(activateQuote); // Close the quote CloseQuoteRequest closeQuoteRequest = new CloseQuoteRequest() { QuoteClose = new QuoteClose() { QuoteId = closeQuote.ToEntityReference(), Subject = "Quote Close " + DateTime.Now.ToString() }, Status = new OptionSetValue(-1) }; _serviceProxy.Execute(closeQuoteRequest); Console.WriteLine("Quote Closed"); //</snippetCloseQuote> #endregion #region Create Quote's Product // Set the quote's product QuoteDetail quoteDetail = new QuoteDetail() { ProductId = new EntityReference(Product.EntityLogicalName, _productId), Quantity = 1, QuoteId = quote.ToEntityReference(), UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId) }; _quoteDetailId = _serviceProxy.Create(quoteDetail); Console.WriteLine("Quote Product created."); // Activate the quote activateQuote = new SetStateRequest() { EntityMoniker = quote.ToEntityReference(), State = new OptionSetValue((int)QuoteState.Active), Status = new OptionSetValue((int)quote_statuscode.InProgress) }; _serviceProxy.Execute(activateQuote); Console.WriteLine("Quote activated."); //<snippetWinQuote> // Mark the quote as won // Note: this is necessary in order to convert a quote into a // SalesOrder. WinQuoteRequest winQuoteRequest = new WinQuoteRequest() { QuoteClose = new QuoteClose() { Subject = "Quote Close" + DateTime.Now.ToString(), QuoteId = quote.ToEntityReference() }, Status = new OptionSetValue(-1) }; _serviceProxy.Execute(winQuoteRequest); Console.WriteLine("Quote won."); //</snippetWinQuote> #endregion #region Convert Quote to SalesOrder //<snippetConvertQuoteToSalesOrder> // Define columns to be retrieved after creating the order ColumnSet salesOrderColumns = new ColumnSet("salesorderid", "totalamount"); // Convert the quote to a sales order ConvertQuoteToSalesOrderRequest convertQuoteRequest = new ConvertQuoteToSalesOrderRequest() { QuoteId = _quoteId, ColumnSet = salesOrderColumns }; ConvertQuoteToSalesOrderResponse convertQuoteResponse = (ConvertQuoteToSalesOrderResponse)_serviceProxy.Execute(convertQuoteRequest); SalesOrder salesOrder = (SalesOrder)convertQuoteResponse.Entity; _salesOrderId = salesOrder.Id; //</snippetConvertQuoteToSalesOrder> Console.WriteLine("Converted Quote to SalesOrder."); #endregion #region Cancel Sales Order //<snippetCancelSalesOrder> // Define columns to be retrieved after creating the order salesOrderColumns = new ColumnSet("salesorderid", "totalamount"); // Convert the quote to a sales order convertQuoteRequest = new ConvertQuoteToSalesOrderRequest() { QuoteId = _quoteId, ColumnSet = salesOrderColumns }; convertQuoteResponse = (ConvertQuoteToSalesOrderResponse)_serviceProxy.Execute(convertQuoteRequest); SalesOrder closeSalesOrder = (SalesOrder)convertQuoteResponse.Entity; _closeSalesOrderId = closeSalesOrder.Id; CancelSalesOrderRequest cancelRequest = new CancelSalesOrderRequest() { OrderClose = new OrderClose() { SalesOrderId = closeSalesOrder.ToEntityReference(), Subject = "Close Sales Order " + DateTime.Now }, Status = new OptionSetValue(-1) }; _serviceProxy.Execute(cancelRequest); Console.WriteLine("Canceled sales order"); //</snippetCancelSalesOrder> #endregion #region Lock pricing on SalesOrder // Note: after converting a won quote to an order, the pricing of // the order is locked by default. //<snippetUpdateRequest> // Retrieve current price list ProductPriceLevel priceListItem = (ProductPriceLevel)_serviceProxy.Retrieve( ProductPriceLevel.EntityLogicalName, _priceListItemId, new ColumnSet("productpricelevelid", "amount") ); Console.WriteLine("Current price list retrieved."); Console.WriteLine(); Console.WriteLine("Details before update:"); Console.WriteLine("----------------"); Console.WriteLine("Current order total: {0}", salesOrder.TotalAmount.Value); Console.WriteLine("Current price per item: {0}", priceListItem.Amount.Value); Console.WriteLine("</End of Listing>"); Console.WriteLine(); // Update the price list priceListItem.Amount = new Money(30.0M); UpdateRequest updatePriceListItem = new UpdateRequest() { Target = priceListItem, }; _serviceProxy.Execute(updatePriceListItem); Console.WriteLine("Price list updated."); //</snippetUpdateRequest> // Retrieve the order SalesOrder updatedSalesOrder = (SalesOrder)_serviceProxy.Retrieve( SalesOrder.EntityLogicalName, _salesOrderId, new ColumnSet("salesorderid", "totalamount") ); Console.WriteLine("Updated order retrieved."); Console.WriteLine(); Console.WriteLine("Details after update:"); Console.WriteLine("----------------"); Console.WriteLine("Current order total: {0}", updatedSalesOrder.TotalAmount.Value); Console.WriteLine("Current price per item: {0}", priceListItem.Amount.Value); Console.WriteLine("</End of Listing>"); Console.WriteLine(); //<snippetUnlockSalesOrderPricing> // Unlock the order pricing UnlockSalesOrderPricingRequest unlockOrderRequest = new UnlockSalesOrderPricingRequest() { SalesOrderId = _salesOrderId }; _serviceProxy.Execute(unlockOrderRequest); //</snippetUnlockSalesOrderPricing> Console.WriteLine("Order pricing unlocked."); // Retrieve the order updatedSalesOrder = (SalesOrder)_serviceProxy.Retrieve( SalesOrder.EntityLogicalName, _salesOrderId, new ColumnSet("salesorderid", "totalamount") ); Console.WriteLine("Updated order retrieved."); Console.WriteLine(); Console.WriteLine("Details after update and unlock:"); Console.WriteLine("----------------"); Console.WriteLine("Current order total: {0}", updatedSalesOrder.TotalAmount.Value); Console.WriteLine("Current price per item: {0}", priceListItem.Amount.Value); Console.WriteLine("</End of Listing>"); Console.WriteLine(); //<snippetLockSalesOrderPricing> // Relock the order pricing LockSalesOrderPricingRequest lockOrderRequest = new LockSalesOrderPricingRequest() { SalesOrderId = _salesOrderId }; _serviceProxy.Execute(lockOrderRequest); //</snippetLockSalesOrderPricing> Console.WriteLine("Order pricing relocked."); #endregion //<snippetConvertSalesOrderToInvoice> #region Convert SalesOrder to Invoice // Define columns to be retrieved after creating the invoice ColumnSet invoiceColumns = new ColumnSet("invoiceid", "totalamount"); // Convert the order to an invoice ConvertSalesOrderToInvoiceRequest convertOrderRequest = new ConvertSalesOrderToInvoiceRequest() { SalesOrderId = _salesOrderId, ColumnSet = invoiceColumns }; ConvertSalesOrderToInvoiceResponse convertOrderResponse = (ConvertSalesOrderToInvoiceResponse)_serviceProxy.Execute(convertOrderRequest); Invoice invoice = (Invoice)convertOrderResponse.Entity; _invoiceId = invoice.Id; //</snippetConvertSalesOrderToInvoice> Console.WriteLine("Converted SalesOrder to Invoice."); #endregion #region Lock pricing on Invoice // Note: after converting a SalesOrder to Invoice, the pricing of // the Invoice is locked by default. // Retrieve current price list priceListItem = (ProductPriceLevel)_serviceProxy.Retrieve( ProductPriceLevel.EntityLogicalName, _priceListItemId, new ColumnSet("productpricelevelid", "amount") ); Console.WriteLine("Current price list retrieved."); Console.WriteLine(); Console.WriteLine("Details before lock and update:"); Console.WriteLine("----------------"); Console.WriteLine("Current invoice total: {0}", invoice.TotalAmount.Value); Console.WriteLine("Current price per item: {0}", priceListItem.Amount.Value); Console.WriteLine("</End of Listing>"); Console.WriteLine(); //<snippetUpdatePriceList> // Update the price list priceListItem.Amount = new Money(40.0M); updatePriceListItem = new UpdateRequest() { Target = priceListItem }; _serviceProxy.Execute(updatePriceListItem); Console.WriteLine("Price list updated."); //</snippetUpdatePriceList> //<snippetUnlockInvoicePricing> // Retrieve the invoice Invoice updatedInvoice = (Invoice)_serviceProxy.Retrieve( Invoice.EntityLogicalName, _invoiceId, new ColumnSet("invoiceid", "totalamount") ); Console.WriteLine("Updated invoice retrieved."); Console.WriteLine(); Console.WriteLine("Details after lock and update:"); Console.WriteLine("----------------"); Console.WriteLine("Current invoice total: {0}", updatedInvoice.TotalAmount.Value); Console.WriteLine("Current price per item: {0}", priceListItem.Amount.Value); Console.WriteLine("</End of Listing>"); Console.WriteLine(); // Unlock the invoice pricing UnlockInvoicePricingRequest unlockInvoiceRequest = new UnlockInvoicePricingRequest() { InvoiceId = _invoiceId }; _serviceProxy.Execute(unlockInvoiceRequest); Console.WriteLine("Invoice pricing unlocked."); //</snippetUnlockInvoicePricing> // Retrieve the invoice updatedInvoice = (Invoice)_serviceProxy.Retrieve( Invoice.EntityLogicalName, _invoiceId, new ColumnSet("invoiceid", "totalamount") ); Console.WriteLine("Updated invoice retrieved."); Console.WriteLine(); Console.WriteLine("Details after update and unlock:"); Console.WriteLine("----------------"); Console.WriteLine("Current invoice total: {0}", updatedInvoice.TotalAmount.Value); Console.WriteLine("Current price per item: {0}", priceListItem.Amount.Value); Console.WriteLine("</End of Listing>"); Console.WriteLine(); //<snippetLockInvoicePricing> // Relock the invoice pricing LockInvoicePricingRequest lockInvoiceRequest = new LockInvoicePricingRequest() { InvoiceId = _invoiceId }; _serviceProxy.Execute(lockInvoiceRequest); Console.WriteLine("Invoice pricing relocked."); //</snippetLockInvoicePricing> #endregion DeleteRequiredRecords(promptforDelete); } //</snippetProcessingQuotesAndSalesOrders1> } // 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 shows how to send a bulk email and monitor its progress. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user is 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 is 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(); #region Create and send SendBulkEmail Console.WriteLine(); Console.WriteLine("Creating and sending SendBulkEmail."); // Get a system user to use as the sender. WhoAmIRequest emailSenderRequest = new WhoAmIRequest(); WhoAmIResponse emailSenderResponse = _serviceProxy.Execute(emailSenderRequest) as WhoAmIResponse; // Set trackingId for bulk mail request. Guid trackingId = Guid.NewGuid(); SendBulkMailRequest bulkMailRequest = new SendBulkMailRequest() { // Create a query expression for the bulk operation to use to retrieve // the contacts in the email list. Query = new QueryExpression() { EntityName = Contact.EntityLogicalName, ColumnSet = new ColumnSet(new String[] { "contactid" }), Criteria = new FilterExpression() { Conditions = { new ConditionExpression("contactid", ConditionOperator.In, _contactsIds) } } }, // Set the Sender. Sender = new EntityReference(SystemUser.EntityLogicalName, emailSenderResponse.UserId), // Set the RegardingId - this field is required. RegardingId = Guid.Empty, RegardingType = SystemUser.EntityLogicalName, // Use a built-in Microsoft Dynamics CRM email template. // NOTE: The email template's "template type" must match the type of // customers in the email list. Our list contains contacts, so our // template must be for contacts. TemplateId = new Guid("07B94C1D-C85F-492F-B120-F0A743C540E6"), RequestId = trackingId }; // Execute the async bulk email request SendBulkMailResponse resp = (SendBulkMailResponse) _serviceProxy.Execute(bulkMailRequest); Console.WriteLine(" Sent Bulk Email."); #endregion #region Monitoring SendBulkEmail Console.WriteLine(); Console.WriteLine("Starting monitoring process.."); // Now that we've executed the bulk operation, we need to retrieve it // using our tracking Id. QueryByAttribute bulkQuery = new QueryByAttribute() { EntityName = AsyncOperation.EntityLogicalName, ColumnSet = new ColumnSet(new string[] { "requestid", "statecode" }), Attributes = { "requestid" }, Values = { trackingId } }; // Retrieve the bulk email async operation. EntityCollection aResponse = _serviceProxy.RetrieveMultiple(bulkQuery); Console.WriteLine(" Retrieved Bulk Email Async Operation."); // Monitor the async operation via polling. int secondsTicker = ARBITRARY_MAX_POLLING_TIME; AsyncOperation createdBulkMailOperation = null; Console.WriteLine(" Checking operation's state for " + ARBITRARY_MAX_POLLING_TIME + " seconds."); Console.WriteLine(); while (secondsTicker > 0) { // Make sure the async operation was retrieved. if (aResponse.Entities.Count > 0) { // Grab the one bulk operation that has been created. createdBulkMailOperation = (AsyncOperation)aResponse.Entities[0]; // Check the operation's state. if (createdBulkMailOperation.StateCode.Value != AsyncOperationState.Completed) { // The operation has not yet completed. // Wait a second for the status to change. System.Threading.Thread.Sleep(1000); secondsTicker--; // Retrieve a fresh version the bulk delete operation. aResponse = _serviceProxy.RetrieveMultiple(bulkQuery); } else { // Stop polling because the operation's state is now complete. secondsTicker = 0; } } else { // Wait a second for the async operation to activate. System.Threading.Thread.Sleep(1000); secondsTicker--; // Retrieve the entity again aResponse = _serviceProxy.RetrieveMultiple(bulkQuery); } } // When the bulk email operation has completed, all sent emails will // have a status of "Pending Send" and will be picked up by your email // router. Alternatively, you can then use BackgroundSendEmail to download // all the emails created with the SendBulkEmail message. // See the BackgroundSendEmail sample for an example. #endregion #region Check success // Validate async operation succeeded if (createdBulkMailOperation.StateCode.Value == AsyncOperationState.Completed) { Console.WriteLine("Operation Completed."); } else { Console.WriteLine("Operation not completed yet."); } #endregion 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 connects to the Organization service. Afterwards, /// a goal is created specifying the target count. The goal is then /// rolled up, the actual and in-progress values are overridden and finally the /// goal is closed. /// </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 { //<snippetOverrideGoalTotalCount1> // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); CreateRequiredRecords(); // Create the count metric, setting the Metric Type to 'Count' by // setting IsAmount to false. Metric sampleMetric = new Metric() { Name = "Sample Count Metric", IsAmount = false, }; _metricId = _serviceProxy.Create(sampleMetric); sampleMetric.Id = _metricId; Console.Write("Created phone call metric, "); #region Create RollupFields // Create RollupField which targets completed (received) phone calls. RollupField actual = new RollupField() { SourceEntity = PhoneCall.EntityLogicalName, GoalAttribute = "actualinteger", SourceState = 1, SourceStatus = 4, EntityForDateAttribute = PhoneCall.EntityLogicalName, DateAttribute = "actualend", MetricId = sampleMetric.ToEntityReference() }; _actualId = _serviceProxy.Create(actual); Console.Write("created actual revenue RollupField, "); // Create RollupField which targets open (in-progress) phone calls. RollupField inprogress = new RollupField() { SourceEntity = PhoneCall.EntityLogicalName, GoalAttribute = "inprogressinteger", SourceState = 0, EntityForDateAttribute = PhoneCall.EntityLogicalName, DateAttribute = "createdon", MetricId = sampleMetric.ToEntityReference() }; _inprogressId = _serviceProxy.Create(inprogress); Console.Write("created in-progress revenue RollupField, "); #endregion #region Create the goal rollup queries // Note: Formatting the FetchXml onto multiple lines in the following // rollup queries causes the length property to be greater than 1,000 // chars and will cause an exception. // The following query locates closed incoming phone calls. GoalRollupQuery goalRollupQuery = new GoalRollupQuery() { Name = "Example Goal Rollup Query - Actual", QueryEntityType = PhoneCall.EntityLogicalName, FetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'><entity name='phonecall'><attribute name='subject'/><attribute name='statecode'/><attribute name='prioritycode'/><attribute name='scheduledend'/><attribute name='createdby'/><attribute name='regardingobjectid'/><attribute name='activityid'/><order attribute='subject' descending='false'/><filter type='and'><condition attribute='directioncode' operator='eq' value='0'/><condition attribute='statecode' operator='eq' value='1' /></filter></entity></fetch>" }; _rollupQueryIds.Add(_serviceProxy.Create(goalRollupQuery)); goalRollupQuery.Id = _rollupQueryIds[0]; // The following query locates open incoming phone calls. GoalRollupQuery inProgressGoalRollupQuery = new GoalRollupQuery() { Name = "Example Goal Rollup Query - InProgress", QueryEntityType = PhoneCall.EntityLogicalName, FetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'><entity name='phonecall'><attribute name='subject'/><attribute name='statecode'/><attribute name='prioritycode'/><attribute name='scheduledend'/><attribute name='createdby'/><attribute name='regardingobjectid'/><attribute name='activityid'/><order attribute='subject' descending='false'/><filter type='and'><condition attribute='directioncode' operator='eq' value='0'/><condition attribute='statecode' operator='eq' value='0' /></filter></entity></fetch>" }; _rollupQueryIds.Add(_serviceProxy.Create(inProgressGoalRollupQuery)); inProgressGoalRollupQuery.Id = _rollupQueryIds[1]; Console.Write("created rollup queries for incoming phone calls.\n"); Console.WriteLine(); #endregion #region Create a goal to track the open incoming phone calls. // Create the goal. Goal goal = new Goal() { Title = "Sample Goal", RollupOnlyFromChildGoals = false, ConsiderOnlyGoalOwnersRecords = false, TargetInteger = 5, RollupQueryActualIntegerId = goalRollupQuery.ToEntityReference(), RollUpQueryInprogressIntegerId = inProgressGoalRollupQuery.ToEntityReference(), IsFiscalPeriodGoal = false, MetricId = sampleMetric.ToEntityReference(), GoalOwnerId = new EntityReference { Id = _salesManagerId, LogicalName = SystemUser.EntityLogicalName }, OwnerId = new EntityReference { Id = _salesManagerId, LogicalName = SystemUser.EntityLogicalName }, GoalStartDate = DateTime.Today.AddDays(-1), GoalEndDate = DateTime.Today.AddDays(30) }; _goalId = _serviceProxy.Create(goal); goal.Id = _goalId; Console.WriteLine("Created goal"); Console.WriteLine("-------------------"); Console.WriteLine("Target: {0}", goal.TargetInteger.Value); Console.WriteLine("Goal owner: {0}", goal.GoalOwnerId.Id); Console.WriteLine("Goal Start Date: {0}", goal.GoalStartDate); Console.WriteLine("Goal End Date: {0}", goal.GoalEndDate); Console.WriteLine("<End of Listing>"); Console.WriteLine(); #endregion #region Calculate rollup and display result // Calculate roll-up of the goal. RecalculateRequest recalculateRequest = new RecalculateRequest() { Target = goal.ToEntityReference() }; _serviceProxy.Execute(recalculateRequest); Console.WriteLine("Calculated roll-up of goal."); Console.WriteLine(); // Retrieve and report 3 different computed values for the goal // - Percentage // - Actual (Integer) // - In-Progress (Integer) QueryExpression retrieveValues = new QueryExpression() { EntityName = Goal.EntityLogicalName, ColumnSet = new ColumnSet( "title", "percentage", "actualinteger", "inprogressinteger") }; EntityCollection ec = _serviceProxy.RetrieveMultiple(retrieveValues); // Compute and display the results. for (int i = 0; i < ec.Entities.Count; i++) { Goal temp = (Goal)ec.Entities[i]; Console.WriteLine("Roll-up details for goal: {0}", temp.Title); Console.WriteLine("---------------"); Console.WriteLine("Percentage Achieved: {0}", temp.Percentage); Console.WriteLine("Actual (Integer): {0}", temp.ActualInteger.Value); Console.WriteLine("In-Progress (Integer): {0}", temp.InProgressInteger.Value); Console.WriteLine("<End of Listing>"); } Console.WriteLine(); #endregion #region Update goal to override the actual rollup value // Override the actual and in-progress values of the goal. // To prevent rollup values to be overwritten during next Recalculate operation, // set: goal.IsOverridden = true; goal.IsOverride = true; goal.ActualInteger = 10; goal.InProgressInteger = 5; // Update the goal. UpdateRequest update = new UpdateRequest() { Target = goal }; _serviceProxy.Execute(update); Console.WriteLine("Goal actual and in-progress values overridden."); Console.WriteLine(); #endregion #region Retrieve result of manual override // Retrieve and report 3 different computed values for the goal // - Percentage // - Actual (Integer) // - In-Progress (Integer) retrieveValues = new QueryExpression() { EntityName = Goal.EntityLogicalName, ColumnSet = new ColumnSet( "title", "percentage", "actualinteger", "inprogressinteger") }; ec = _serviceProxy.RetrieveMultiple(retrieveValues); // Compute and display the results. for (int i = 0; i < ec.Entities.Count; i++) { Goal temp = (Goal)ec.Entities[i]; Console.WriteLine("Roll-up details for goal: {0}", temp.Title); Console.WriteLine("---------------"); Console.WriteLine("Percentage Achieved: {0}", temp.Percentage); Console.WriteLine("Actual (Integer): {0}", temp.ActualInteger.Value); Console.WriteLine("In-Progress (Integer): {0}", temp.InProgressInteger.Value); Console.WriteLine("<End of Listing>"); } Console.WriteLine(); #endregion #region Close the goal // Close the goal. SetStateRequest closeGoal = new SetStateRequest() { EntityMoniker = goal.ToEntityReference(), State = new OptionSetValue(1), Status = new OptionSetValue(1) }; Console.WriteLine("Goal closed."); #endregion DeleteRequiredRecords(promptforDelete); } //</snippetOverrideGoalTotalCount1> } // 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> /// 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 = ServerConnection.GetOrganizationProxy(serverConfig)) { _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; } }
/// <summary> /// This method first creates a series of Accounts to query over, a user query /// that retrieves the names of all Accounts with a name of 'Coho Winery' and /// a system query that retrieves all Account names. Then it validates the system /// query, executes the system query and displays the results, and finally /// executes the user query and displays the results. /// </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 { //<snippetUserQueryAndSavedQuery1> // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); CreateRequiredRecords(); #region Validate saved query // Create the request ValidateSavedQueryRequest validateRequest = new ValidateSavedQueryRequest() { FetchXml = _savedQuery.FetchXml, QueryType = _savedQuery.QueryType.Value }; // Send the request Console.WriteLine(" Validating Saved Query"); try { // executing the request will throw an exception if the fetch xml is invalid var validateResponse = (ValidateSavedQueryResponse)_serviceProxy.Execute(validateRequest); Console.WriteLine(" Saved Query validated successfully"); } catch (Exception) { Console.WriteLine(" Invalid Saved Query"); throw; } #endregion #region Execute saved query // Create the request ExecuteByIdSavedQueryRequest executeSavedQueryRequest = new ExecuteByIdSavedQueryRequest() { EntityId = _savedQuery.Id }; // Execute the request Console.WriteLine(" Executing Saved Query"); ExecuteByIdSavedQueryResponse executeSavedQueryResponse = (ExecuteByIdSavedQueryResponse)_serviceProxy.Execute(executeSavedQueryRequest); // Check results if (String.IsNullOrEmpty(executeSavedQueryResponse.String)) { throw new Exception("Saved Query did not return any results"); } PrintResults(executeSavedQueryResponse.String); #endregion #region Execute user query // Create the request ExecuteByIdUserQueryRequest executeUserQuery = new ExecuteByIdUserQueryRequest() { EntityId = _userQuery.ToEntityReference() }; // Send the request Console.WriteLine(" Executing User Query"); ExecuteByIdUserQueryResponse executeUserQueryResponse = (ExecuteByIdUserQueryResponse)_serviceProxy.Execute(executeUserQuery); if (String.IsNullOrEmpty(executeUserQueryResponse.String)) { throw new Exception("User Query did not return any results"); } // validate results PrintResults(executeUserQueryResponse.String); #endregion DeleteRequiredRecords(promptforDelete); } //</snippetUserQueryAndSavedQuery1> } // 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> /// Create and configure the organization service proxy. /// Initiate the method to create any data that this sample requires. /// Create an organization-owned visualization. /// Retrieve the visualization. /// Update the visualization; update the name and set it as the default /// visualization for the Opportunity entity. /// 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 = ServerConnection.GetOrganizationProxy(serverConfig)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); // Call the method to create any data that this sample requires. CreateRequiredRecords(); //<snippetCRUDVisualization1> // Create a visualization // Set The presentation XML string. string presentationXml = @" <Chart Palette='BrightPastel'> <Series> <Series _Template_='All' ShadowOffset='2' BorderColor='64, 64, 64' BorderDashStyle='Solid' BorderWidth='1' IsValueShownAsLabel='true' Font='Tahoma, 6.75pt, GdiCharSet=0' LabelForeColor='100, 100, 100' CustomProperties='FunnelLabelStyle=Outside' ChartType='Funnel'> <SmartLabelStyle Enabled='True' /> <Points /> </Series> </Series> <ChartAreas> <ChartArea _Template_='All' BackColor='Transparent' BorderColor='Transparent' BorderDashStyle='Solid'> <Area3DStyle Enable3D='True' IsClustered='True'/> </ChartArea> </ChartAreas> <Legends> <Legend _Template_='All' Alignment='Center' LegendStyle='Table' Docking='Bottom' IsEquallySpacedItems='True' BackColor='White' BorderColor='228, 228, 228' BorderWidth='0' Font='Tahoma, 8pt, GdiCharSet=0' ShadowColor='0, 0, 0, 0' ForeColor='100, 100, 100'> </Legend> </Legends> <Titles> <Title _Template_='All' Font='Tahoma, 9pt, style=Bold, GdiCharSet=0' ForeColor='102, 102, 102'> </Title> </Titles> <BorderSkin PageColor='Control' BackColor='CornflowerBlue' BackSecondaryColor='CornflowerBlue' /> </Chart> "; // Set the data XML string. string dataXml = @" <datadefinition> <fetchcollection> <fetch mapping='logical' count='10' aggregate='true'> <entity name='opportunity'> <attribute name='actualvalue_base' aggregate='sum' alias='sum_actualvalue_base' /> <attribute name='stepname' groupby='true' alias='stepname' /> <order alias='stepname' descending='false'/> </entity> </fetch> </fetchcollection> <categorycollection> <category> <measurecollection> <measure alias='sum_actualvalue_base'/> </measurecollection> </category> </categorycollection> </datadefinition> "; //<snippetCRUDVisualization2> // Create the visualization entity instance. SavedQueryVisualization newOrgOwnedVisualization = new SavedQueryVisualization { Name = "Sample Visualization", Description = "Sample organization-owned visualization.", PresentationDescription = presentationXml, DataDescription = dataXml, PrimaryEntityTypeCode = Opportunity.EntityLogicalName, IsDefault = false }; _orgOwnedVisualizationId = _serviceProxy.Create(newOrgOwnedVisualization); //</snippetCRUDVisualization2> Console.WriteLine("Created {0}.", newOrgOwnedVisualization.Name); //</snippetCRUDVisualization1> // Retrieve the visualization SavedQueryVisualization retrievedOrgOwnedVisualization = (SavedQueryVisualization)_serviceProxy.Retrieve(SavedQueryVisualization.EntityLogicalName, _orgOwnedVisualizationId, new ColumnSet(true)); Console.WriteLine("Retrieved the visualization."); // Update the retrieved visualization // 1. Update the name. // 2. Update the data description string. string newDataXml = @"<datadefinition> <fetchcollection> <fetch mapping='logical' count='10' aggregate='true'> <entity name='opportunity'> <attribute name='estimatedvalue_base' aggregate='sum' alias='sum_estimatedvalue_base' /> <attribute name='name' groupby='true' alias='name' /> <order alias='name' descending='false'/> </entity> </fetch> </fetchcollection> <categorycollection> <category> <measurecollection> <measure alias='sum_estimatedvalue_base'/> </measurecollection> </category> </categorycollection> </datadefinition>"; retrievedOrgOwnedVisualization.Name = "Updated Sample Visualization"; retrievedOrgOwnedVisualization.DataDescription = newDataXml; _serviceProxy.Update(retrievedOrgOwnedVisualization); // Publish the changes to the solution. This step is only required // for organization-owned visualizations. PublishAllXmlRequest updateRequest = new PublishAllXmlRequest(); _serviceProxy.Execute(updateRequest); Console.WriteLine("Updated the visualization."); 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> /// </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(); #region How to dump attribute info RetrieveAllEntitiesRequest request = new RetrieveAllEntitiesRequest() { EntityFilters = EntityFilters.Attributes, RetrieveAsIfPublished = true }; // Retrieve the MetaData. RetrieveAllEntitiesResponse response = (RetrieveAllEntitiesResponse)_serviceProxy.Execute(request); // Create an instance of StreamWriter to write text to a file. // The using statement also closes the StreamWriter. // To view this file, right click the file and choose open with Excel. // Excel will figure out the schema and display the information in columns. String filename = String.Concat("AllAttributeDesc.xml"); using (StreamWriter sw = new StreamWriter(filename)) { // Create Xml Writer. XmlTextWriter metadataWriter = new XmlTextWriter(sw); // Start Xml File. metadataWriter.WriteStartDocument(); // Metadata Xml Node. metadataWriter.WriteStartElement("Metadata"); foreach (EntityMetadata currentEntity in response.EntityMetadata) { //if (currentEntity.IsIntersect.Value == false) if (true) { // Start Entity Node metadataWriter.WriteStartElement("Entity"); // Write the Entity's Information. metadataWriter.WriteElementString("EntitySchemaName", currentEntity.SchemaName); if (currentEntity.IsCustomizable.Value == true) { metadataWriter.WriteElementString("IsCustomizable", "yes"); } else { metadataWriter.WriteElementString("IsCustomizable", "no"); } if (currentEntity.IsIntersect.Value == true) { metadataWriter.WriteElementString("IsIntersect", "yes"); } else { metadataWriter.WriteElementString("IsIntersect", "no"); } #region Attributes // Write Entity's Attributes. metadataWriter.WriteStartElement("Attributes"); foreach (AttributeMetadata currentAttribute in currentEntity.Attributes) { // Only write out main attributes. if (currentAttribute.AttributeOf == null) { // Start Attribute Node metadataWriter.WriteStartElement("Attribute"); // Write Attribute's information. metadataWriter.WriteElementString("LogicalName", currentAttribute.LogicalName); // Write the Description if it is set. if (currentAttribute.Description.UserLocalizedLabel != null) { metadataWriter.WriteElementString("Description", currentAttribute.Description.UserLocalizedLabel.Label.ToString()); } metadataWriter.WriteElementString("Type", currentAttribute.AttributeType.Value.ToString()); if (currentAttribute.DisplayName.UserLocalizedLabel != null) { metadataWriter.WriteElementString("DisplayName", currentAttribute.DisplayName.UserLocalizedLabel.Label.ToString()); } if (currentAttribute.SchemaName != null) { metadataWriter.WriteElementString("SchemaName", currentAttribute.SchemaName.ToString()); } if (currentAttribute.IntroducedVersion != null) { metadataWriter.WriteElementString("IntroducedVersion", currentAttribute.IntroducedVersion.ToString()); } if (currentAttribute.DeprecatedVersion != null) { metadataWriter.WriteElementString("DeprecatedVersion", currentAttribute.DeprecatedVersion.ToString()); } if (currentAttribute.IsCustomAttribute != null) { metadataWriter.WriteElementString("IsCustomAttribute", currentAttribute.IsCustomAttribute.Value.ToString()); } if (currentAttribute.IsCustomizable != null) { metadataWriter.WriteElementString("IsCustomizable", currentAttribute.IsCustomizable.Value.ToString()); } if (currentAttribute.RequiredLevel != null) { metadataWriter.WriteElementString("RequiredLevel", currentAttribute.RequiredLevel.Value.ToString()); } if (currentAttribute.IsValidForCreate != null) { metadataWriter.WriteElementString("IsValidForCreate", currentAttribute.IsValidForCreate.Value.ToString()); } if (currentAttribute.IsValidForRead != null) { metadataWriter.WriteElementString("IsValidForRead", currentAttribute.IsValidForRead.Value.ToString()); } if (currentAttribute.IsValidForUpdate != null) { metadataWriter.WriteElementString("IsValidForUpdate", currentAttribute.IsValidForUpdate.Value.ToString()); } if (currentAttribute.CanBeSecuredForCreate != null) { metadataWriter.WriteElementString("CanBeSecuredForCreate", currentAttribute.CanBeSecuredForCreate.Value.ToString()); } if (currentAttribute.CanBeSecuredForRead != null) { metadataWriter.WriteElementString("CanBeSecuredForRead", currentAttribute.CanBeSecuredForRead.Value.ToString()); } if (currentAttribute.CanBeSecuredForUpdate != null) { metadataWriter.WriteElementString("CanBeSecuredForUpdate", currentAttribute.CanBeSecuredForUpdate.Value.ToString()); } if (currentAttribute.IsAuditEnabled != null) { metadataWriter.WriteElementString("IsAuditEnabled", currentAttribute.IsAuditEnabled.Value.ToString()); } if (currentAttribute.IsManaged != null) { metadataWriter.WriteElementString("IsManaged", currentAttribute.IsManaged.Value.ToString()); } if (currentAttribute.IsPrimaryId != null) { metadataWriter.WriteElementString("IsPrimaryId", currentAttribute.IsPrimaryId.Value.ToString()); } if (currentAttribute.IsPrimaryName != null) { metadataWriter.WriteElementString("IsPrimaryName", currentAttribute.IsPrimaryName.Value.ToString()); } if (currentAttribute.IsRenameable != null) { metadataWriter.WriteElementString("IsRenameable", currentAttribute.IsRenameable.Value.ToString()); } if (currentAttribute.IsSecured != null) { metadataWriter.WriteElementString("IsSecured", currentAttribute.IsSecured.Value.ToString()); } if (currentAttribute.IsValidForAdvancedFind != null) { metadataWriter.WriteElementString("IsValidForAdvancedFind", currentAttribute.IsValidForAdvancedFind.Value.ToString()); } // End Attribute Node metadataWriter.WriteEndElement(); } } // End Attributes Node metadataWriter.WriteEndElement(); #endregion // End Entity Node metadataWriter.WriteEndElement(); } } // End Metadata Xml Node metadataWriter.WriteEndElement(); metadataWriter.WriteEndDocument(); // Close xml writer. metadataWriter.Close(); } #endregion How to dump attribute info Console.WriteLine("Done."); //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> /// Create and configure the organization service proxy. /// Create one-to-many relationship. /// Create many-to-many relationship. /// 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)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); bool eligibleCreateOneToManyRelationship = EligibleCreateOneToManyRelationship("account", "campaign"); if (eligibleCreateOneToManyRelationship) { CreateOneToManyRequest createOneToManyRelationshipRequest = new CreateOneToManyRequest { OneToManyRelationship = new OneToManyRelationshipMetadata { ReferencedEntity = "account", ReferencingEntity = "campaign", SchemaName = "new_account_campaign", AssociatedMenuConfiguration = new AssociatedMenuConfiguration { Behavior = AssociatedMenuBehavior.UseLabel, Group = AssociatedMenuGroup.Details, Label = new Label("Account", 1033), Order = 10000 }, CascadeConfiguration = new CascadeConfiguration { Assign = CascadeType.NoCascade, Delete = CascadeType.RemoveLink, Merge = CascadeType.NoCascade, Reparent = CascadeType.NoCascade, Share = CascadeType.NoCascade, Unshare = CascadeType.NoCascade } }, Lookup = new LookupAttributeMetadata { SchemaName = "new_parent_accountid", DisplayName = new Label("Account Lookup", 1033), RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None), Description = new Label("Sample Lookup", 1033) } }; CreateOneToManyResponse createOneToManyRelationshipResponse = (CreateOneToManyResponse)_serviceProxy.Execute( createOneToManyRelationshipRequest); _oneToManyRelationshipId = createOneToManyRelationshipResponse.RelationshipId; _oneToManyRelationshipName = createOneToManyRelationshipRequest.OneToManyRelationship.SchemaName; Console.WriteLine( "The one-to-many relationship has been created between {0} and {1}.", "account", "campaign"); } bool accountEligibleParticipate = EligibleCreateManyToManyRelationship("account"); bool campaignEligibleParticipate = EligibleCreateManyToManyRelationship("campaign"); if (accountEligibleParticipate & amp; & campaignEligibleParticipate) { CreateManyToManyRequest createManyToManyRelationshipRequest = new CreateManyToManyRequest { IntersectEntitySchemaName = "new_accounts_campaigns", ManyToManyRelationship = new ManyToManyRelationshipMetadata { SchemaName = "new_accounts_campaigns", Entity1LogicalName = "account", Entity1AssociatedMenuConfiguration = new AssociatedMenuConfiguration { Behavior = AssociatedMenuBehavior.UseLabel, Group = AssociatedMenuGroup.Details, Label = new Label("Account", 1033), Order = 10000 }, Entity2LogicalName = "campaign", Entity2AssociatedMenuConfiguration = new AssociatedMenuConfiguration { Behavior = AssociatedMenuBehavior.UseLabel, Group = AssociatedMenuGroup.Details, Label = new Label("Campaign", 1033), Order = 10000 } } }; CreateManyToManyResponse createManytoManyRelationshipResponse = (CreateManyToManyResponse)_serviceProxy.Execute( createManyToManyRelationshipRequest); _manyToManyRelationshipId = createManytoManyRelationshipResponse.ManyToManyRelationshipId; _manyToManyRelationshipName = createManyToManyRelationshipRequest.ManyToManyRelationship.SchemaName; Console.WriteLine( "The many-to-many relationship has been created between {0} and {1}.", "account", "campaign"); } // Publish the customization changes. _serviceProxy.Execute(new PublishAllXmlRequest()); //You can use either the Name or the MetadataId of the relationship. //Retrieve the One-to-many relationship using the MetadataId. RetrieveRelationshipRequest retrieveOneToManyRequest = new RetrieveRelationshipRequest { MetadataId = _oneToManyRelationshipId }; RetrieveRelationshipResponse retrieveOneToManyResponse = (RetrieveRelationshipResponse)_serviceProxy.Execute(retrieveOneToManyRequest); Console.WriteLine("Retrieved {0} One-to-many relationship by id", retrieveOneToManyResponse.RelationshipMetadata.SchemaName); //Retrieve the Many-to-many relationship using the Name. RetrieveRelationshipRequest retrieveManyToManyRequest = new RetrieveRelationshipRequest { Name = _manyToManyRelationshipName }; RetrieveRelationshipResponse retrieveManyToManyResponse = (RetrieveRelationshipResponse)_serviceProxy.Execute(retrieveManyToManyRequest); Console.WriteLine("Retrieved {0} Many-to-Many relationship by Name", retrieveManyToManyResponse.RelationshipMetadata.MetadataId); 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 connects to the Organization service. Afterwards, /// retrieves the Contact entity record, and then enables the document management /// for the entity. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforRevert">When True, the user will be prompted to revert all /// the changes done in this sample.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforRevert) { 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(); //<snippetEnableDocumentManagement1> // Retrieve an entity for which you want to enable document management. // In this sample, we will retrieve and enable document management // for the Contact entity because by default, document management is // not enabled for this entity. RetrieveEntityRequest entityRequest = new RetrieveEntityRequest { EntityFilters = EntityFilters.All, LogicalName = Contact.EntityLogicalName, // Retrieve only the currently published changes, ignoring the changes // that have not been published. RetrieveAsIfPublished = false }; RetrieveEntityResponse entityResponse = (RetrieveEntityResponse)_serviceProxy.Execute(entityRequest); Console.WriteLine("Retrieved the contact entity."); // Get the entity from the response. EntityMetadata contactEntity = entityResponse.EntityMetadata; // Enable document management for the retrieved entity. contactEntity.IsDocumentManagementEnabled = true; // Create an update request. UpdateEntityRequest updateRequest = new UpdateEntityRequest { Entity = contactEntity }; _serviceProxy.Execute(updateRequest); // Publish the entity. // All customizations must be published before they can be used. PublishAllXmlRequest enableRequest = new PublishAllXmlRequest(); _serviceProxy.Execute(enableRequest); // Retrieve the contact entity, and verify that document management is enabled. entityResponse = (RetrieveEntityResponse)_serviceProxy.Execute(entityRequest); contactEntity = entityResponse.EntityMetadata; if (contactEntity.IsDocumentManagementEnabled.Value == true) { Console.WriteLine("Enabled document management for the contact entity."); } RevertChanges(promptforRevert); //</snippetEnableDocumentManagement1> } } // 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> /// Run this sample, which shows both how to serialize late-bound and /// early-bound entity instances to XML and how to de-serialize them back from /// XML into entity instances. /// </summary> /// <param name="serverConfig"> Contains server connection information.</param> /// <param name="promptToDelete"> When True, the user will be prompted to delete all /// created entities. public void Run(ServerConnection.Configuration serverConfig, bool promptToDelete) { 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(); #region Retrieve the contact from Microsoft CRM // Create the column set object that indicates the fields to be retrieved. var columns = new ColumnSet( "contactid", "firstname", "lastname", "jobtitle"); // Retrieve the contact from Microsoft CRM using the ID of the record that was just created. // The EntityLogicalName indicates the EntityType of the object being retrieved. var contact = (Contact)_serviceProxy.Retrieve( Contact.EntityLogicalName, _contactId, columns); Console.WriteLine("The contact for the sample has been retrieved."); #endregion #region Serialize the contact into XML and save it // Serialize the contact into XML and write it to the hard drive. var earlyBoundSerializer = new DataContractSerializer(typeof(Contact)); // Create a unique file name for the XML. String earlyboundFile = "Contact_early_" + contact.ContactId.Value.ToString("B") + ".xml"; // Write the serialized object to a file. The using statement will // ensure that the FileStream is disposed of correctly. The FileMode // will ensure that the file is overwritten if it already exists. using (var file = new FileStream(earlyboundFile, FileMode.Create)) { // Write the XML to disk. earlyBoundSerializer.WriteObject(file, contact); } Console.WriteLine( "The early-bound contact instance has been serialized to a file, {0}.", earlyboundFile); // Convert the contact to a late-bound entity instance and serialize it to disk. var lateboundContact = contact.ToEntity <Entity>(); String lateboundFile = "Contact_late_" + lateboundContact.Id.ToString("B") + ".xml"; var lateBoundSerializer = new DataContractSerializer(typeof(Entity)); // Write the serialized object to a file. using (var file = new FileStream(lateboundFile, FileMode.Create)) { lateBoundSerializer.WriteObject(file, lateboundContact); } Console.WriteLine( "The late-bound contact instance has been serialized to a file, {0}.", lateboundFile); #endregion #region De-serialize the Microsoft CRM contact from XML Contact deserializedContact = null; using (var file = new FileStream(earlyboundFile, FileMode.Open)) { deserializedContact = (Contact)earlyBoundSerializer.ReadObject(file); Console.WriteLine("The contact has been de-serialized: {0} {1}", deserializedContact.FirstName, deserializedContact.LastName); } #endregion #region Update contact in Microsoft CRM // Update the contact in Microsoft CRM to prove that the de-serialization worked. deserializedContact.JobTitle = "Plumber"; _serviceProxy.Update(deserializedContact); Console.WriteLine("The contact was updated in Microsoft CRM."); #endregion DeleteRequiredRecords(promptToDelete); } }
/// <summary> /// Create and configure the organization service proxy. /// Create a new queue instance. /// 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 = ServerConnection.GetOrganizationProxy(serverConfig)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); //<snippetCreateQueue1> // Define some anonymous types to define the range of possible // queue property values. var IncomingEmailDeliveryMethods = new { None = 0, EmailRouter = 2, ForwardMailbox = 3 }; var IncomingEmailFilteringMethods = new { AllEmailMessages = 0, EmailMessagesInResponseToCrmEmail = 1, EmailMessagesFromCrmLeadsContactsAndAccounts = 2 }; var OutgoingEmailDeliveryMethods = new { None = 0, EmailRouter = 2 }; var QueueViewType = new { Public = 0, Private = 1 }; // Create a queue instance and set its property values. Queue newQueue = new Queue() { Name = "Example Queue.", Description = "This is an example queue.", IncomingEmailDeliveryMethod = new OptionSetValue( IncomingEmailDeliveryMethods.None), IncomingEmailFilteringMethod = new OptionSetValue( IncomingEmailFilteringMethods.AllEmailMessages), OutgoingEmailDeliveryMethod = new OptionSetValue( OutgoingEmailDeliveryMethods.None), QueueViewType = new OptionSetValue( QueueViewType.Private) }; // Create a new queue instance. _queueId = _serviceProxy.Create(newQueue); //</snippetCreateQueue1> Console.WriteLine("Created {0}", newQueue.Name); 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> /// Create and configure the organization service proxy. /// Create a date/time attribute for account entity with UserLocal behavior. /// Create an account record. /// Retrieve the value in the new date/time attribute. /// Update attribute to set the behavior to DateOnly. /// Create another account record. /// Retrieve both the account records to compare the date value retrieved. /// Use the "ConvertDateandTimeRequest" message to change the behavior for the /// existing records. /// Optionally delete/revert any attributes /// that were created/changed 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)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); // Check if you are running the correct version of CRM. // This sample requires that the CRM version be 7.1.0.xxxx or later. RetrieveVersionRequest crmVersionReq = new RetrieveVersionRequest(); RetrieveVersionResponse crmVersionResp = (RetrieveVersionResponse)_serviceProxy.Execute(crmVersionReq); if (String.CompareOrdinal("7.1.0.0", crmVersionResp.Version) < 0) { // Create required records for the sample. CreateRequiredRecords(); // Use the ConvertDateandTimeBehaviorRequest SDK message to change // the behavior of the date and time values in the custom attribute // (new_SampleDateTimeAttribute) for the account entity. ConvertDateAndTimeBehaviorRequest request = new ConvertDateAndTimeBehaviorRequest() { Attributes = new EntityAttributeCollection() { new KeyValuePair <string, StringCollection>("account", new StringCollection() { "new_sampledatetimeattribute" }) }, ConversionRule = DateTimeBehaviorConversionRule.SpecificTimeZone.Value, TimeZoneCode = 190, // Time zone code for India Standard Time (IST) in CRM AutoConvert = false // Conversion must be done using ConversionRule }; // Execute the request ConvertDateAndTimeBehaviorResponse response = (ConvertDateAndTimeBehaviorResponse)_serviceProxy.Execute(request); Console.WriteLine("***************************************"); Console.WriteLine("Executed the ConvertDateAndTimeBehaviorRequest SDK message.\n"); // Wait for two seconds to let the async job be created System.Threading.Thread.Sleep(2000); if (response.JobId != null) { Console.WriteLine("An async job created with ID: {0}", response.JobId.ToString()); } // Retrieve the job completion details based on the Job ID ColumnSet cs = new ColumnSet("statecode", "statuscode", "friendlymessage", "message"); Console.WriteLine("Waiting for the async job to complete...\n"); AsyncOperation crmAsyncJob = new AsyncOperation(); while (response.JobId != null && waitCount > 0) { // Check to see if the async operation is complete crmAsyncJob = (AsyncOperation)_serviceProxy.Retrieve(AsyncOperation.EntityLogicalName, response.JobId, cs); if (crmAsyncJob.StateCode.HasValue && crmAsyncJob.StateCode.Value == AsyncOperationState.Completed && crmAsyncJob.StatusCode.Value == (int)asyncoperation_statuscode.Succeeded) { waitCount = 0; Console.WriteLine("The async job is complete.\n"); Console.WriteLine("****************************"); Console.WriteLine(crmAsyncJob.FriendlyMessage); Console.WriteLine("****************************"); Console.WriteLine(crmAsyncJob.Message); Console.WriteLine("****************************\n"); // Retrieve both the account records created earlier to check the date value Console.WriteLine("Retrieving the date and time values after the conversion...\n"); // Create a column set to define which attributes should be retrieved. ColumnSet attributes = new ColumnSet(new string[] { "name", "new_sampledatetimeattribute" }); Account retrievedAccount1 = (Account)_serviceProxy.Retrieve(Account.EntityLogicalName, _account1ID, attributes); Account retrievedAccount2 = (Account)_serviceProxy.Retrieve(Account.EntityLogicalName, _account2ID, attributes); Console.WriteLine("'{0}' is: {1}", retrievedAccount1.GetAttributeValue <String>("name"), retrievedAccount1.GetAttributeValue <DateTime>("new_sampledatetimeattribute")); Console.WriteLine("'{0}' is: {1}\n", retrievedAccount2.GetAttributeValue <String>("name"), retrievedAccount2.GetAttributeValue <DateTime>("new_sampledatetimeattribute")); Console.WriteLine("The behavior converted to DateOnly for account record ('Sample Account 1')\nbased on the specified conversion rule.\n"); Console.WriteLine("No changes to 'Sample Account 2' because it was already DateOnly.\n"); Console.WriteLine("***************************************\n"); } else { waitCount--; System.Threading.Thread.Sleep(1000); } } // If the async job is taking tool long to process, // inform the user about the same. if (waitCount == 0 && crmAsyncJob.StateCode.Value != (AsyncOperationState.Completed)) { Console.WriteLine("The async job is taking too long to complete. Aborting the sample."); } // Prompt the user to delete the records and attribute created by the sample. DeleteRequiredRecords(promptForDelete); } else { Console.WriteLine("This sample cannot be run against the current version of CRM."); Console.WriteLine("Upgrade your CRM instance to the latest version to run this sample."); } } } // 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 connects to the Organization service. Afterwards, /// a phone call is created to a contact regarding a lead. /// </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(); _service = (IOrganizationService)_serviceProxy; // Create a lead. Lead lead = new Lead() { CompanyName = "Litware, Inc." }; _leadId = _service.Create(lead); Console.Write("Lead created, "); // Create a contact. Contact contact = new Contact() { FirstName = "Dan", LastName = "Park", Address1_Line1 = "23 Market St.", Address1_City = "Sammamish", Address1_StateOrProvince = "MT", Address1_PostalCode = "99999", Telephone1 = "12345678", EMailAddress1 = "*****@*****.**" }; _contactId = _service.Create(contact); contact.ContactId = _contactId; Console.Write("contact created, "); // Create a blank phone call. PhoneCall phoneCall = new PhoneCall(); _phoneCallId = _service.Create(phoneCall); Console.Write("phone call created, "); // Create an ActivityParty for the phone call's "to" field. ActivityParty activityParty = new ActivityParty() { PartyId = new EntityReference { Id = _contactId, LogicalName = Contact.EntityLogicalName, }, ActivityId = new EntityReference { Id = _phoneCallId, LogicalName = PhoneCall.EntityLogicalName, }, ParticipationTypeMask = new OptionSetValue(9) }; // Create a phone call and add the properties we are updating. PhoneCall updatePhoneCall = new PhoneCall() { Id = _phoneCallId, Subject = "Test Phone Call", RegardingObjectId = new EntityReference { Id = _leadId, LogicalName = Lead.EntityLogicalName }, To = new ActivityParty[] { activityParty } }; // Update the phone call. UpdateRequest updateRequest = new UpdateRequest() { Target = updatePhoneCall }; _service.Execute(updateRequest); Console.Write("phone call updated.\n"); 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> /// </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(); //<snippetDumpEntityInfo1> RetrieveAllEntitiesRequest request = new RetrieveAllEntitiesRequest() { EntityFilters = EntityFilters.Entity, RetrieveAsIfPublished = true }; // Retrieve the MetaData. RetrieveAllEntitiesResponse response = (RetrieveAllEntitiesResponse)_serviceProxy.Execute(request); // Create an instance of StreamWriter to write text to a file. // The using statement also closes the StreamWriter. // To view this file, right click the file and choose open with Excel. // Excel will figure out the schema and display the information in columns. String filename = String.Concat("EntityInfo.xml"); using (StreamWriter sw = new StreamWriter(filename)) { // Create Xml Writer. XmlTextWriter metadataWriter = new XmlTextWriter(sw); // Start Xml File. metadataWriter.WriteStartDocument(); // Metadata Xml Node. metadataWriter.WriteStartElement("Metadata"); foreach (EntityMetadata currentEntity in response.EntityMetadata) { //if (currentEntity.IsIntersect.Value == false) if (true) { // Start Entity Node metadataWriter.WriteStartElement("Entity"); // Write the Entity's Information. metadataWriter.WriteElementString("EntitySchemaName", currentEntity.SchemaName); metadataWriter.WriteElementString("OTC", currentEntity.ObjectTypeCode.ToString()); metadataWriter.WriteElementString("OwnershipType", currentEntity.OwnershipType.Value.ToString()); if (currentEntity.DisplayName.UserLocalizedLabel != null) { metadataWriter.WriteElementString("DisplayName", currentEntity.DisplayName.UserLocalizedLabel.Label); } if (currentEntity.DisplayCollectionName.UserLocalizedLabel != null) { metadataWriter.WriteElementString("DisplayCollectionName", currentEntity.DisplayCollectionName.UserLocalizedLabel.Label); } metadataWriter.WriteElementString("IntroducedVersion", currentEntity.IntroducedVersion.ToString()); metadataWriter.WriteElementString("AutoRouteToOwnerQueue", currentEntity.AutoRouteToOwnerQueue.ToString()); metadataWriter.WriteElementString("CanBeInManyToMany", currentEntity.CanBeInManyToMany.Value.ToString()); metadataWriter.WriteElementString("CanBePrimaryEntityInRelationship", currentEntity.CanBePrimaryEntityInRelationship.Value.ToString()); metadataWriter.WriteElementString("CanBeRelatedEntityInRelationship", currentEntity.CanBeRelatedEntityInRelationship.Value.ToString()); metadataWriter.WriteElementString("CanCreateAttributes", currentEntity.CanCreateAttributes.Value.ToString()); metadataWriter.WriteElementString("CanCreateCharts", currentEntity.CanCreateCharts.Value.ToString()); metadataWriter.WriteElementString("CanCreateForms", currentEntity.CanCreateForms.Value.ToString()); metadataWriter.WriteElementString("CanCreateViews", currentEntity.CanCreateViews.Value.ToString()); metadataWriter.WriteElementString("CanModifyAdditionalSettings", currentEntity.CanModifyAdditionalSettings.Value.ToString()); metadataWriter.WriteElementString("CanTriggerWorkflow", currentEntity.CanTriggerWorkflow.Value.ToString()); metadataWriter.WriteElementString("IsActivity", currentEntity.IsActivity.Value.ToString()); //metadataWriter.WriteElementString("ActivityTypeMask", currentEntity.ActivityTypeMask.ToString()); metadataWriter.WriteElementString("IsActivityParty", currentEntity.IsActivityParty.Value.ToString()); metadataWriter.WriteElementString("IsAuditEnabled", currentEntity.IsAuditEnabled.Value.ToString()); metadataWriter.WriteElementString("IsAvailableOffline", currentEntity.IsAvailableOffline.ToString()); metadataWriter.WriteElementString("IsChildEntity", currentEntity.IsChildEntity.ToString()); metadataWriter.WriteElementString("IsConnectionsEnabled", currentEntity.IsConnectionsEnabled.ManagedPropertyLogicalName.ToString()); metadataWriter.WriteElementString("IsCustomEntity", currentEntity.IsCustomEntity.Value.ToString()); metadataWriter.WriteElementString("IsCustomizable", currentEntity.IsCustomizable.Value.ToString()); metadataWriter.WriteElementString("IsDocumentManagementEnabled", currentEntity.IsDocumentManagementEnabled.Value.ToString()); metadataWriter.WriteElementString("IsDuplicateDetectionEnabled", currentEntity.IsDuplicateDetectionEnabled.Value.ToString()); if (currentEntity.IsEnabledForCharts != null) { metadataWriter.WriteElementString("IsEnabledForCharts", currentEntity.IsEnabledForCharts.Value.ToString()); } metadataWriter.WriteElementString("IsImportable", currentEntity.IsImportable.Value.ToString()); metadataWriter.WriteElementString("IsIntersect", currentEntity.IsIntersect.Value.ToString()); metadataWriter.WriteElementString("IsMailMergeEnabled", currentEntity.IsMailMergeEnabled.Value.ToString()); metadataWriter.WriteElementString("IsManaged", currentEntity.IsManaged.Value.ToString()); metadataWriter.WriteElementString("IsMappable", currentEntity.IsMappable.Value.ToString()); metadataWriter.WriteElementString("IsReadingPaneEnabled", currentEntity.IsReadingPaneEnabled.Value.ToString()); metadataWriter.WriteElementString("IsRenameable", currentEntity.IsRenameable.Value.ToString()); metadataWriter.WriteElementString("IsValidForAdvancedFind", currentEntity.IsValidForAdvancedFind.Value.ToString()); metadataWriter.WriteElementString("IsValidForQueue", currentEntity.IsValidForQueue.Value.ToString()); metadataWriter.WriteElementString("IsVisibleInMobile", currentEntity.IsVisibleInMobile.Value.ToString()); metadataWriter.WriteElementString("PrimaryIdAttribute", currentEntity.PrimaryIdAttribute); metadataWriter.WriteElementString("PrimaryNameAttribute", currentEntity.PrimaryNameAttribute); metadataWriter.WriteElementString("ReportViewName", currentEntity.ReportViewName); metadataWriter.WriteElementString("RecurrenceBaseEntityLogicalName", currentEntity.RecurrenceBaseEntityLogicalName); if (currentEntity.Description.UserLocalizedLabel != null) { metadataWriter.WriteElementString("Description", currentEntity.Description.UserLocalizedLabel.Label); } // End Entity Node metadataWriter.WriteEndElement(); } } // End Metadata Xml Node metadataWriter.WriteEndElement(); metadataWriter.WriteEndDocument(); // Close xml writer. metadataWriter.Close(); } Console.WriteLine("Done."); //</snippetDumpEntityInfo1> //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 connects to the Organization service. Afterwards, /// basic create, retrieve, update, and delete entity operations are performed. /// </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(); CreateRequiredRecords(); //Read the descriptive data from the XML file XDocument xmlDoc = XDocument.Load("../../ImportJob.xml"); //Create a collection of anonymous type references to each of the Web Resources var webResources = from webResource in xmlDoc.Descendants("webResource") select new { path = webResource.Element("path").Value, displayName = webResource.Element("displayName").Value, description = webResource.Element("description").Value, name = webResource.Element("name").Value, type = webResource.Element("type").Value }; // Loop through the collection creating Web Resources int counter = 0; foreach (var webResource in webResources) { //Set the Web Resource properties WebResource wr = new WebResource { Content = getEncodedFileContents(@"../../" + webResource.path), DisplayName = webResource.displayName, Description = webResource.description, Name = _customizationPrefix + webResource.name, LogicalName = WebResource.EntityLogicalName, WebResourceType = new OptionSetValue(Int32.Parse(webResource.type)) }; // Using CreateRequest because we want to add an optional parameter CreateRequest cr = new CreateRequest { Target = wr }; //Set the SolutionUniqueName optional parameter so the Web Resources will be // created in the context of a specific solution. cr.Parameters.Add("SolutionUniqueName", _ImportWebResourcesSolutionUniqueName); CreateResponse cresp = (CreateResponse)_serviceProxy.Execute(cr); // Capture the id values for the Web Resources so the sample can delete them. _webResourceIds[counter] = cresp.id; counter++; Console.WriteLine("Created Web Resource: {0}", webResource.displayName); } 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> /// Create and configure the organization service proxy. /// Create the connection role instances. /// Associate the connection roles. /// 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 = ServerConnection.GetOrganizationProxy(serverConfig)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); // Create the Connection Role 1 ConnectionRole newConnectionRole1 = new ConnectionRole { Name = "Example Connection Role 1", Category = new OptionSetValue((int)connectionrole_category.Business), }; _connectionRole1Id = _serviceProxy.Create(newConnectionRole1); Console.WriteLine("Created {0}.", newConnectionRole1.Name); // Create a related Connection Role Object Type Code record for Account ConnectionRoleObjectTypeCode newAccountConnectionRole1TypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _connectionRole1Id), AssociatedObjectTypeCode = Account.EntityLogicalName }; _serviceProxy.Create(newAccountConnectionRole1TypeCode); Console.WriteLine( "Created a related Connection Role 1 Object Type Code record for Account." ); // Create a related Connection Role Object Type Code record for Contact ConnectionRoleObjectTypeCode newContactConnectionRole1TypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _connectionRole1Id), AssociatedObjectTypeCode = Contact.EntityLogicalName }; _serviceProxy.Create(newContactConnectionRole1TypeCode); Console.WriteLine( "Created a related Connection Role 1 Object Type Code record for Contact." ); // Create the Connection Role 2 ConnectionRole newConnectionRole2 = new ConnectionRole { Name = "Example Connection Role 2", Category = new OptionSetValue((int)connectionrole_category.Business), }; _connectionRole2Id = _serviceProxy.Create(newConnectionRole2); Console.WriteLine("Created {0}.", newConnectionRole2.Name); // Create a related Connection Role 2 Object Type Code record for Account ConnectionRoleObjectTypeCode newAccountConnectionRole2TypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _connectionRole2Id), AssociatedObjectTypeCode = Account.EntityLogicalName }; _serviceProxy.Create(newAccountConnectionRole2TypeCode); Console.WriteLine( "Created a related Connection Role 2 Object Type Code record for Account." ); // Create a related Connection Role 2 Object Type Code record for Contact ConnectionRoleObjectTypeCode newContactConnectionRole2TypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _connectionRole2Id), AssociatedObjectTypeCode = Contact.EntityLogicalName }; _serviceProxy.Create(newContactConnectionRole2TypeCode); Console.WriteLine( "Created a related Connection Role 2 Object Type Code record for Contact." ); //<snippetAssociateReciprocalConnectionRoles> // Associate the connection roles AssociateRequest associateConnectionRoles = new AssociateRequest { Target = new EntityReference(ConnectionRole.EntityLogicalName, _connectionRole1Id), RelatedEntities = new EntityReferenceCollection() { new EntityReference(ConnectionRole.EntityLogicalName, _connectionRole2Id) }, // The name of the relationship connection role association // relationship in MS CRM Relationship = new Relationship() { PrimaryEntityRole = EntityRole.Referencing, // Referencing or Referenced based on N:1 or 1:N reflexive relationship. SchemaName = "connectionroleassociation_association" } }; _serviceProxy.Execute(associateConnectionRoles); Console.WriteLine("Associated the connection roles."); //</snippetAssociateReciprocalConnectionRoles> 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> /// Create and configure the organization service proxy. /// Initiate the method to create any data that this sample requires. /// Reschedule an instance of the recurring appointment series. /// Cancel another instance of the recurring appointment series. /// 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)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); // Call the method to create any data that this sample requires. CreateRequiredRecords(); //<snippetRescheduleandCancelRecurringAppointmentInstance1> // Retrieve the individual appointment instance that falls on or after // 10 days from today. Basically this will be the second instance in the // recurring appointment series. QueryExpression instanceQuery = new QueryExpression { EntityName = Appointment.EntityLogicalName, ColumnSet = new ColumnSet { Columns = { "activityid", "scheduledstart", "scheduledend" } }, Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "seriesid", Operator = ConditionOperator.Equal, Values = { _recurringAppointmentMasterId } }, new ConditionExpression { AttributeName = "scheduledstart", Operator = ConditionOperator.OnOrAfter, Values = { DateTime.Today.AddDays(10) } } } } }; EntityCollection individualAppointments = _serviceProxy.RetrieveMultiple(instanceQuery); //<snippetRescheduleandCancelRecurringAppointmentInstance2> #region Reschedule an instance of recurring appointment // Update the scheduled start and end dates of the appointment // to reschedule it. Appointment updateAppointment = new Appointment { ActivityId = individualAppointments.Entities.Select(x => (Appointment)x).First().ActivityId, ScheduledStart = individualAppointments.Entities.Select(x => (Appointment)x).First().ScheduledStart.Value.AddHours(1), ScheduledEnd = individualAppointments.Entities.Select(x => (Appointment)x).First().ScheduledEnd.Value.AddHours(2) }; RescheduleRequest reschedule = new RescheduleRequest { Target = updateAppointment }; RescheduleResponse rescheduled = (RescheduleResponse)_serviceProxy.Execute(reschedule); Console.WriteLine("Rescheduled the second instance of the recurring appointment."); #endregion Reschedule an instance of recurring appointment //</snippetRescheduleandCancelRecurringAppointmentInstance2> //<snippetRescheduleandCancelRecurringAppointmentInstance3> #region Cancel an instance of recurring appointment // Cancel the last instance of the appointment. The status of this appointment // instance is set to 'Canceled'. You can view this appoinyment instance under // the 'All Activities' view. SetStateRequest appointmentRequest = new SetStateRequest { State = new OptionSetValue((int)AppointmentState.Canceled), Status = new OptionSetValue(4), EntityMoniker = new EntityReference(Appointment.EntityLogicalName, new Guid(individualAppointments.Entities.Select(x => (Appointment)x).Last().ActivityId.ToString())) }; _serviceProxy.Execute(appointmentRequest); Console.WriteLine("Canceled the last instance of the recurring appointment."); #endregion Cancel an instance of recurring appointment //</snippetRescheduleandCancelRecurringAppointmentInstance3> //</snippetRescheduleandCancelRecurringAppointmentInstance1> 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 connects to the Organization service. Afterwards, it /// creates/retrieves a system user, and /// updates the system user to associate with the salesperson role. /// Note: Creating a user is only supported /// in an on-premises/active directory environment. /// </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 is properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { _serviceProxy.EnableProxyTypes(); CreateRequiredRecords(); // Retrieve a user. SystemUser user = _serviceProxy.Retrieve(SystemUser.EntityLogicalName, _userId, new ColumnSet(new String[] { "systemuserid", "firstname", "lastname" })).ToEntity <SystemUser>(); if (user != null) { Console.WriteLine("{1} {0} user account is retrieved.", user.FirstName, user.LastName); // Find the role. QueryExpression query = new QueryExpression { EntityName = "role", ColumnSet = new ColumnSet("roleid"), Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "name", Operator = ConditionOperator.Equal, Values = { _givenRole } } } } }; // Get the role. EntityCollection roles = _serviceProxy.RetrieveMultiple(query); // Disassociate the role. if (roles.Entities.Count > 0) { Role salesRole = _serviceProxy.RetrieveMultiple(query).Entities[0].ToEntity <Role>(); Console.WriteLine("Role {0} is retrieved.", _givenRole); _serviceProxy.Disassociate( "systemuser", user.Id, new Relationship("systemuserroles_association"), new EntityReferenceCollection() { new EntityReference("role", salesRole.Id) }); Console.WriteLine("Role {0} is disassociated from user {1} {2}.", _givenRole, user.FirstName, user.LastName); } } } } // 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 connects to the Organization service and creates the /// OrganizationServiceContext. Then, several entity creation and relationship /// operations are performed. /// </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(); _service = (IOrganizationService)_serviceProxy; CreateRequiredRecords(); // The OrganizationServiceContext is an object that wraps the service // proxy and allows creating/updating multiple records simultaneously. _orgContext = new OrganizationServiceContext(_service); // Create a new contact called Mary Kay Andersen. var contact = new Contact() { FirstName = "Mary Kay", LastName = "Andersen", Address1_Line1 = "23 Market St.", Address1_City = "Sammamish", Address1_StateOrProvince = "MT", Address1_PostalCode = "99999", Telephone1 = "12345678", EMailAddress1 = "*****@*****.**", Id = Guid.NewGuid() }; _contactId = contact.Id; _orgContext.AddObject(contact); Console.Write("Instantiating contact, "); // Create an account called Contoso. var account = new Account() { Name = "Contoso", Address1_City = "Redmond", // set the account category to 'Preferred Customer' AccountCategoryCode = new OptionSetValue(1), LastUsedInCampaign = DateTime.Now, MarketCap = new Money(120000), DoNotEMail = true, Description = "Contoso is a fictional company!", Id = Guid.NewGuid(), }; _accountId = account.Id; Console.Write("instantiating account, "); // Set Mary Kay Andersen as the primary contact _orgContext.AddRelatedObject( contact, new Relationship("account_primary_contact"), account); SaveChangesHelper(contact, account); Console.WriteLine("and creating both records in CRM."); // Remove the primary contact value from Mary Kay Andersen _orgContext.Attach(contact); _orgContext.DeleteLink( contact, new Relationship("account_primary_contact"), account); SaveChangesHelper(contact, account); Console.Write("Removing primary contact status, "); // Add Mary Kay Andersen to the contact list for the account Contoso. _orgContext.Attach(account); _orgContext.Attach(contact); _orgContext.AddLink( account, new Relationship("contact_customer_accounts"), contact); SaveChangesHelper(contact, account); Console.WriteLine("and adding contact to account's contact list."); // Add a note with a document attachment to the contact's record. var attachment = File.OpenRead("sample.txt"); var data = new byte[attachment.Length]; attachment.Read(data, 0, (int)attachment.Length); var note = new Annotation() { Subject = "Note subject...", NoteText = "Note Details....", DocumentBody = Convert.ToBase64String(data), FileName = Path.GetFileName(attachment.Name), MimeType = "text/plain", Id = Guid.NewGuid(), // Associate the note to the contact. ObjectId = contact.ToEntityReference(), ObjectTypeCode = Contact.EntityLogicalName }; _annotationId = note.Id; Console.Write("Instantiating a note, "); _orgContext.AddObject(note); _orgContext.Attach(contact); // Set the contact as the Regarding attribute of the note. _orgContext.AddLink( contact, new Relationship("Contact_Annotation"), note); SaveChangesHelper(note, contact); Console.WriteLine("creating the note in CRM and linking to contact."); // Change the owning user of the contact Mary Kay Andersen // Find a user with an email address of "*****@*****.**" var newOwner = (from u in _orgContext.CreateQuery <SystemUser>() where u.InternalEMailAddress == "*****@*****.**" select u).Single(); AssignRequest assignRequest = new AssignRequest() { Target = contact.ToEntityReference(), Assignee = newOwner.ToEntityReference() }; _orgContext.Execute(assignRequest); Console.WriteLine("Changing ownership of contact record."); // Create a new price list called Retail Price List. var priceList = new PriceLevel() { Name = "Retail Price List", BeginDate = DateTime.Now, EndDate = DateTime.Now, Description = "Contoso's primary pricelist.", Id = Guid.NewGuid() }; _priceLevelId = priceList.Id; _orgContext.AddObject(priceList); Console.Write("Instantiating price list "); // Create a new product called Widget A. var newProduct = new Product() { Name = "Widget A", Description = "Industrial widget for hi-tech industries", ProductStructure = new OptionSetValue(1), // 1 = Product QuantityOnHand = 2, ProductNumber = "WIDG-A", Price = new Money(decimal.Parse("12.50")), QuantityDecimal = 2, // Sets the Decimals Supported value Id = Guid.NewGuid(), DefaultUoMScheduleId = new EntityReference( UoMSchedule.EntityLogicalName, _orgContext.CreateQuery <UoMSchedule>().First().Id), DefaultUoMId = new EntityReference( UoM.EntityLogicalName, _orgContext.CreateQuery <UoM>().First().Id) }; _productId = newProduct.Id; _orgContext.AddObject(newProduct); Console.WriteLine("and product."); SaveChangesHelper(priceList, newProduct); // Add Widget A to the Retail Price List. var priceLevelProduct = new ProductPriceLevel() { ProductId = newProduct.ToEntityReference(), UoMId = newProduct.DefaultUoMId, Amount = new Money(decimal.Parse("12.50")), PriceLevelId = priceList.ToEntityReference(), Id = Guid.NewGuid() }; _productPriceLevelId = priceLevelProduct.Id; _orgContext.AddObject(priceLevelProduct); Console.Write("Associating product to price list, "); // Publish the product SetStateRequest publishRequest = new SetStateRequest { EntityMoniker = newProduct.ToEntityReference(), State = new OptionSetValue((int)ProductState.Active), Status = new OptionSetValue(1) }; _serviceProxy.Execute(publishRequest); Console.WriteLine("and publishing the product."); // Create a new quote for Contoso. var newQuote = new Quote() { Name = "Quotation for Contoso", // Sets the pricelist to the one we've just created PriceLevelId = priceList.ToEntityReference(), Id = Guid.NewGuid(), CustomerId = account.ToEntityReference() }; _quoteId = newQuote.Id; _orgContext.AddObject(newQuote); _orgContext.Attach(account); _orgContext.AddLink( newQuote, new Relationship("quote_customer_accounts"), account); Console.Write("Instantiating a quote, "); // Add a quote product to this quote. var quoteProduct = new QuoteDetail() { ProductId = newProduct.ToEntityReference(), Quantity = 1, QuoteId = newQuote.ToEntityReference(), UoMId = newProduct.DefaultUoMId, Id = Guid.NewGuid() }; _quoteDetailId = quoteProduct.Id; _orgContext.AddObject(quoteProduct); Console.WriteLine("and adding product to quote."); // Create a sales opportunity with Contoso. var oppty = new Opportunity() { Name = "Interested in Widget A", EstimatedCloseDate = DateTime.Now.AddDays(30.0), EstimatedValue = new Money(decimal.Parse("300000.00")), CloseProbability = 25, // 25% probability of closing this deal IsRevenueSystemCalculated = false, // user-calculated revenue OpportunityRatingCode = new OptionSetValue(2), // warm CustomerId = account.ToEntityReference(), Id = Guid.NewGuid() }; _opportunityId = oppty.Id; _orgContext.AddObject(oppty); Console.Write("Instantiating opportunity, "); //_orgContext.AddLink( // oppty, // new Relationship("opportunity_customer_accounts"), // account); SaveChangesHelper(priceList, newQuote, newProduct, priceLevelProduct, quoteProduct, oppty, account); Console.WriteLine("and creating all records in CRM."); // Associate quote to contact, which adds the Contact record in the // "Other Contacts" section of a Quote record. _orgContext.Attach(contact); _orgContext.Attach(newQuote); _orgContext.AddLink( contact, new Relationship("contactquotes_association"), newQuote); SaveChangesHelper(contact, newQuote); Console.WriteLine("Associating contact and quote."); // Create a case for Mary Kay Andersen. var serviceRequest = new Incident() { Title = "Problem with Widget B", PriorityCode = new OptionSetValue(1), // 1 = High CaseOriginCode = new OptionSetValue(1), // 1 = Phone CaseTypeCode = new OptionSetValue(2), // 2 = Problem SubjectId = new EntityReference( Subject.EntityLogicalName, _orgContext.CreateQuery <Subject>() .First().Id), // use the default subject Description = "Customer can't switch the product on.", FollowupBy = DateTime.Now.AddHours(3.0), // follow-up in 3 hours CustomerId = contact.ToEntityReference(), Id = Guid.NewGuid() }; _incidentId = serviceRequest.Id; _orgContext.AddObject(serviceRequest); _orgContext.Attach(contact); _orgContext.AddLink( serviceRequest, new Relationship("incident_customer_contacts"), contact); SaveChangesHelper(serviceRequest, contact); Console.WriteLine("Creating service case for contact."); // Deactivate the Mary Kay Andersen contact record. SetStateRequest setInactiveRequest = new SetStateRequest { EntityMoniker = contact.ToEntityReference(), State = new OptionSetValue((int)ContactState.Inactive), Status = new OptionSetValue(2) }; _orgContext.Execute(setInactiveRequest); Console.WriteLine("Deactivating the contact record."); 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 XAML to define the custom workflow. Afterwards, /// it creates the workflow record with this XAML and then activates it. /// </summary> /// <remarks> /// Visit http://msdn.microsoft.com/en-us/library/gg309458.aspx /// for instructions on enabling XAML workflows on the Microsoft Dynamics CRM server. /// </remarks> /// <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(); CreateRequiredRecords(); #region Define the workflow in XAML // Define the workflow using XAML. This is typically done in the Visual Studio // workflow designer. string xamlWF = @"<?xml version=""1.0"" encoding=""utf-16""?> <Activity x:Class=""SampleWF"" xmlns=""http://schemas.microsoft.com/netfx/2009/xaml/activities"" xmlns:mva=""clr-namespace:Microsoft.VisualBasic.Activities;assembly=System.Activities, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" xmlns:mxs=""clr-namespace:Microsoft.Xrm.Sdk;assembly=Microsoft.Xrm.Sdk, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" xmlns:mxswa=""clr-namespace:Microsoft.Xrm.Sdk.Workflow.Activities;assembly=Microsoft.Xrm.Sdk.Workflow, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"" xmlns:s=""clr-namespace:System;assembly=mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" xmlns:scg=""clr-namespace:System.Collections.Generic;assembly=mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" xmlns:srs=""clr-namespace:System.Runtime.Serialization;assembly=System.Runtime.Serialization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" xmlns:this=""clr-namespace:"" xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""> <x:Members> <x:Property Name=""InputEntities"" Type=""InArgument(scg:IDictionary(x:String, mxs:Entity))"" /> <x:Property Name=""CreatedEntities"" Type=""InArgument(scg:IDictionary(x:String, mxs:Entity))"" /> </x:Members> <this:SampleWF.InputEntities> <InArgument x:TypeArguments=""scg:IDictionary(x:String, mxs:Entity)"" /> </this:SampleWF.InputEntities> <this:SampleWF.CreatedEntities> <InArgument x:TypeArguments=""scg:IDictionary(x:String, mxs:Entity)"" /> </this:SampleWF.CreatedEntities> <mva:VisualBasic.Settings>Assembly references and imported namespaces for internal implementation</mva:VisualBasic.Settings> <mxswa:Workflow> <Sequence> <Sequence.Variables> <Variable x:TypeArguments=""x:Int32"" Default=""[40]"" Name=""probability_value"" /> <Variable x:TypeArguments=""mxs:Entity"" Default=""[CreatedEntities("primaryEntity#Temp")]"" Name=""CreatedEntity"" /> </Sequence.Variables> <Assign x:TypeArguments=""mxs:Entity"" To=""[CreatedEntity]"" Value=""[New Entity("opportunity")]"" /> <Assign x:TypeArguments=""s:Guid"" To=""[CreatedEntity.Id]"" Value=""[InputEntities("primaryEntity").Id]"" /> <mxswa:SetEntityProperty Attribute=""closeprobability"" Entity=""[CreatedEntity]"" EntityName=""opportunity"" TargetType=""[Type.GetType("probability_value")]"" Value=""[probability_value]""> </mxswa:SetEntityProperty> <mxswa:UpdateEntity Entity=""[CreatedEntity]"" EntityName=""opportunity"" /> <Assign x:TypeArguments=""mxs:Entity"" To=""[InputEntities("primaryEntity")]"" Value=""[CreatedEntity]"" /> <Persist /> </Sequence> </mxswa:Workflow> </Activity>"; #endregion Define the workflow in XAML #region Create the workflow //<snippetCreateRealTimeWorkflow1> // Create a real-time workflow. // The workflow should execute after a new opportunity is created // and run in the context of the logged on user. Workflow workflow = new Workflow() { // These properties map to the New Process form settings in the web application. Name = "Set closeprobability on opportunity create (real-time)", Type = new OptionSetValue((int)WorkflowType.Definition), Category = new OptionSetValue((int)WorkflowCategory.Workflow), PrimaryEntity = Opportunity.EntityLogicalName, Mode = new OptionSetValue((int)WorkflowMode.Realtime), // Additional settings from the second New Process form. Description = @"When an opportunity is created, this workflow" + " sets the closeprobability field of the opportunity record to 40%.", OnDemand = false, Subprocess = false, Scope = new OptionSetValue((int)WorkflowScope.User), RunAs = new OptionSetValue((int)workflow_runas.CallingUser), SyncWorkflowLogOnFailure = true, TriggerOnCreate = true, CreateStage = new OptionSetValue((int)workflow_stage.Postoperation), Xaml = xamlWF, // Other properties not in the web forms. LanguageCode = 1033, // U.S. English }; _workflowId = _serviceProxy.Create(workflow); //</snippetCreateRealTimeWorkflow1> Console.WriteLine("Created Workflow: " + workflow.Name); #endregion Create the workflow #region Activate the workflow // Activate the workflow. Initially, the workflow is created in // a Draft state and must be activated before it can run. var activateRequest = new SetStateRequest { EntityMoniker = new EntityReference (Workflow.EntityLogicalName, _workflowId), State = new OptionSetValue((int)WorkflowState.Activated), Status = new OptionSetValue((int)workflow_statuscode.Activated) }; _serviceProxy.Execute(activateRequest); Console.WriteLine("Activated Workflow: " + workflow.Name); #endregion Activate the workflow 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> /// Create and configure the organization service proxy. /// Create a new connectionrole instance and set the object type. /// 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 = ServerConnection.GetOrganizationProxy(serverConfig)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); //<snippetCreateConnectionRole1> // 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 for account and contact ConnectionRole newConnectionRole = new ConnectionRole { Name = "Example Connection Role", Category = new OptionSetValue(Categories.Business) }; _connectionRoleId = _serviceProxy.Create(newConnectionRole); Console.WriteLine("Created {0}.", newConnectionRole.Name); // Create a related Connection Role Object Type Code record for Account ConnectionRoleObjectTypeCode newAccountConnectionRoleTypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _connectionRoleId), AssociatedObjectTypeCode = Account.EntityLogicalName }; _serviceProxy.Create(newAccountConnectionRoleTypeCode); Console.WriteLine( "Created a related Connection Role Object Type Code record for Account."); // Create a related Connection Role Object Type Code record for Contact ConnectionRoleObjectTypeCode newContactConnectionRoleTypeCode = new ConnectionRoleObjectTypeCode { ConnectionRoleId = new EntityReference( ConnectionRole.EntityLogicalName, _connectionRoleId), AssociatedObjectTypeCode = Contact.EntityLogicalName }; _serviceProxy.Create(newContactConnectionRoleTypeCode); Console.WriteLine( "Created a related Connection Role Object Type Code record for Contact."); //</snippetCreateConnectionRole1> 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> /// Create and configure the organization service proxy. /// Creates an account and some associated letters with a nested operation. /// Updates those records with a nested operation. // </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 = ServerConnection.GetOrganizationProxy(serverConfig)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); _service = (IOrganizationService)_serviceProxy; //<snippetCompoundCreateUpdate1> //Define the account for which we will add letters Account accountToCreate = new Account { Name = "Example Account" }; //Define the IDs of the related letters we will create _letterIds = new[] { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() }; //This acts as a container for each letter we create. Note that we haven't //define the relationship between the letter and account yet. EntityCollection relatedLettersToCreate = new EntityCollection { EntityName = Letter.EntityLogicalName, Entities = { new Letter { Subject = "Letter 1", ActivityId = _letterIds[0] }, new Letter { Subject = "Letter 2", ActivityId = _letterIds[1] }, new Letter { Subject = "Letter 3", ActivityId = _letterIds[2] } } }; //Creates the reference between which relationship between Letter and //Account we would like to use. Relationship letterRelationship = new Relationship("Account_Letters"); //Adds the letters to the account under the specified relationship accountToCreate.RelatedEntities.Add(letterRelationship, relatedLettersToCreate); //Passes the Account (which contains the letters) _accountId = _service.Create(accountToCreate); Console.WriteLine("An account and {0} letters were created.", _letterIds.Length); //Now we run through many of the same steps as the above "Create" example Account accountToUpdate = new Account { Name = "Example Account - Updated", AccountId = _accountId }; EntityCollection relatedLettersToUpdate = new EntityCollection { EntityName = Letter.EntityLogicalName, Entities = { new Letter { Subject = "Letter 1 - Updated", ActivityId = _letterIds[0] }, new Letter { Subject = "Letter 2 - Updated", ActivityId = _letterIds[1] }, new Letter { Subject = "Letter 3 - Updated", ActivityId = _letterIds[2] } } }; accountToUpdate.RelatedEntities.Add(letterRelationship, relatedLettersToUpdate); //This will update the account as well as all of the related letters _service.Update(accountToUpdate); Console.WriteLine("An account and {0} letters were updated.", _letterIds.Length); //</snippetCompoundCreateUpdate1> 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 connects to the Organization service. Afterwards, /// an annotation is created, uploaded, then finally downloaded. /// </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 { //<snippetUploadAndDownloadAttachment1> // 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(); #region Create and Upload annotation attachment // Instantiate an Annotation object. // See the Entity Metadata topic in the SDK documentation to determine // which attributes must be set for each entity. Annotation setupAnnotation = new Annotation() { Subject = "Example Annotation", FileName = "ExampleAnnotationAttachment.txt", DocumentBody = Convert.ToBase64String( new UnicodeEncoding().GetBytes("Sample Annotation Text")), MimeType = "text/plain" }; // Create the Annotation object. _annotationId = _serviceProxy.Create(setupAnnotation); Console.Write("{0} created with an attachment", setupAnnotation.Subject); #endregion Create and Upload annotation attachment #region Download attachment from annotation record // Define columns to retrieve from the annotation record. ColumnSet cols = new ColumnSet("filename", "documentbody"); // Retrieve the annotation record. Annotation retrievedAnnotation = (Annotation)_serviceProxy.Retrieve("annotation", _annotationId, cols); Console.WriteLine(", and retrieved."); _fileName = retrievedAnnotation.FileName; // Download the attachment in the current execution folder. using (FileStream fileStream = new FileStream(retrievedAnnotation.FileName, FileMode.OpenOrCreate)) { byte[] fileContent = Convert.FromBase64String(retrievedAnnotation.DocumentBody); fileStream.Write(fileContent, 0, fileContent.Length); } Console.WriteLine("Attachment downloaded."); #endregion Download attachment from annotation record DeleteRequiredRecords(promptforDelete); } //</snippetUploadAndDownloadAttachment1> } // 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> /// Retrieve a role from CRM. /// Assign that role to a team. /// <param name="organizationFriendlyName">The friendly name of /// the target organization.</param> /// <param name="discoveryServer">The name of the discovery server.</param> /// <param name="promptForDelete">Indicates whether to prompt the user /// to delete the records created in this sample.</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(); _service = (IOrganizationService)_serviceProxy; // Call the method to create any data that this sample requires. CreateRequiredRecords(); // Retrieve a role from CRM. QueryExpression query = new QueryExpression { EntityName = Role.EntityLogicalName, ColumnSet = new ColumnSet("roleid"), Criteria = new FilterExpression { Conditions = { // You would replace the condition below with an actual role // name, or skip this query if you had a role id. new ConditionExpression { AttributeName = "name", Operator = ConditionOperator.Equal, Values = { _roleName } } } } }; Role role = _service.RetrieveMultiple(query).Entities. Cast <Role>().First(); // Add the role to the team. _service.Associate( Team.EntityLogicalName, _teamId, new Relationship("teamroles_association"), new EntityReferenceCollection() { new EntityReference(Role.EntityLogicalName, _roleId) }); Console.WriteLine("Assigned role to team"); 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> /// Demonstrates how to programmatically execute a workflow. /// </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(); OrganizationServiceContext _orgContext = new OrganizationServiceContext(_serviceProxy); CreateRequiredRecords(); // Create an ExecuteWorkflow request. ExecuteWorkflowRequest request = new ExecuteWorkflowRequest() { WorkflowId = _workflowId, EntityId = _leadId }; Console.Write("Created ExecuteWorkflow request, "); // Execute the workflow. ExecuteWorkflowResponse response = (ExecuteWorkflowResponse)_serviceProxy.Execute(request); Console.WriteLine("and sent request to service."); #region Check success ColumnSet cols = new ColumnSet("statecode"); QueryByAttribute retrieveOpQuery = new QueryByAttribute(); retrieveOpQuery.EntityName = AsyncOperation.EntityLogicalName; retrieveOpQuery.ColumnSet = cols; retrieveOpQuery.AddAttributeValue("asyncoperationid", response.Id); // Wait for the asyncoperation to complete. // (wait no longer than 1 minute) for (int i = 0; i < 60; i++) { System.Threading.Thread.Sleep(1000); EntityCollection retrieveOpResults = _serviceProxy.RetrieveMultiple(retrieveOpQuery); if (retrieveOpResults.Entities.Count() > 0) { AsyncOperation op = (AsyncOperation)retrieveOpResults.Entities[0]; if (op.StateCode == AsyncOperationState.Completed) { _asyncOperationId = op.AsyncOperationId.Value; Console.WriteLine("AsyncOperation completed successfully."); break; } } if (i == 59) { throw new TimeoutException("AsyncOperation failed to complete in under one minute."); } } // Retrieve the task that was created by the workflow. cols = new ColumnSet("activityid"); QueryByAttribute retrieveActivityQuery = new QueryByAttribute(); retrieveActivityQuery.EntityName = PhoneCall.EntityLogicalName; retrieveActivityQuery.ColumnSet = cols; retrieveActivityQuery.AddAttributeValue("subject", "First call to Diogo Andrade"); EntityCollection results = _serviceProxy.RetrieveMultiple(retrieveActivityQuery); if (results.Entities.Count() == 0) { throw new InvalidOperationException("Phone call activity was not successfully created"); } else { Console.WriteLine("Phone call activity successfully created from workflow."); } #endregion Check success 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> /// Main. Runs the sample and provides error output. /// <param name="args">Array of arguments to Main method.</param> /// </summary> static public void Main(string[] args) { try { // Obtain the target organization's Web address and client logon // credentials from the user. ServerConnection serverConnect = new ServerConnection(); ServerConnection.Configuration config = serverConnect.GetServerConfiguration(); AssignVisualizationToUser app = new AssignVisualizationToUser(); app.Run(config, true); } catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ex) { Console.WriteLine("The application terminated with an error."); Console.WriteLine("Timestamp: {0}", ex.Detail.Timestamp); Console.WriteLine("Code: {0}", ex.Detail.ErrorCode); Console.WriteLine("Message: {0}", ex.Detail.Message); Console.WriteLine("Plugin Trace: {0}", ex.Detail.TraceText); Console.WriteLine("Inner Fault: {0}", null == ex.Detail.InnerFault ? "No Inner Fault" : "Has Inner Fault"); } catch (System.TimeoutException ex) { Console.WriteLine("The application terminated with an error."); Console.WriteLine("Message: {0}", ex.Message); Console.WriteLine("Stack Trace: {0}", ex.StackTrace); Console.WriteLine("Inner Fault: {0}", null == ex.InnerException.Message ? "No Inner Fault" : ex.InnerException.Message); } catch (System.Exception ex) { Console.WriteLine("The application terminated with an error."); Console.WriteLine(ex.Message); // Display the details of the inner exception. if (ex.InnerException != null) { Console.WriteLine(ex.InnerException.Message); FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> fe = ex.InnerException as FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault>; if (fe != null) { Console.WriteLine("Timestamp: {0}", fe.Detail.Timestamp); Console.WriteLine("Code: {0}", fe.Detail.ErrorCode); Console.WriteLine("Message: {0}", fe.Detail.Message); Console.WriteLine("Plugin Trace: {0}", fe.Detail.TraceText); Console.WriteLine("Inner Fault: {0}", null == fe.Detail.InnerFault ? "No Inner Fault" : "Has Inner Fault"); } } } // Additional exceptions to catch: SecurityTokenValidationException, ExpiredSecurityTokenException, // SecurityAccessDeniedException, MessageSecurityException, and SecurityNegotiationException. finally { Console.WriteLine("Press <Enter> to exit."); Console.ReadLine(); } }
/// <summary> /// </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 = ServerConnection.GetOrganizationProxy(serverConfig)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); //<snippetDumpEntityPrivileges1> RetrieveAllEntitiesRequest request = new RetrieveAllEntitiesRequest() { EntityFilters = EntityFilters.Privileges, // When RetrieveAsIfPublished property is set to false, retrieves only the currently published changes. Defaulted setting is to false. // When RetrieveAsIfPublished property is set to true, retrieves the changes that are published and those changes that have not been published. RetrieveAsIfPublished = false }; // Retrieve the MetaData. RetrieveAllEntitiesResponse response = (RetrieveAllEntitiesResponse)_serviceProxy.Execute(request); // Create an instance of StreamWriter to write text to a file. // The using statement also closes the StreamWriter. // To view this file, right click the file and choose open with Excel. // Excel will figure out the schema and display the information in columns. String filename = String.Concat("EntityPrivileges.xml"); using (StreamWriter sw = new StreamWriter(filename)) { // Create Xml Writer. XmlTextWriter metadataWriter = new XmlTextWriter(sw); // Start Xml File. metadataWriter.WriteStartDocument(); // Metadata Xml Node. metadataWriter.WriteStartElement("Metadata"); foreach (EntityMetadata currentEntity in response.EntityMetadata) { if (currentEntity.IsIntersect.Value == false) { // Start Entity Node metadataWriter.WriteStartElement("Entity"); // Write the Entity's Information. metadataWriter.WriteElementString("EntitySchemaName", currentEntity.SchemaName); metadataWriter.WriteElementString("OTC", currentEntity.ObjectTypeCode.ToString()); metadataWriter.WriteStartElement("Privileges"); foreach (SecurityPrivilegeMetadata privilege in currentEntity.Privileges) { metadataWriter.WriteStartElement("Privilege"); metadataWriter.WriteElementString("PrivilegeName", privilege.Name.ToString()); metadataWriter.WriteElementString("Id", privilege.PrivilegeId.ToString()); metadataWriter.WriteElementString("Type", privilege.PrivilegeType.ToString()); metadataWriter.WriteElementString("CanBeBasic", privilege.CanBeBasic.ToString()); metadataWriter.WriteElementString("CanBeDeep", privilege.CanBeDeep.ToString()); metadataWriter.WriteElementString("CanBeGlobal", privilege.CanBeGlobal.ToString()); metadataWriter.WriteElementString("CanBeLocal", privilege.CanBeLocal.ToString()); metadataWriter.WriteEndElement(); } metadataWriter.WriteEndElement(); // End Entity Node metadataWriter.WriteEndElement(); } } // End Metadata Xml Node metadataWriter.WriteEndElement(); metadataWriter.WriteEndDocument(); // Close xml writer. metadataWriter.Close(); } Console.WriteLine("Done."); //</snippetDumpEntityPrivileges1> //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; } }