/// <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 = 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 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 method creates any entity records that this sample requires. /// Create a queue instance. /// Create a phone call activity instance. /// Add phone call entity instance in to queue. /// Mark phone call entity instance status as completed. /// </summary> public void CreateRequiredRecords() { // Create a queue instance and set its property values. Queue newQueue = new Queue() { Name = "Example Queue", Description = "This is an example queue.", QueueViewType = new OptionSetValue((int)QueueQueueViewType.Private) }; _queueId = _serviceProxy.Create(newQueue); Console.WriteLine("Created {0}.", newQueue.Name); // Create a phone call activity instance. PhoneCall newPhoneCall = new PhoneCall { Description = "Example Phone Call" }; _phoneCallId = _serviceProxy.Create(newPhoneCall); Console.WriteLine("Created {0}.", newPhoneCall.Description); // Create a new instance of a queueitem and initialize its // properties. QueueItem item = new QueueItem { QueueId = new EntityReference(Queue.EntityLogicalName, _queueId), ObjectId = new EntityReference(PhoneCall.EntityLogicalName, _phoneCallId) }; // Create the queueitem on the server, which will associate // the phone call activity with the queue. _queueItemId = _serviceProxy.Create(item); Console.WriteLine("Added phone call entity instance to {0}", newQueue.Name); // Mark the phone call as completed. SetStateRequest setStatePhoneCall = new SetStateRequest { EntityMoniker = new EntityReference(PhoneCall.EntityLogicalName, _phoneCallId), State = new OptionSetValue((int)PhoneCallState.Completed), Status = new OptionSetValue(-1) }; _serviceProxy.Execute(setStatePhoneCall); Console.WriteLine("PhoneCall entity instance has been marked as completed."); return; }
/// <summary> /// Creates any entity records that this sample requires. /// </summary> public void CreateRequiredRecords() { // Create an account. Account account = new Account { Name = "Fourth Coffee", }; _accountId = _serviceProxy.Create(account); Console.WriteLine("Created a sample account: {0}.", account.Name); // Define the body and subject of the email template in XML format. string bodyXml = "<?xml version=\"1.0\" ?>" + "<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\">" + "<xsl:output method=\"text\" indent=\"no\"/><xsl:template match=\"/data\">" + "<![CDATA[" + "This message is to notify you that a new account has been created." + "]]></xsl:template></xsl:stylesheet>"; string subjectXml = "<?xml version=\"1.0\" ?>" + "<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\">" + "<xsl:output method=\"text\" indent=\"no\"/><xsl:template match=\"/data\">" + "<![CDATA[New account notification]]></xsl:template></xsl:stylesheet>"; string presentationXml = "<template><text><![CDATA[" + "This message is to notify you that a new account has been created." + "]]></text></template>"; string subjectPresentationXml = "<template><text><![CDATA[New account notification]]></text></template>"; // Create an e-mail template. Template template = new Template { Title = "Sample E-mail Template for Account", Body = bodyXml, Subject = subjectXml, PresentationXml = presentationXml, SubjectPresentationXml = subjectPresentationXml, TemplateTypeCode = Account.EntityLogicalName, LanguageCode = 1033, // For US English. IsPersonal = false }; _templateId = _serviceProxy.Create(template); Console.WriteLine("Created {0}.", template.Title); }
/// <summary> /// This method creates any entity records that this sample requires. /// Creates the email activity. /// </summary> public static void CreateRequiredRecords(CrmServiceClient service) { // TODO Create entity records Console.WriteLine("Creating required records for the sample"); Console.WriteLine("*****************************************"); // Create a unit group. UoMSchedule newUnitGroup = new UoMSchedule { Name = "Example Unit Group", BaseUoMName = "Example Primary Unit" }; _unitGroupId = _serviceProxy.Create(newUnitGroup); Console.WriteLine("Created {0}", newUnitGroup.Name); // retrieve the unit id. QueryExpression unitQuery = new QueryExpression { EntityName = UoM.EntityLogicalName, ColumnSet = new ColumnSet("uomid", "name"), Criteria = new FilterExpression(), PageInfo = new PagingInfo { PageNumber = 1, Count = 1 } }; unitQuery.Criteria.AddCondition("uomscheduleid", ConditionOperator.Equal, _unitGroupId); // Retrieve the unit. _unit = (UoM)_serviceProxy.RetrieveMultiple(unitQuery).Entities[0]; Console.WriteLine("Retrieved {0}", _unit.Name); // Create a price list PriceLevel newPriceList = new PriceLevel { Name = "Example Price List" }; _priceListId = _serviceProxy.Create(newPriceList); Console.WriteLine("Created {0}", newPriceList.Name); Console.WriteLine("*****************************************"); return; }
public override Guid WriteToCDS(OrganizationServiceProxy _serviceProxy) { Guid medicationPriceListId = Guid.Empty; try { // Create a price list PriceLevel newPriceList = new PriceLevel { Name = "Sample Price List " + GenerateRandomNumber() }; medicationPriceListId = _serviceProxy.Create(newPriceList); foreach (Medication product in Products) { ProductPriceLevel newPriceListItem = new ProductPriceLevel { PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, medicationPriceListId), ProductId = new EntityReference(Product.EntityLogicalName, Guid.Parse(product.MedicationId)), UoMId = new EntityReference(UoM.EntityLogicalName, Guid.Parse(UomId)), Amount = new Money(int.Parse(GenerateRandomNumber(2))) }; Guid priceListItemId = _serviceProxy.Create(newPriceListItem); if (priceListItemId == null) { break; } } if (medicationPriceListId != Guid.Empty) { PriceListId = medicationPriceListId.ToString(); Console.WriteLine("Created Price List [" + PriceListId + "]"); } else { throw new Exception("PriceListId == null"); } } catch (Exception ex) { throw new Exception(ex.ToString()); } return(medicationPriceListId); }
/// <summary> /// Creates any entity records that this sample requires. /// </summary> public void CreateRequiredRecords() { Console.WriteLine("Creating required records......"); // Create 10 book records for demo. for (int i = 0; i < 10; i++) { Entity book = new Entity("sample_book"); book["sample_name"] = "Demo Book " + i.ToString(); book["sample_bookcode"] = "BookCode" + i.ToString(); book["sample_author"] = "Author" + i.ToString(); bookIdtoDelete = _serviceProxy.Create(book); } Console.WriteLine("10 records created..."); }
/* Before the qualifying process.-> Add all the other necessary fields ->Add some new work order product * As all know, we need to track, update, and track some more. * So while the leads has been trasfer to account. Dont delete it but to update the state of it to closed. * The key is to make sure the lead keeps moving through the sales cycle without being lost */ private static void QualifyLead(OrganizationServiceProxy service, Guid id) { var entity = new Entity("lead"); entity["leadid"] = id; entity["log_contracttermsid"] = GetContractTerms(service).ToEntityReference(); entity["log_dateofbirth"] = DateTime.Now.AddYears(-19); //Date cannot be in the future entity["log_solddate"] = DateTime.Now; entity["log_salespersonid"] = GetSalesPerson(service).ToEntityReference(); entity["address2_line1"] = "address2 vitaminveien 1, oslo"; entity["log_address2_postalcode"] = GetPostCode(service).ToEntityReference(); entity["log_postalcode"] = GetPostCode(service).ToEntityReference(); entity["address1_line1"] = "address1 vitaminveien 1, oslo"; entity["log_canoverwritecreditcheck"] = true; //service.Update(entity); var createEntity = new Entity("log_workorderproduct"); createEntity["log_leadid"] = new EntityReference("lead", id); service.Create(createEntity); entity["log_convertleadflag"] = 1; service.Update(entity); }
/// <summary> /// This method creates any entity records that this sample requires. /// Create a new connectionrole instance. /// </summary> public void CreateRequiredRecords() { // Define some anonymous types to define the range // of possible connection property values. var Categories = new { Business = 1, Family = 2, Social = 3, Sales = 4, Other = 5 }; // Create a Connection Role ConnectionRole setupConnectionRole = new ConnectionRole { Name = "Example Connection Role", Description = "This is an example one sided connection role.", Category = new OptionSetValue(Categories.Business), }; _connectionRoleId = _serviceProxy.Create(setupConnectionRole); Console.WriteLine("Created {0}.", setupConnectionRole.Name); return; }
public override Guid WriteToCDS(OrganizationServiceProxy _serviceProxy) { Guid patientProcedureId = Guid.Empty; HealthCDM.msemr_procedure addProcedure = new HealthCDM.msemr_procedure(); addProcedure.msemr_Patient = new EntityReference(HealthCDM.Contact.EntityLogicalName, Guid.Parse((PatientId))); addProcedure.msemr_Status = new OptionSetValue(Status); addProcedure.msemr_DateTime = ProcedureDateTime; addProcedure.msemr_SubjectType = new OptionSetValue(SubjectType); addProcedure.msemr_description = Description; try { patientProcedureId = _serviceProxy.Create(addProcedure); if (patientProcedureId != Guid.Empty) { ProcedureId = patientProcedureId.ToString(); Console.WriteLine("Created Patient Procedure [" + ProcedureId + "] for Patient [" + PatientId + "]"); } else { throw new Exception("ProcedueId == null"); } } catch (Exception ex) { throw new Exception(ex.ToString()); } return(patientProcedureId); }
/// <summary> /// Create and configure the organization service proxy. /// Initiate the method to create any data that this sample requires. /// Create an appointment. /// </summary> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { //<snippetMarketingAutomation1> // 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(); var academicperiod = new Entity("mshied_academicperiod"); academicperiod["mshied_enddate"] = new DateTime(2014, 12, 5); academicperiod["mshied_name"] = "Fall 2014"; academicperiod["mshied_startdate"] = new DateTime(2014, 9, 1); academicperiod["mshied_code"] = "FA14"; var id = _serviceProxy.Create(academicperiod); // Verify that the record has been created. if (id != Guid.Empty) { Console.WriteLine($"Successfully created {id}."); } } } // 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; } }
public Guid CreateEntity(OrganizationServiceProxy serivce, Entity entity) { var recordId = serivce.Create(entity); Console.WriteLine("A record of {0} was created sucessfully, Guid: {1}", entity.LogicalName, recordId); return(recordId); }
/// <summary> /// Creates any entity records that this sample requires. /// </summary> public void CreateRequiredRecords() { // Create a sample Lead record. // This will also create an instance of "Lead To Opportunity Sales Process" // BPF for the new lead record. Lead myLead = new Lead { Subject = "SDK Sample Record", FirstName = "Randy", LastName = "Blythe" }; _leadId = _serviceProxy.Create(myLead); Console.WriteLine("\nCreated a Lead: '{0}'.", myLead.Subject); // Verify that an instance of "Lead To Opportunity Sales Process" is created for the new Lead record. RetrieveProcessInstancesRequest procLeadReq = new RetrieveProcessInstancesRequest { EntityId = _leadId, EntityLogicalName = Lead.EntityLogicalName }; RetrieveProcessInstancesResponse procLeadResp = (RetrieveProcessInstancesResponse)_serviceProxy.Execute(procLeadReq); if (procLeadResp.Processes.Entities.Count > 0) { var processLeadInstance = procLeadResp.Processes.Entities[0]; Console.WriteLine("Process instance automatically created for the new Lead record: '{0}'", processLeadInstance["name"]); } else { Console.WriteLine("No processes found for the Lead record; aborting the sample."); Environment.Exit(1); } }
//</snippetQuickCampaign3> /// <summary> /// This method creates any entity records that this sample requires. /// Create a new queue instance. /// </summary> public void CreateRequiredRecords() { WhoAmIRequest whoRequest = new WhoAmIRequest(); _currentUser = ((WhoAmIResponse)_serviceProxy.Execute(whoRequest)).UserId; //Create an activity objects which will act like a template during QC distrbution. //The activities created by QC will create activities with content that this activity has _templateEmailActivity = new Email() { Subject = "qcCreatedEmailActivity" }; _templateLetterActivity = new Letter() { Subject = "qcCreatedLetterActivity" }; // Create accounts on which we want to run QC _accountIdArray = new Guid[5]; for (int i = 0; i < 5; i++) { Account acct = new Account() { Name = "Account For Quick Campaign " + i.ToString() }; _accountIdArray[i] = _serviceProxy.Create(acct); Console.WriteLine("Created {0}.", acct.Name); } }
static void Main(string[] args) { var organizationServiceProxy = new OrganizationServiceProxy(GetUri(), null, GetClientCredentials(), null); DataTable csvDataTable = GetCSVData(); for (int locIndexRow = 1; locIndexRow < csvDataTable.Rows.Count; locIndexRow++) { string name = csvDataTable.Rows[locIndexRow][0].ToString(); string primaryContact = csvDataTable.Rows[locIndexRow][1].ToString(); string telephone1 = csvDataTable.Rows[locIndexRow][2].ToString(); QueryExpression queryExpression = new QueryExpression("contact"); queryExpression.ColumnSet = new ColumnSet(false); queryExpression.NoLock = true; queryExpression.TopCount = 1; queryExpression.Criteria.AddCondition("fullname", ConditionOperator.Equal, primaryContact); Entity queryResult = organizationServiceProxy.RetrieveMultiple(queryExpression).Entities.FirstOrDefault(); if (queryResult != null) { EntityReference primaryContactReference = queryResult.ToEntityReference(); Entity customEntity = CreateCustomEntity("account", name, primaryContactReference, telephone1); Guid myGuid = organizationServiceProxy.Create(customEntity); if (myGuid != Guid.Empty) { Console.WriteLine(name + "account is created with guid" + myGuid.ToString()); } } } }
public override Guid WriteToCDS(OrganizationServiceProxy _serviceProxy) { Guid allergyIntolernaceId = Guid.Empty; HealthCDM.msemr_allergyintolerance addAllergyIntolerance = new HealthCDM.msemr_allergyintolerance(); addAllergyIntolerance.msemr_Patient = new EntityReference(HealthCDM.Contact.EntityLogicalName, Guid.Parse((PatientId))); addAllergyIntolerance.msemr_name = Item; addAllergyIntolerance.msemr_Code = Item; addAllergyIntolerance.msemr_Criticality = new OptionSetValue(Severity); addAllergyIntolerance.msemr_VerificationStatus = new OptionSetValue(VertificationStatus); addAllergyIntolerance.msemr_Type = new OptionSetValue(Type); try { allergyIntolernaceId = _serviceProxy.Create(addAllergyIntolerance); if (allergyIntolernaceId != Guid.Empty) { AllergyIntoleranceId = allergyIntolernaceId.ToString(); Console.WriteLine("Created Allergy Intolerance [" + AllergyIntoleranceId + "] for Patient [" + PatientId + "]"); } else { throw new Exception("AllegyIntoleranceId == null"); } } catch (Exception ex) { throw new Exception(ex.ToString()); } return(allergyIntolernaceId); }
public override Guid WriteToCDS(OrganizationServiceProxy _serviceProxy) { Guid nutritionId = Guid.Empty; HealthCDM.msemr_nutritionorder addNutritionOrder = new HealthCDM.msemr_nutritionorder(); addNutritionOrder.msemr_Patient = new EntityReference(HealthCDM.Contact.EntityLogicalName, Guid.Parse((Patient))); addNutritionOrder.msemr_Orderer = new EntityReference(HealthCDM.Contact.EntityLogicalName, Guid.Parse((Practitioner))); addNutritionOrder.msemr_name = OrderName; addNutritionOrder.msemr_DateTime = OrderDateTime; addNutritionOrder.msemr_Status = new OptionSetValue(OrderStatus); try { nutritionId = _serviceProxy.Create(addNutritionOrder); if (nutritionId != Guid.Empty) { NutritionOrderId = nutritionId.ToString(); Console.WriteLine("Created Nutrition [" + NutritionOrderId + "] for Patient [" + Patient + "]"); } else { throw new Exception("NutritionId == null"); } } catch (Exception ex) { throw new Exception(ex.ToString()); } return(nutritionId); }
/// <summary> /// This method creates any entity records that this sample requires. /// </summary> public void CreateRequiredRecords() { // Get the current user. WhoAmIRequest userRequest = new WhoAmIRequest(); WhoAmIResponse userResponse = (WhoAmIResponse)_serviceProxy.Execute(userRequest); _userId = userResponse.UserId; // Create the activity party for sending and receiving the fax. ActivityParty party = new ActivityParty { PartyId = new EntityReference(SystemUser.EntityLogicalName, _userId) }; // Create the fax object. Fax fax = new Fax { Subject = "Sample Fax", From = new ActivityParty[] { party }, To = new ActivityParty[] { party } }; _faxId = _serviceProxy.Create(fax); Console.WriteLine("Created a fax: '{0}'.", fax.Subject); }
public Action SaveCommand() { if (_saveCommand == null) { _saveCommand = delegate() { bool confirmed = Script.Confirm(String.Format("Are you sure save these sessions?")); if (!confirmed) { return; } SessionVM stopSession = StopSession.GetValue(); dev1_session sessionToUpdate = stopSession.GetUpdatedModel(); try { OrganizationServiceProxy.Update(sessionToUpdate); // Save next session if (StartNewSession.GetValue()) { dev1_session nextSession = StartSession.GetValue().GetUpdatedModel(); OrganizationServiceProxy.Create(nextSession); } } catch (Exception ex) { Script.Alert("There was a problem saving your session. Please contact your system administrator.\n\n" + ex.Message); } }; } return(_saveCommand); }
public string CreateAccount(string firstName, string lastname, string email, string phone) { try { using (service = new CrmConn().GetService()) { Console.WriteLine("Connected to CRM Service - inside CreateAccount"); Entity account = new Entity("account"); Guid _accountId; account["name"] = firstName + " " + lastname; account["telephone1"] = phone; account["emailaddress1"] = email; _accountId = service.Create(account); return(_accountId.ToString()); } } catch (Exception e) { Console.WriteLine("Exception: " + e.Message); return("error creating the account"); } }
/* * Lead create Process allow end user to choose which name they want to use * The purpose of we want the name as a parameter is that it can be easily track and create. */ private static Guid CreateLeadWithName(OrganizationServiceProxy service, String name) { var leadSource = GetLeadSourceName(service, leadSourceName); var newLead = new Entity("lead"); var user = GetUser(service); newLead["companyname"] = name; newLead["log_leadsourceid"] = leadSource.ToEntityReference(); //newLead["ownerid"] = user.ToEntityReference(); newLead["log_direction"] = new OptionSetValue(182400001); //moved out newLead["log_contracttermsid"] = GetContractTerms(service).ToEntityReference(); newLead["telephone2"] = "45512131"; newLead["log_dateofbirth"] = DateTime.Now.AddYears(-19); //Date cannot be in the future newLead["log_solddate"] = DateTime.Now; newLead["log_movingdate"] = DateTime.Now; newLead["log_salespersonid"] = GetSalesPerson(service).ToEntityReference(); //street 1 //newLead["address2_line1"] = "address2 vitaminveien 1, oslo"; newLead["log_address2_postalcode"] = GetPostCode(service).ToEntityReference(); newLead["log_postalcode"] = GetPostCode(service).ToEntityReference(); newLead["address1_line1"] = "address1 vitaminveien 1, oslo"; newLead["log_canoverwritecreditcheck"] = true; newLead["log_takeovercase"] = GetTakdOverCASE(service).ToEntityReference(); newLead["log_typeoflead"] = new OptionSetValue(182400002); return(service.Create(newLead)); }
public override Guid WriteToCDS(OrganizationServiceProxy _serviceProxy) { Guid patientDeviceId = Guid.Empty; HealthCDM.msemr_device addPatientDevice = new HealthCDM.msemr_device(); addPatientDevice.msemr_Patient = new EntityReference(HealthCDM.Contact.EntityLogicalName, Guid.Parse(PatientId)); addPatientDevice.msemr_DeviceNumber = DeviceNumber; addPatientDevice.msemr_Version = Version; addPatientDevice.msemr_Model = Model; addPatientDevice.msemr_ExpirationDate = ExpirationDate; addPatientDevice.msemr_name = Name; addPatientDevice.msemr_DeviceStatus = new OptionSetValue(DeviceStatus); try { patientDeviceId = _serviceProxy.Create(addPatientDevice); if (patientDeviceId != Guid.Empty) { DeviceId = patientDeviceId.ToString(); Console.WriteLine("Created Device [" + DeviceId + "] for Patient [" + PatientId + "]"); } else { throw new Exception("DeviceId == null"); } } catch (Exception ex) { throw new Exception(ex.ToString()); } return(patientDeviceId); }
public override Guid WriteToCDS(OrganizationServiceProxy _serviceProxy) { Guid practitionerRoleId = Guid.Empty; try { HealthCDM.msemr_practitionerrole addPractitionerRole = new HealthCDM.msemr_practitionerrole(); addPractitionerRole.msemr_Practitioner = new EntityReference(HealthCDM.Contact.EntityLogicalName, Guid.Parse(PractitionerId)); addPractitionerRole.msemr_PeriodEnddatetime = PeriodEndDate; addPractitionerRole.msemr_PeriodStartdatetime = PeriodStartDate; addPractitionerRole.msemr_name = Name; practitionerRoleId = _serviceProxy.Create(addPractitionerRole); if (practitionerRoleId != Guid.Empty) { RoleId = practitionerRoleId.ToString(); Console.WriteLine("Created Practitioner Role [" + RoleId + "] for Practitioner [" + PractitionerId + "]"); } else { throw new Exception("RoleId == null"); } } catch (Exception ex) { throw new Exception(ex.ToString()); } return(practitionerRoleId); }
/// <summary> /// Create and configure the organization service proxy. /// Initiate the method to create any data that this sample requires. /// Create an appointment. /// </summary> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { //<snippetMarketingAutomation1> // 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(); var deviceclass = new Entity("msauto_deviceclass"); deviceclass["msauto_code"] = "12345"; deviceclass["msauto_description"] = "Luxury sedan"; deviceclass["msauto_name"] = "Contoso V3"; var id = _serviceProxy.Create(deviceclass); // Verify that the record has been created. if (id != Guid.Empty) { Console.WriteLine($"Successfully created {id}."); } } } // 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; } }
private bool MigrateEntityToExternal(OrganizationServiceProxy localProxy, BinaryStorageOptions.Providers.IBinaryStorageProvider storageProvider, Entity entity, string entityName, string documentBodyKey, string filenameKey) { if (!entity.Attributes.ContainsKey(documentBodyKey) || (string)entity.Attributes[documentBodyKey] == BinaryStorageOptions.GenericConstants.EmptyBodyContent) { return(true); } string fileName = (string)entity.Attributes[filenameKey]; Notify(string.Format("Migrating '{0}' with filename '{1}' CRM -> External using {2}.", entityName, entity.Id.ToString() + "_" + fileName, storageProvider.GetType().Name)); if (storageProvider.Create(entity.Id, fileName, Convert.FromBase64String((string)entity.Attributes[documentBodyKey]))) { Notify(string.Format("Created '{0}' with filename '{1}'. Removing from CRM.", entityName, entity.Id.ToString() + "_" + fileName)); //Create an additional record to basically store the filesize Entity attachmentExtension = new Entity(GenericConstants.AttachementExtensionEntityName); attachmentExtension.Attributes.Add(GenericConstants.AttachementExtensionEntityNameKey, entity.LogicalName); attachmentExtension.Attributes.Add(GenericConstants.AttachementExtensionEntityIdKey, entity.Id.ToString()); attachmentExtension.Attributes.Add(GenericConstants.AttachementExtensionFileSizeKey, entity.Attributes[CrmConstants.FileSizeKey]); localProxy.Create(attachmentExtension); //FileSize (3) attributes are handled by CRM and is useless to set here. Must have a body else we get funny requests in retrieve messages. entity.Attributes[GenericConstants.Constants[entity.LogicalName][GenericConstants.DocumentBodyAttributeKey]] = GenericConstants.EmptyBodyContent; localProxy.Update(entity); Notify(string.Format("Migration of '{0}' with filename '{1}' DONE.", entityName, entity.Id.ToString() + "_" + fileName)); return(true); } return(false); }
public static void CreateMember(OrganizationServiceProxy service, string firstname, string lastname, string idnumber, string mobilephone, string telephone, string emailaddress, string countryofrigin, int gender, int race, string jobtitle, string areaofexpertise) { var member = new Entity("contact") { ["firstname"] = firstname, ["lastname"] = lastname, ["emailaddress1"] = emailaddress, ["mobilephone"] = mobilephone, ["address1_telephone2"] = telephone, ["eppei_countryoforigin"] = countryofrigin, ["eppei_gender"] = new OptionSetValue(gender), ["eppei_race"] = new OptionSetValue(race), ["jobtitle"] = jobtitle, ["eppei_membertype"] = new OptionSetValue(2), ["eppei_areaofindustrialexpertise"] = areaofexpertise }; if (string.IsNullOrEmpty(idnumber)) { member["eppei_saidnumber"] = idnumber; } service.Create(member); Console.WriteLine("Created: " + firstname + " " + lastname); }
/// <summary> /// Create and configure the organization service proxy. /// Initiate the method to create any data that this sample requires. /// Create an appointment. /// </summary> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { //<snippetMarketingAutomation1> // 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(); var programversion = new Entity("mshied_programversion"); programversion["mshied_code"] = "AT__AS_009"; programversion["mshied_programid"] = new EntityReference("mshied_program", new Guid("4c44f395-64c6-e811-a987-000d3a161ff6")); programversion["mshied_programlevelid"] = new EntityReference("mshied_programlevel", new Guid("e28ceedd-64c6-e811-a984-000d3a1618d5")); programversion["mshied_name"] = "06/09 Associate of Science: Accounting Technology"; var id = _serviceProxy.Create(programversion); // Verify that the record has been created. if (id != Guid.Empty) { Console.WriteLine($"Successfully created {id}."); } } } // 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; } }
public override Guid WriteToCDS(OrganizationServiceProxy _serviceProxy) { Guid patientConditionId = Guid.Empty; HealthCDM.msemr_condition addCondition = new HealthCDM.msemr_condition(); addCondition.msemr_SubjectTypePatient = new EntityReference(HealthCDM.Contact.EntityLogicalName, Guid.Parse((PatientId))); addCondition.msemr_Practitioner = new EntityReference(HealthCDM.Contact.EntityLogicalName, Guid.Parse((PractitionerId))); addCondition.msemr_SubjectType = new OptionSetValue(SubjectType); addCondition.msemr_OnsetDate = OnsetDate; addCondition.msemr_name = Description; addCondition.msemr_VerificationStatus = new OptionSetValue(VerificationStatus); try { patientConditionId = _serviceProxy.Create(addCondition); if (patientConditionId != Guid.Empty) { ConditionId = patientConditionId.ToString(); Console.WriteLine("Created Condition [" + ConditionId + "] for Patient [" + PatientId + "]"); } else { throw new Exception("ConditionId == null"); } } catch (Exception ex) { throw new Exception(ex.ToString()); } return(patientConditionId); }
/// <summary> /// Creates any entity records that this sample requires. /// </summary> public void CreateRequiredRecords() { // Retrieve the default business unit needed to create the team. QueryExpression queryDefaultBusinessUnit = new QueryExpression { EntityName = BusinessUnit.EntityLogicalName, ColumnSet = new ColumnSet("businessunitid"), Criteria = { Conditions = { new ConditionExpression("parentbusinessunitid", ConditionOperator.Null) } } }; BusinessUnit defaultBusinessUnit = (BusinessUnit)_serviceProxy.RetrieveMultiple( queryDefaultBusinessUnit).Entities[0]; // Instantiate a team entity record and set its property values. // See the Entity Metadata topic in the SDK documentation to determine // which attributes must be set for each entity. Team setupTeam = new Team { Name = "ABC Management Team", BusinessUnitId = new EntityReference(BusinessUnit.EntityLogicalName, defaultBusinessUnit.Id) }; //Create a team record. _teamId = _serviceProxy.Create(setupTeam); Console.Write("Created Team, "); }
public static Guid CreateAppointment(OrganizationServiceProxy service, Appointment appointment) { try { var appointmentEntity = new Entity("appointment") { ["subject"] = appointment.Subject.Length > 200 ? appointment.Subject.Substring(0, 200) : appointment.Subject, ["scheduledend"] = appointment.EndTime, ["scheduledstart"] = appointment.StartTime, ["ownerid"] = new EntityReference("systemuser", appointment.OwnerId), ["prioritycode"] = new OptionSetValue((appointment.PriorityCode == 2 ? 2 : 1)), ["blu_createdfromportal"] = true }; if (appointment.RegardingObjectId != Guid.Empty) { appointmentEntity["regardingobjectid"] = new EntityReference("salesorder", appointment.RegardingObjectId); } return(service.Create(appointmentEntity)); } catch (Exception ex) { LogService.LogMessage(service, new Log() { Level = (int)LogType.Error, Name = ex.Message, FunctionName = ClassName + " | " + MethodBase.GetCurrentMethod().Name, Message = ex.InnerException != null ? ex.InnerException.Message : ex.Message }); return(Guid.Empty); } }
public override Guid WriteToCDS(OrganizationServiceProxy _serviceProxy) { Guid episodeId = Guid.Empty; try { HealthCDM.msemr_episodeofcare episode = new HealthCDM.msemr_episodeofcare(); episode.msemr_CareManager = new EntityReference(HealthCDM.Contact.EntityLogicalName, new Guid(PractitionerId)); //episode.msemr_msemr_episodeofcare_msemr_encounter_ContextEpisodeofCare = new EntityReference(HealthCDM.Contact.EntityLogicalName, new Guid(PractitionerId)); episode.msemr_Patient = new EntityReference(HealthCDM.Contact.EntityLogicalName, new Guid(PatientId)); episode.msemr_Organization = new EntityReference(HealthCDM.Contact.EntityLogicalName, new Guid(AccountId)); episode.msemr_description = Description; episode.msemr_StartDateTime = StartDateTime; episode.msemr_EndDateTime = EndDateTime; episodeId = _serviceProxy.Create(episode); if (episodeId != Guid.Empty) { EpisodeOfCareId = episodeId.ToString(); Console.WriteLine("Created EpisodeOfcare [" + episodeId + "] for Patient [" + PatientId + "]"); } else { throw new Exception("episodeId == null"); } } catch (Exception ex) { throw new Exception(ex.ToString()); } return(episodeId); }
/// <summary> /// This method creates any entity records that this sample requires. /// </summary> public void CreateRequiredRecords() { // Define an anonymous type to define the possible values for // report type var ReportTypeCode = new { ReportingServicesReport = 1, OtherReport = 2, LinkedReport = 3 }; // Create a report Report newReport = new Report { Name = "Sample Report", Description = "Report created by the SDK code sample.", ReportTypeCode = new OptionSetValue((int)ReportTypeCode.OtherReport), //Base64-encoded "Hello, I am a text file." BodyBinary = "SGVsbG8sIEkgYW0gYSB0ZXh0IGZpbGUu", FileName = "textfile.txt", IsPersonal = true }; _reportId = _serviceProxy.Create(newReport); Console.WriteLine("Created {0}.", newReport.Name); }
/// <summary> /// This method first connects to the Organization service. Afterwards, a /// rollup field and rollup query are created. The rollup query is only /// associated with the child goal. Then a parent goal and child goal /// are created. The goals are both rolled up and their results are displayed. /// </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 { //<snippetUsingQueriesToTrackGoals1> // 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(); // Create the revenue metric, setting the Amount Data Type to 'Money' // and the Metric Type to 'Amount'. Metric sampleMetric = new Metric() { Name = "Sample Revenue Metric", AmountDataType = new OptionSetValue(0), IsAmount = true, }; _metricId = _serviceProxy.Create(sampleMetric); sampleMetric.Id = _metricId; Console.Write("Created revenue metric, "); #region Create RollupFields // Create RollupField which targets the actual totals. RollupField actual = new RollupField() { SourceEntity = SalesOrder.EntityLogicalName, SourceAttribute = "totalamount", GoalAttribute = "actualmoney", SourceState = 1, EntityForDateAttribute = SalesOrder.EntityLogicalName, DateAttribute = "datefulfilled", MetricId = sampleMetric.ToEntityReference() }; _actualId = _serviceProxy.Create(actual); Console.Write("created actual revenue RollupField, "); #endregion #region Create the goal rollup query // The query locates sales orders in the first sales // representative's area (zip code: 60661) and with a value // greater than $1,000. GoalRollupQuery goalRollupQuery = new GoalRollupQuery() { Name = "First Example Goal Rollup Query", QueryEntityType = SalesOrder.EntityLogicalName, FetchXml = @"<fetch mapping=""logical"" version=""1.0""><entity name=""salesorder""><attribute name=""customerid"" /><attribute name=""name"" /><attribute name=""salesorderid"" /><attribute name=""statuscode"" /><attribute name=""totalamount"" /><order attribute=""name"" /><filter><condition attribute=""totalamount"" operator=""gt"" value=""1000"" /><condition attribute=""billto_postalcode"" operator=""eq"" value=""60661"" /></filter></entity></fetch>" }; _rollupQueryId = _serviceProxy.Create(goalRollupQuery); goalRollupQuery.Id = _rollupQueryId; Console.Write("created rollup query."); Console.WriteLine(); #endregion #region Create two goals: one parent and one child goal // Create the parent goal. Goal parentGoal = new Goal() { Title = "Parent Goal Example", RollupOnlyFromChildGoals = true, TargetMoney = new Money(1000.0M), 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) }; _parentGoalId = _serviceProxy.Create(parentGoal); parentGoal.Id = _parentGoalId; Console.WriteLine("Created parent goal"); Console.WriteLine("-------------------"); Console.WriteLine("Target: {0}", parentGoal.TargetMoney.Value); Console.WriteLine("Goal owner: {0}", parentGoal.GoalOwnerId.Id); Console.WriteLine("Goal Start Date: {0}", parentGoal.GoalStartDate); Console.WriteLine("Goal End Date: {0}", parentGoal.GoalEndDate); Console.WriteLine("<End of Listing>"); Console.WriteLine(); // Create the child goal. Goal firstChildGoal = new Goal() { Title = "First Child Goal Example", ConsiderOnlyGoalOwnersRecords = true, TargetMoney = new Money(1000.0M), IsFiscalPeriodGoal = false, MetricId = sampleMetric.ToEntityReference(), ParentGoalId = parentGoal.ToEntityReference(), GoalOwnerId = new EntityReference { Id = _salesRepresentativeId, LogicalName = SystemUser.EntityLogicalName }, OwnerId = new EntityReference { Id = _salesManagerId, LogicalName = SystemUser.EntityLogicalName }, RollUpQueryActualMoneyId = goalRollupQuery.ToEntityReference(), GoalStartDate = DateTime.Today.AddDays(-1), GoalEndDate = DateTime.Today.AddDays(30) }; _firstChildGoalId = _serviceProxy.Create(firstChildGoal); Console.WriteLine("First child goal"); Console.WriteLine("----------------"); Console.WriteLine("Target: {0}", firstChildGoal.TargetMoney.Value); Console.WriteLine("Goal owner: {0}", firstChildGoal.GoalOwnerId.Id); Console.WriteLine("Goal Start Date: {0}", firstChildGoal.GoalStartDate); Console.WriteLine("Goal End Date: {0}", firstChildGoal.GoalEndDate); Console.WriteLine("<End of Listing>"); Console.WriteLine(); #endregion // Calculate roll-up of goals. // Note: Recalculate can be run against any goal in the tree to cause // a rollup of the whole tree. RecalculateRequest recalculateRequest = new RecalculateRequest() { Target = parentGoal.ToEntityReference() }; _serviceProxy.Execute(recalculateRequest); Console.WriteLine("Calculated roll-up of goals."); Console.WriteLine(); // Retrieve and report 3 different computed values for the goals // - Percentage // - ComputedTargetAsOfTodayPercentageAchieved // - ComputedTargetAsOfTodayMoney QueryExpression retrieveValues = new QueryExpression() { EntityName = Goal.EntityLogicalName, ColumnSet = new ColumnSet( "title", "computedtargetasoftodaypercentageachieved", "computedtargetasoftodaymoney") }; 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("ComputedTargetAsOfTodayPercentageAchieved: {0}", temp.ComputedTargetAsOfTodayPercentageAchieved); Console.WriteLine("ComputedTargetAsOfTodayMoney: {0}", temp.ComputedTargetAsOfTodayMoney.Value); Console.WriteLine("<End of Listing>"); } DeleteRequiredRecords(promptforDelete); } //</snippetUsingQueriesToTrackGoals1> } // 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 Outlook service. Afterwards, /// client information is retrieved and the client state is changed. /// </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(); //<snippetRetrieveDataFilters1> // Create and Retrieve Offline Filter // In your Outlook client, this will appear in the System Filters tab // under File | CRM | Synchronize | Outlook Filters. Console.Write("Creating offline filter"); String contactName = String.Format("offlineFilteredContact {0}", DateTime.Now.ToLongTimeString()); String fetchXml = String.Format("<fetch version=\"1.0\" output-format=\"xml-platform\" mapping=\"logical\"><entity name=\"contact\"><attribute name=\"contactid\" /><filter type=\"and\">" + "<condition attribute=\"ownerid\" operator=\"eq-userid\" /><condition attribute=\"description\" operator=\"eq\" value=\"{0}\" />" + "<condition attribute=\"statecode\" operator=\"eq\" value=\"0\" /></filter></entity></fetch>", contactName); SavedQuery filter = new SavedQuery(); filter.FetchXml = fetchXml; filter.IsQuickFindQuery = false; filter.QueryType = SavedQueryQueryType.OfflineFilters; filter.ReturnedTypeCode = Contact.EntityLogicalName; filter.Name = "ReadOnlyFilter_" + contactName; filter.Description = "Sample offline filter for Contact entity"; _offlineFilter = _serviceProxy.Create(filter); Console.WriteLine(" and retrieving offline filter"); SavedQuery result = (SavedQuery)_serviceProxy.Retrieve( SavedQuery.EntityLogicalName, _offlineFilter, new ColumnSet("name", "description")); Console.WriteLine("Name: {0}", result.Name); Console.WriteLine("Description: {0}", result.Description); Console.WriteLine(); // Create and Retrieve Offline Template // In your Outlook client, this will appear in the User Filters tab // under File | CRM | Synchronize | Outlook Filters. Console.Write("Creating offline template"); String accountName = String.Format("offlineFilteredAccount {0}", DateTime.Now.ToLongTimeString()); fetchXml = String.Format("<fetch version=\"1.0\" output-format=\"xml-platform\" mapping=\"logical\"><entity name=\"account\"><attribute name=\"accountid\" /><filter type=\"and\">" + "<condition attribute=\"ownerid\" operator=\"eq-userid\" /><condition attribute=\"name\" operator=\"eq\" value=\"{0}\" />" + "<condition attribute=\"statecode\" operator=\"eq\" value=\"0\" /></filter></entity></fetch>", accountName); SavedQuery template = new SavedQuery(); template.FetchXml = fetchXml; template.IsQuickFindQuery = false; template.QueryType = SavedQueryQueryType.OfflineTemplate; template.ReturnedTypeCode = Account.EntityLogicalName; template.Name = "ReadOnlyFilter_" + accountName; template.Description = "Sample offline template for Account entity"; _offlineTemplate = _serviceProxy.Create(template); Console.WriteLine(" and retrieving offline template"); result = (SavedQuery)_serviceProxy.Retrieve( SavedQuery.EntityLogicalName, _offlineTemplate, new ColumnSet("name", "description")); Console.WriteLine("Name: {0}", result.Name); Console.WriteLine("Description: {0}", result.Description); Console.WriteLine(); //</snippetRetrieveDataFilters1> //<snippetRetrieveDataFilters2> // Call InstantiateFiltersRequest Console.WriteLine("Retrieving user's ID and creating the template collection"); WhoAmIRequest whoAmI = new WhoAmIRequest(); Guid id = ((WhoAmIResponse)_serviceProxy.Execute(whoAmI)).UserId; EntityReferenceCollection templates = new EntityReferenceCollection(); templates.Add(new EntityReference( SavedQuery.EntityLogicalName, _offlineTemplate)); Console.WriteLine("Activating the selected offline templates for this user"); InstantiateFiltersRequest request = new InstantiateFiltersRequest { UserId = id, TemplateCollection = templates }; InstantiateFiltersResponse response = (InstantiateFiltersResponse)_serviceProxy.Execute(request); Console.WriteLine(); //</snippetRetrieveDataFilters2> //<snippetRetrieveDataFilters3> // Call ResetUserFiltersRequest Console.WriteLine("Resetting the user's offline templates to the defaults"); ResetUserFiltersRequest resetRequest = new ResetUserFiltersRequest { QueryType = SavedQueryQueryType.OfflineFilters }; ResetUserFiltersResponse resetResponse = (ResetUserFiltersResponse)_serviceProxy.Execute(resetRequest); Console.WriteLine(); //</snippetRetrieveDataFilters3> 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, /// several actions on Goal records are executed. /// </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 { //<snippetRollupAllGoalsForCustomPeriodAgainstTargetRevenue1> // 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(); // Create the revenue metric, setting the Amount Data Type to 'Money' // and the Metric Type to 'Amount'. Metric sampleMetric = new Metric() { Name = "Sample Revenue Metric", AmountDataType = new OptionSetValue(0), IsAmount = true, }; _metricId = _serviceProxy.Create(sampleMetric); Console.Write("Created revenue metric, "); // Create first RollupField which targets the estimated values. RollupField inProgress = new RollupField() { SourceEntity = Opportunity.EntityLogicalName, SourceAttribute = "estimatedvalue", GoalAttribute = "inprogressmoney", SourceState = 0, EntityForDateAttribute = Opportunity.EntityLogicalName, DateAttribute = "estimatedclosedate", MetricId = new EntityReference(Metric.EntityLogicalName, _metricId), }; _inProgressId = _serviceProxy.Create(inProgress); Console.Write("created in-progress RollupField, "); // Create second RollupField which targets the actual values. RollupField actual = new RollupField() { SourceEntity = Opportunity.EntityLogicalName, SourceAttribute = "actualvalue", GoalAttribute = "actualmoney", SourceState = 1, EntityForDateAttribute = Opportunity.EntityLogicalName, DateAttribute = "actualclosedate", MetricId = new EntityReference(Metric.EntityLogicalName, _metricId) }; _actualId = _serviceProxy.Create(actual); Console.Write("created actual revenue RollupField, "); // Create the goal rollup queries. // Note: Formatting the FetchXml onto multiple lines in the following // rollup queries causes the lenth property to be greater than 1,000 // chars and will cause an exception. // The first query locates opportunities in the first sales // representative's area (zip code: 60661). GoalRollupQuery goalRollupQuery = new GoalRollupQuery() { Name = "First Example Goal Rollup Query", QueryEntityType = Opportunity.EntityLogicalName, FetchXml = @"<fetch version=""1.0"" output-format=""xml-platform"" mapping=""logical"" distinct=""false""><entity name=""opportunity""><attribute name=""totalamount""/><attribute name=""name""/><attribute name=""customerid""/><attribute name=""estimatedvalue""/><attribute name=""statuscode""/><attribute name=""opportunityid""/><order attribute=""name"" descending=""false""/><link-entity name=""account"" from=""accountid"" to=""customerid"" alias=""aa""><filter type=""and""><condition attribute=""address1_postalcode"" operator=""eq"" value=""60661""/></filter></link-entity></entity></fetch>" }; _rollupQueryIds.Add(_serviceProxy.Create(goalRollupQuery)); Console.Write("created first rollup query for zip code 60661, "); // The second query locates opportunities in the second sales // representative's area (zip code: 99999). goalRollupQuery = new GoalRollupQuery() { Name = "Second Example Goal Rollup Query", QueryEntityType = Opportunity.EntityLogicalName, FetchXml = @"<fetch version=""1.0"" output-format=""xml-platform"" mapping=""logical"" distinct=""false""><entity name=""opportunity""><attribute name=""totalamount""/><attribute name=""customerid""/><attribute name=""estimatedvalue""/><attribute name=""statuscode""/><attribute name=""opportunityid""/><order attribute=""name"" descending=""false""/><link-entity name=""account"" from=""accountid"" to=""customerid"" alias=""aa""><filter type=""and""><condition attribute=""address1_postalcode"" operator=""eq"" value=""99999""/></filter></link-entity></entity></fetch>" }; _rollupQueryIds.Add(_serviceProxy.Create(goalRollupQuery)); Console.WriteLine("created second rollup query for zip code 99999."); Console.WriteLine(); // Create three goals: one parent goal and two child goals. Goal parentGoal = new Goal() { Title = "Parent Goal Example", RollupOnlyFromChildGoals = true, ConsiderOnlyGoalOwnersRecords = true, TargetMoney = new Money(300.0M), IsFiscalPeriodGoal = false, MetricId = new EntityReference { Id = _metricId, LogicalName = Metric.EntityLogicalName }, 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) }; _parentGoalId = _serviceProxy.Create(parentGoal); Console.WriteLine("Created parent goal"); Console.WriteLine("-------------------"); Console.WriteLine("Target: {0}", parentGoal.TargetMoney.Value); Console.WriteLine("Goal owner: {0}", parentGoal.GoalOwnerId.Id); Console.WriteLine("Goal Start Date: {0}", parentGoal.GoalStartDate); Console.WriteLine("Goal End Date: {0}", parentGoal.GoalEndDate); Console.WriteLine("<End of Listing>"); Console.WriteLine(); Goal firstChildGoal = new Goal() { Title = "First Child Goal Example", ConsiderOnlyGoalOwnersRecords = true, TargetMoney = new Money(100.0M), IsFiscalPeriodGoal = false, MetricId = new EntityReference { Id = _metricId, LogicalName = Metric.EntityLogicalName }, ParentGoalId = new EntityReference { Id = _parentGoalId, LogicalName = Goal.EntityLogicalName }, GoalOwnerId = new EntityReference { Id = _salesRepresentativeIds[0], LogicalName = SystemUser.EntityLogicalName }, OwnerId = new EntityReference { Id = _salesManagerId, LogicalName = SystemUser.EntityLogicalName }, RollUpQueryActualMoneyId = new EntityReference { Id = _rollupQueryIds[0], LogicalName = GoalRollupQuery.EntityLogicalName }, GoalStartDate = DateTime.Today.AddDays(-1), GoalEndDate = DateTime.Today.AddDays(30) }; _firstChildGoalId = _serviceProxy.Create(firstChildGoal); Console.WriteLine("First child goal"); Console.WriteLine("----------------"); Console.WriteLine("Target: {0}", firstChildGoal.TargetMoney.Value); Console.WriteLine("Goal owner: {0}", firstChildGoal.GoalOwnerId.Id); Console.WriteLine("Goal Start Date: {0}", firstChildGoal.GoalStartDate); Console.WriteLine("Goal End Date: {0}", firstChildGoal.GoalEndDate); Console.WriteLine(); Goal secondChildGoal = new Goal() { Title = "Second Child Goal Example", ConsiderOnlyGoalOwnersRecords = true, TargetMoney = new Money(200.0M), IsFiscalPeriodGoal = false, MetricId = new EntityReference { Id = _metricId, LogicalName = Metric.EntityLogicalName }, ParentGoalId = new EntityReference { Id = _parentGoalId, LogicalName = Goal.EntityLogicalName }, GoalOwnerId = new EntityReference { Id = _salesRepresentativeIds[1], LogicalName = SystemUser.EntityLogicalName }, OwnerId = new EntityReference { Id = _salesManagerId, LogicalName = SystemUser.EntityLogicalName }, RollUpQueryActualMoneyId = new EntityReference { Id = _rollupQueryIds[1], LogicalName = GoalRollupQuery.EntityLogicalName }, GoalStartDate = DateTime.Today.AddDays(-1), GoalEndDate = DateTime.Today.AddDays(30) }; _secondChildGoalId = _serviceProxy.Create(secondChildGoal); Console.WriteLine("Second child goal"); Console.WriteLine("-----------------"); Console.WriteLine("Target: {0}", secondChildGoal.TargetMoney.Value); Console.WriteLine("Goal owner: {0}", secondChildGoal.GoalOwnerId.Id); Console.WriteLine("Goal Start Date: {0}", secondChildGoal.GoalStartDate); Console.WriteLine("Goal End Date: {0}", secondChildGoal.GoalEndDate); Console.WriteLine(); // <snippetRecalculate1> // Calculate roll-up of goals. RecalculateRequest recalculateRequest = new RecalculateRequest() { Target = new EntityReference(Goal.EntityLogicalName, _parentGoalId) }; _serviceProxy.Execute(recalculateRequest); //</snippetRecalculate1> Console.WriteLine("Calculated roll-up of goals."); // Retrieve and report 3 different computed values for the goals // - Percentage // - ComputedTargetAsOfTodayPercentageAchieved // - ComputedTargetAsOfTodayMoney QueryExpression retrieveValues = new QueryExpression() { EntityName = Goal.EntityLogicalName, ColumnSet = new ColumnSet( "title", "percentage", "computedtargetasoftodaypercentageachieved", "computedtargetasoftodaymoney") }; 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: {0}", temp.Percentage); Console.WriteLine("ComputedTargetAsOfTodayPercentageAchieved: {0}", temp.ComputedTargetAsOfTodayPercentageAchieved); Console.WriteLine("ComputedTargetAsOfTodayMoney: {0}", temp.ComputedTargetAsOfTodayMoney.Value); Console.WriteLine("<End of Listing>"); } DeleteRequiredRecords(promptforDelete); } //</snippetRollupAllGoalsForCustomPeriodAgainstTargetRevenue1> } // 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 = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials)) { // 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. /// Initiate creating all entity records that this sample requires. /// Create a bundle record. /// Add products to a bundle. /// 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(); //<snippetAddProductstoBundle1> // Add products to a bundle ProductAssociation newAssociation1 = new ProductAssociation { AssociatedProduct = new EntityReference(Product.EntityLogicalName, _product1Id), ProductId = new EntityReference(Product.EntityLogicalName, _bundleId), Quantity = new decimal(15), ProductIsRequired = new OptionSetValue(0), // Adding this as an optional product UoMId = new EntityReference(UoM.EntityLogicalName, unit.Id) }; _product1AssociationId = _serviceProxy.Create(newAssociation1); ProductAssociation newAssociation2 = new ProductAssociation { AssociatedProduct = new EntityReference(Product.EntityLogicalName, _product2Id), ProductId = new EntityReference(Product.EntityLogicalName, _bundleId), Quantity = new decimal(20), ProductIsRequired = new OptionSetValue(1), // Adding this as a mandatory product UoMId = new EntityReference(UoM.EntityLogicalName, unit.Id), }; _product2AssociationId = _serviceProxy.Create(newAssociation2); // Verify if the product association is created if ((_product1AssociationId != null) && (_product1AssociationId != null)) { Console.WriteLine("\nAdded both the products to the bundle"); } //</snippetAddProductstoBundle1> DeleteRequiredRecords(promptForDelete); } } catch { // 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> /// Convert a fax to a task. /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> /// </summary> public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); // Call the method to create any data that this sample requires. CreateRequiredRecords(); //<snippetConvertFaxToTask1> // Retrieve the fax. Fax retrievedFax = (Fax)_serviceProxy.Retrieve(Fax.EntityLogicalName, _faxId, new ColumnSet(true)); // Create a task. Task task = new Task() { Subject = "Follow Up: " + retrievedFax.Subject, ScheduledEnd = retrievedFax.CreatedOn.Value.AddDays(7), }; _taskId = _serviceProxy.Create(task); // Verify that the task has been created if (_taskId != Guid.Empty) { Console.WriteLine("Created a task for the fax: '{0}'.", task.Subject); } //</snippetConvertFaxToTask1> 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; } }
private static Guid CreateSystemUser(String userName, String firstName, String lastName, String domain, String roleStr, OrganizationServiceProxy serviceProxy, ref String ldapPath) { CreateADAccount(userName, firstName, lastName, serviceProxy, ref ldapPath); // Retrieve the default business unit needed to create the user. QueryExpression businessUnitQuery = new QueryExpression { EntityName = BusinessUnit.EntityLogicalName, ColumnSet = new ColumnSet("businessunitid"), Criteria = { Conditions = { new ConditionExpression("parentbusinessunitid", ConditionOperator.Null) } } }; BusinessUnit defaultBusinessUnit = serviceProxy.RetrieveMultiple( businessUnitQuery).Entities[0].ToEntity<BusinessUnit>(); //Create a new system user. SystemUser user = new SystemUser { DomainName = domain + userName, FirstName = firstName, LastName = lastName, BusinessUnitId = new EntityReference { LogicalName = BusinessUnit.EntityLogicalName, Name = BusinessUnit.EntityLogicalName, Id = defaultBusinessUnit.Id } }; Guid userId = serviceProxy.Create(user); if (!String.IsNullOrWhiteSpace(roleStr)) { // Retrieve the specified security role. Role role = RetrieveRoleByName(serviceProxy, roleStr); // Assign the security role to the newly created Microsoft Dynamics CRM user. AssociateRequest associate = new AssociateRequest() { Target = new EntityReference(SystemUser.EntityLogicalName, userId), RelatedEntities = new EntityReferenceCollection() { new EntityReference(Role.EntityLogicalName, role.Id), }, Relationship = new Relationship("systemuserroles_association") }; serviceProxy.Execute(associate); } return userId; }
/// <summary> /// Create and configure the organization service proxy. /// Initiate the method to create any data that this sample requires. /// Delete a new queue instance. /// Optionally delete any entity records that were created for this sample. /// </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(); #region Run a QC with marketing list as input //<snippetQuickCampaign1> List newList = new List() { ListName = "TestList", CreatedFromCode = new OptionSetValue((int)ListCreatedFromCode.Account) }; _newListId = _serviceProxy.Create(newList); for (int j = 0; j < 5; j++) { AddMemberListRequest addMemberListRequest = new AddMemberListRequest(); addMemberListRequest.EntityId = _accountIdArray[j]; addMemberListRequest.ListId = _newListId; AddMemberListResponse addMemberListResponse = _serviceProxy.Execute(addMemberListRequest) as AddMemberListResponse; } Guid BOId = CreateAndRetrieveQuickCampaignForMarketingList( _templateLetterActivity, _newListId, PropagationOwnershipOptions.ListMemberOwner, true); //</snippetQuickCampaign1> #endregion #region Run a QC with a list of accounts as input // Construct a Query Expression(QE) which specifies which records QC should include QueryExpression query = new QueryExpression("account"); query.ColumnSet = new ColumnSet("accountid"); query.Criteria = new FilterExpression(); FilterExpression filter = query.Criteria.AddFilter(LogicalOperator.Or); for (int j = 0; j < 5; j++) { filter.AddCondition("accountid", ConditionOperator.Equal, _accountIdArray[j]); } _qcBOId = CreateAndRetrieveQuickCampaignForQueryExpression( _templateEmailActivity, query, PropagationOwnershipOptions.ListMemberOwner, true); #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, /// 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 { //<snippetCRUDOperations1> // 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(); // Instantiate an account object. // See the Entity Metadata topic in the SDK documentation to determine // which attributes must be set for each entity. Account account = new Account { Name = "Fourth Coffee" }; // Create an account record named Fourth Coffee. _accountId = _serviceProxy.Create(account); Console.Write("{0} {1} created, ", account.LogicalName, account.Name); // Retrieve the account containing several of its attributes. ColumnSet cols = new ColumnSet( new String[] { "name", "address1_postalcode", "lastusedincampaign", "versionnumber" }); Account retrievedAccount = (Account)_serviceProxy.Retrieve("account", _accountId, cols); Console.Write("retrieved "); // Retrieve version number of the account. Shows BigInt attribute usage. long? versionNumber = retrievedAccount.VersionNumber; if (versionNumber != null) Console.WriteLine("version # {0}, ", versionNumber); // Update the postal code attribute. retrievedAccount.Address1_PostalCode = "98052"; // The address 2 postal code was set accidentally, so set it to null. retrievedAccount.Address2_PostalCode = null; // Shows usage of option set (picklist) enumerations defined in OptionSets.cs. retrievedAccount.Address1_AddressTypeCode = new OptionSetValue((int)AccountAddress1_AddressTypeCode.Primary); retrievedAccount.Address1_ShippingMethodCode = new OptionSetValue((int)AccountAddress1_ShippingMethodCode.DHL); retrievedAccount.IndustryCode = new OptionSetValue((int)AccountIndustryCode.AgricultureandNonpetrolNaturalResourceExtraction); // Shows use of a Money value. retrievedAccount.Revenue = new Money(5000000); // Shows use of a Boolean value. retrievedAccount.CreditOnHold = false; // Shows use of EntityReference. retrievedAccount.ParentAccountId = new EntityReference(Account.EntityLogicalName, _parentAccountId); // Shows use of Memo attribute. retrievedAccount.Description = "Account for Fourth Coffee."; // Update the account record. _serviceProxy.Update(retrievedAccount); Console.WriteLine("and updated."); DeleteRequiredRecords(promptforDelete); } //</snippetCRUDOperations1> } // 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 Create XAML // Define the workflow XAML. string xamlWF; 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 Create XAML #region Create Workflow //<snippetCreateAWorkflow1> // Create an asynchronous workflow. // The workflow should execute after a new opportunity is created. Workflow workflow = new Workflow() { // These properties map to the New Process form settings in the web application. Name = "Set closeprobability on opportunity create (async)", Type = new OptionSetValue((int)WorkflowType.Definition), Category = new OptionSetValue((int)WorkflowCategory.Workflow), PrimaryEntity = Opportunity.EntityLogicalName, Mode = new OptionSetValue((int)WorkflowMode.Background), // 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), TriggerOnCreate = true, AsyncAutoDelete = true, Xaml = xamlWF, // Other properties not in the web forms. LanguageCode = 1033, // U.S. English }; _workflowId = _serviceProxy.Create(workflow); //</snippetCreateAWorkflow1> Console.WriteLine("Created Workflow: " + workflow.Name); #endregion Create Workflow #region Activate Workflow // Activate the workflow. 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 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> /// This method first connects to the Organization service. Afterwards, /// it creates a system user account with a given active directory account. /// 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 { //<snippetCreateAUser1> // 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 the default business unit needed to create the user. QueryExpression businessUnitQuery = new QueryExpression { EntityName = BusinessUnit.EntityLogicalName, ColumnSet = new ColumnSet("businessunitid"), Criteria = { Conditions = { new ConditionExpression("parentbusinessunitid", ConditionOperator.Null) } } }; BusinessUnit defaultBusinessUnit = _serviceProxy.RetrieveMultiple( businessUnitQuery).Entities[0].ToEntity<BusinessUnit>(); //Create a new system user. SystemUser user = new SystemUser { DomainName = _domain + _userName, FirstName = _firstName, LastName = _lastName, BusinessUnitId = new EntityReference { LogicalName = BusinessUnit.EntityLogicalName, Name = BusinessUnit.EntityLogicalName, Id = defaultBusinessUnit.Id } }; Guid userId = _serviceProxy.Create(user); Console.WriteLine("Created a system user {0} for '{1}, {2}'", userId, _lastName, _firstName); } //</snippetCreateAUser1> } // 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 recurring appointment. /// Retrieve the recurring appointment. /// Update the retrieved recurring appointment. /// 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(); //<snippetCRUDRecurringAppointment1> // Define an anonymous type to define the possible recurrence pattern values. var RecurrencePatternTypes = new { Daily = 0, Weekly = 1, Monthly = 2, Yearly = 3 }; // Define an anonymous type to define the possible values for days // of the week var DayOfWeek = new { Sunday = 0x01, Monday = 0x02, Tuesday = 0x04, Wednesday = 0x08, Thursday = 0x10, Friday = 0x20, Saturday = 0x40 }; // Define an anonymous type to define the possible values // for the recurrence rule pattern end type. var RecurrenceRulePatternEndType = new { NoEndDate = 1, Occurrences = 2, PatternEndDate = 3 }; // Create a recurring appointment RecurringAppointmentMaster newRecurringAppointment = new RecurringAppointmentMaster { Subject = "Sample Recurring Appointment", StartTime = DateTime.Now.AddHours(1), EndTime = DateTime.Now.AddHours(2), RecurrencePatternType = new OptionSetValue(RecurrencePatternTypes.Weekly), Interval = 1, DaysOfWeekMask = DayOfWeek.Thursday, PatternStartDate = DateTime.Today, Occurrences = 10, PatternEndType = new OptionSetValue(RecurrenceRulePatternEndType.Occurrences) }; _recurringAppointmentMasterId = _serviceProxy.Create(newRecurringAppointment); Console.WriteLine("Created {0}.", newRecurringAppointment.Subject); // Retrieve the newly created recurring appointment QueryExpression recurringAppointmentQuery = new QueryExpression { EntityName = RecurringAppointmentMaster.EntityLogicalName, ColumnSet = new ColumnSet("subject"), Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "subject", Operator = ConditionOperator.Equal, Values = { "Sample Recurring Appointment" } }, new ConditionExpression { AttributeName = "interval", Operator = ConditionOperator.Equal, Values = { 1 } } } }, PageInfo = new PagingInfo { Count = 1, PageNumber = 1 } }; RecurringAppointmentMaster retrievedRecurringAppointment = _serviceProxy.RetrieveMultiple(recurringAppointmentQuery). Entities.Select(x => (RecurringAppointmentMaster)x).FirstOrDefault(); Console.WriteLine("Retrieved the recurring appointment."); // Update the recurring appointment. // Update the following for the retrieved recurring appointment series: // 1. Update the subject. // 2. Update the number of occurences to 5. // 3. Update the appointment interval to 2. retrievedRecurringAppointment.Subject = "Updated Recurring Appointment"; retrievedRecurringAppointment.Occurrences = 5; retrievedRecurringAppointment.Interval = 2; _serviceProxy.Update(retrievedRecurringAppointment); Console.WriteLine("Updated the subject, occurrences, and interval of the recurring appointment."); //</snippetCRUDRecurringAppointment1> 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 = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials)) { // 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> /// This method first connects to the Organization service. Afterwards, /// a Contract Template and several Contracts are created, demonstrating how to /// create and work with the Contract entity. /// </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 { //<snippetWorkingWithContracts1> // 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 Create Contract Template // First, attempt to retrieve the Contract Template. Otherwise, // create the template. QueryExpression templateQuery = new QueryExpression() { EntityName = ContractTemplate.EntityLogicalName, ColumnSet = new ColumnSet("contracttemplateid"), Criteria = { Conditions = { new ConditionExpression("abbreviation", ConditionOperator.Equal, "SCT") } } }; EntityCollection ec = _serviceProxy.RetrieveMultiple(templateQuery); if (ec.Entities.Count > 0) { _contractTemplateId = ec.Entities[0].Id; Console.Write("Template retrieved, "); } else { ContractTemplate contractTemplate = new ContractTemplate() { Name = "Sample Contract Template", BillingFrequencyCode = new OptionSetValue((int)ContractTemplateBillingFrequencyCode.Monthly), Abbreviation = "SCT", AllotmentTypeCode = new OptionSetValue((int)ContractTemplateAllotmentTypeCode.NumberofCases), EffectivityCalendar = "--------+++++++++---------------+++++++++---------------+++++++++---------------+++++++++---------------+++++++++-------------------------------------------------------" }; _contractTemplateId = _serviceProxy.Create(contractTemplate); Console.Write("Template created, "); } #endregion #region Create Contract // Create a Contract from the Contract Template. Contract contract = new Contract() { Title = "Sample Contract", ContractTemplateId = new EntityReference { Id = _contractTemplateId, LogicalName = ContractTemplate.EntityLogicalName }, CustomerId = new EntityReference { Id = _accountId, LogicalName = Account.EntityLogicalName }, BillingCustomerId = new EntityReference { Id = _accountId, LogicalName = Account.EntityLogicalName }, ActiveOn = new DateTime(2015, 1, 1), ExpiresOn = new DateTime(2020, 1, 1), BillingStartOn = new DateTime(2015, 1, 1), BillingEndOn = new DateTime(2020, 1, 1) }; _contractId = _serviceProxy.Create(contract); Console.Write("parent contract created, "); // Create a contract line item. ContractDetail contractLineItem = new ContractDetail() { Title = "Sample Contract Line Item", ContractId = new EntityReference { Id = _contractId, LogicalName = Contract.EntityLogicalName }, CustomerId = new EntityReference { Id = _accountId, LogicalName = Account.EntityLogicalName }, ActiveOn = new DateTime(2015, 1, 1), ExpiresOn = new DateTime(2020, 1, 1), Price = new Money(20.0M), TotalAllotments = 20 }; _serviceProxy.Create(contractLineItem); Console.Write("contract line attached, "); #endregion #region Clone contract twice //<snippetCloneContract> // Create the first clone of the contract. CloneContractRequest cloneRequest = new CloneContractRequest() { ContractId = _contractId, IncludeCanceledLines = false }; CloneContractResponse cloneResponse = (CloneContractResponse)_serviceProxy.Execute(cloneRequest); _firstCloneId = ((Contract)cloneResponse.Entity).ContractId.Value; //</snippetCloneContract> Console.Write("first clone created, "); // Create the second clone of the contract. cloneRequest = new CloneContractRequest() { ContractId = _contractId, IncludeCanceledLines = true }; cloneResponse = (CloneContractResponse)_serviceProxy.Execute(cloneRequest); _secondCloneId = ((Contract)cloneResponse.Entity).ContractId.Value; Console.Write("second clone created. \n"); // Retrieve all Contracts. QueryExpression contractQuery = new QueryExpression() { EntityName = Contract.EntityLogicalName, ColumnSet = new ColumnSet("contractid"), Criteria = { Conditions = { new ConditionExpression("customerid", ConditionOperator.Equal, _accountId) } } }; EntityCollection contracts = _serviceProxy.RetrieveMultiple(contractQuery); // Display the retrieved Contract Ids. for (int i = 0; i < contracts.Entities.Count; i++) { Console.WriteLine("Retrieved contract with Id: {0}", ((Contract)contracts.Entities[i]).ContractId); } #endregion #region Deactivate a cloned contract // In order to deactivate a contract (put it on hold), it is first // necessary to invoice the contract. SetStateRequest setStateRequest = new SetStateRequest() { EntityMoniker = new EntityReference { Id = _firstCloneId, LogicalName = Contract.EntityLogicalName }, State = new OptionSetValue((int)ContractState.Invoiced), Status = new OptionSetValue(2) }; _serviceProxy.Execute(setStateRequest); Console.Write("Contract invoiced, "); // Now that the contract has been invoiced, it is possible to put // the contract on hold. setStateRequest = new SetStateRequest() { EntityMoniker = new EntityReference { Id = _firstCloneId, LogicalName = Contract.EntityLogicalName }, State = new OptionSetValue((int)ContractState.OnHold), Status = new OptionSetValue(4) }; _serviceProxy.Execute(setStateRequest); Console.Write("and put on hold.\n"); #endregion #region Renew an invoiced contract // In order to renew a contract, it must be invoiced first, and // then canceled. //<snippetSetStateForContract> // Invoice the contract. setStateRequest = new SetStateRequest() { EntityMoniker = new EntityReference { Id = _contractId, LogicalName = Contract.EntityLogicalName }, State = new OptionSetValue((int)ContractState.Invoiced), Status = new OptionSetValue(3) }; _serviceProxy.Execute(setStateRequest); //</snippetSetStateForContract> Console.Write("Contract invoiced, "); //<snippetCancelContract> // Cancel the contract. setStateRequest = new SetStateRequest() { EntityMoniker = new EntityReference { Id = _contractId, LogicalName = Contract.EntityLogicalName }, State = new OptionSetValue((int)ContractState.Canceled), Status = new OptionSetValue(5) }; _serviceProxy.Execute(setStateRequest); //</snippetCancelContract> Console.Write("canceled, "); //<snippetRenewContract> // Renew the canceled contract. RenewContractRequest renewRequest = new RenewContractRequest() { ContractId = _contractId, IncludeCanceledLines = true, Status = 1 }; RenewContractResponse renewResponse = (RenewContractResponse)_serviceProxy.Execute(renewRequest); // Retrieve Id of renewed contract. _renewedId = ((Contract)renewResponse.Entity).ContractId.Value; //</snippetRenewContract> // Display the Id of the renewed contract. Console.WriteLine("and renewed."); #endregion DeleteRequiredRecords(promptforDelete); } //</snippetWorkingWithContracts1> } // 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 method to create any data that this sample requires. /// Create a new opportunity and few opportunity product /// including write-in product. /// 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(); CreateRequiredRecords(); //<snippetCreateOpportunity1> // Create a new opportunity with user specified estimated revenue Opportunity newOpportunity = new Opportunity { Name = "Example Opportunity", CustomerId = new EntityReference(Account.EntityLogicalName, _accountId), PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId), IsRevenueSystemCalculated = false, EstimatedValue = new Money(400.00m), FreightAmount = new Money(10.00m), DiscountAmount = new Money(0.10m), DiscountPercentage = 0.20m }; _opportunityId = _serviceProxy.Create(newOpportunity); Console.WriteLine("Created {0} with user specified estimated revenue.", newOpportunity.Name); // Create a new opportunity product from the catalog // Create a catalog product OpportunityProduct catalogProduct = new OpportunityProduct { OpportunityId = new EntityReference(Opportunity.EntityLogicalName, _opportunityId), ProductId = new EntityReference(Product.EntityLogicalName, _product1Id), UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId), Quantity = 8, Tax = new Money(12.42m) }; _catalogProductId = _serviceProxy.Create(catalogProduct); Console.WriteLine("Created the catalog product."); // Create anothter catalog product and override the list price OpportunityProduct catalogProductPriceOverride = new OpportunityProduct { OpportunityId = new EntityReference(Opportunity.EntityLogicalName, _opportunityId), ProductId = new EntityReference(Product.EntityLogicalName, _product2Id), UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId), Quantity = 3, Tax = new Money(2.88m), IsPriceOverridden = true, PricePerUnit = new Money(12) }; _catalogProductPriceOverrideId = _serviceProxy.Create( catalogProductPriceOverride); Console.WriteLine(@"Created another catalog product and overriden the list price."); // create a new write-in opportunity product with a manual discount applied OpportunityProduct writeInProduct = new OpportunityProduct { OpportunityId = new EntityReference(Opportunity.EntityLogicalName, _opportunityId), IsProductOverridden = true, ProductDescription = "Example Write-in Product", PricePerUnit = new Money(20.00m), Quantity = 5, ManualDiscountAmount = new Money(10.50m), Tax = new Money(7.16m) }; _writeInProductId = _serviceProxy.Create(writeInProduct); Console.WriteLine("Created {0}.", writeInProduct.ProductDescription); //</snippetCreateOpportunity1> 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 custom entity is created and configured to support entity images. /// Then records are created using this custom entity with image data. /// The records are then retrieved and the resized images are saved. /// Finally, the custom entity can be deleted. /// </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 { //<snippetEntityImages1> // 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(); Console.WriteLine("Please wait while the custom Image Attribute Demo entity used by this sample is created."); //Creates the Image Attribute Demo entity used in this sample CreateImageAttributeDemoEntity(); //Create 5 records using different sized images. /* This sample uses late-binding because the entity was just created and is not included in the 'MyOrganizationsCrmSdkTypes.cs' file created by the code generation tool (CrmSvcUtil.exe) */ //<snippetEntityImages2> //Use a 144x144 pixel image Entity imageEntity1 = new Entity(_customEntityName.ToLower()); imageEntity1["sample_name"] = "144x144.png"; imageEntity1["entityimage"] = File.ReadAllBytes("Images\\144x144.png"); Guid imageEntity1Id = _serviceProxy.Create(imageEntity1); ShowEntityFormInBrowser(promptforDelete, "144x144.png", imageEntity1Id); //Use a 144x400 pixel image Entity imageEntity2 = new Entity(_customEntityName.ToLower()); imageEntity2["sample_name"] = "144x400.png"; imageEntity2["entityimage"] = File.ReadAllBytes("Images\\144x400.png"); Guid imageEntity2Id = _serviceProxy.Create(imageEntity2); ShowEntityFormInBrowser(promptforDelete, "144x400.png", imageEntity2Id); //Use a 400x144 pixel image Entity imageEntity3 = new Entity(_customEntityName.ToLower()); imageEntity3["sample_name"] = "400x144.png"; imageEntity3["entityimage"] = File.ReadAllBytes("Images\\400x144.png"); Guid imageEntity3Id = _serviceProxy.Create(imageEntity3); ShowEntityFormInBrowser(promptforDelete, "400x144.png", imageEntity3Id); //Use a 400x500 pixel image Entity imageEntity4 = new Entity(_customEntityName.ToLower()); imageEntity4["sample_name"] = "400x500.png"; imageEntity4["entityimage"] = File.ReadAllBytes("Images\\400x500.png"); Guid imageEntity4Id = _serviceProxy.Create(imageEntity4); ShowEntityFormInBrowser(promptforDelete, "400x500.png", imageEntity4Id); //Use a 60x80 pixel image Entity imageEntity5 = new Entity(_customEntityName.ToLower()); imageEntity5["sample_name"] = "60x80.png"; imageEntity5["entityimage"] = File.ReadAllBytes("Images\\60x80.png"); Guid imageEntity5Id = _serviceProxy.Create(imageEntity5); ShowEntityFormInBrowser(promptforDelete, "60x80.png", imageEntity5Id); //</snippetEntityImages2> Console.WriteLine(); //<snippetEntityImages3> //Retrieve and download the binary images string binaryImageQuery = String.Format(@"<fetch mapping='logical'> <entity name='{0}'> <attribute name='sample_name' /> <attribute name='entityimage' /> </entity> </fetch>",_customEntityName.ToLower()); EntityCollection binaryImageResults = _serviceProxy.RetrieveMultiple(new FetchExpression(binaryImageQuery)); Console.WriteLine("Records retrieved and image files saved to: {0}", Directory.GetCurrentDirectory()); foreach (Entity record in binaryImageResults.Entities) { String recordName = record["sample_name"] as String; String downloadedFileName = String.Format("Downloaded_{0}", recordName); byte[] imageBytes = record["entityimage"] as byte[]; var fs = new BinaryWriter(new FileStream(downloadedFileName, FileMode.Append, FileAccess.Write)); fs.Write(imageBytes); fs.Close(); Console.WriteLine(downloadedFileName); } //</snippetEntityImages3> Console.WriteLine(); //<snippetEntityImages4> //Retrieve and the records with just the url string imageUrlQuery = String.Format(@"<fetch mapping='logical'> <entity name='{0}'> <attribute name='sample_name' /> <attribute name='entityimage_url' /> </entity> </fetch>", _customEntityName.ToLower()); EntityCollection imageUrlResults = _serviceProxy.RetrieveMultiple(new FetchExpression(imageUrlQuery)); Console.WriteLine("These are the relative URLs for the images retrieved:"); foreach (Entity record in imageUrlResults.Entities) { String imageUrl = record["entityimage_url"] as String; Console.WriteLine(imageUrl); } //</snippetEntityImages4> DeleteImageAttributeDemoEntity(promptforDelete); } //</snippetEntityImages1> } // 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; } }
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)) { String ldapPath = String.Empty; Guid businessUnitId; // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); // Call this method to create any data that this sample requires. CreateRequiredRecords(); // Retrieve the sales people that will be added to the team. salesPersons = SystemUserProvider.RetrieveSalespersons(_serviceProxy, ref ldapPath); // Get the ID's of the current user and business unit. var who = new WhoAmIRequest(); var whoResponse = (WhoAmIResponse)_serviceProxy.Execute(who); _currentUserId = whoResponse.UserId; businessUnitId = whoResponse.BusinessUnitId; //<snippetCreateAndShareAccessTeam1> // Create a access team. var team = new Team { AdministratorId = new EntityReference( "systemuser", _currentUserId), Name = "UserAccess Test Team", BusinessUnitId = new EntityReference( "businessunit", businessUnitId), TeamType = new OptionSetValue((int)TeamTeamType.Access), }; _teamId = _serviceProxy.Create(team); Console.WriteLine("Created an access team named '{0}'.", team.Name); // Add two sales people to the access team. var addToTeamRequest = new AddMembersTeamRequest { TeamId = _teamId, MemberIds = new[] { salesPersons[0], salesPersons[1] } }; _serviceProxy.Execute(addToTeamRequest); Console.WriteLine("Added two sales people to the team."); // Grant the team read/write access to an account. var accountReference = new EntityReference(Account.EntityLogicalName, _accountId); var teamReference = new EntityReference(Team.EntityLogicalName, _teamId); var grantAccessRequest = new GrantAccessRequest { PrincipalAccess = new PrincipalAccess { AccessMask = AccessRights.ReadAccess | AccessRights.WriteAccess, Principal = teamReference }, Target = accountReference }; _serviceProxy.Execute(grantAccessRequest); Console.WriteLine("Granted read/write access on the account record to the team."); //</snippetCreateAndShareAccessTeam1> // Retrieve and display access information for the account. RetrieveAndDisplayEntityAccess(accountReference); // Display the account access for the team and its members. var currentUserReference = new EntityReference( SystemUser.EntityLogicalName, _currentUserId); RetrieveAndDisplayPrincipalAccess(accountReference, currentUserReference, "Current User"); var firstSalesPersonReference = new EntityReference( SystemUser.EntityLogicalName, salesPersons[0]); RetrieveAndDisplayPrincipalAccess(accountReference, firstSalesPersonReference, "Sales Person"); var secondSalesPersonReference = new EntityReference( SystemUser.EntityLogicalName, salesPersons[1]); RetrieveAndDisplayPrincipalAccess(accountReference, secondSalesPersonReference, "Sales Person"); // Delete all records created by this sample. 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 checks if the logged on user has prvReadPOAA permissions. /// Afterwards, the method creates the secure custom fields required for this sample, /// an account record for testing purposes, and POAA records for the user /// and those custom fields. /// Finally, the method retrieves the User Shared Attribute permissions for that user. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { //<snippetRetrieveUserSharedAttributePermissions1> // 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(); //<snippetRetrieveUserSharedAttributePermissions2> #region Check if this user has prvReadPOAA // Get the GUID of the current user. WhoAmIRequest whoAmI = new WhoAmIRequest(); Guid userLoggedId = ((WhoAmIResponse)_serviceProxy.Execute(whoAmI)).UserId; Console.WriteLine("User logged: " + userLoggedId); // Check if this user has prvReadPOAA. RetrieveUserPrivilegesRequest userPrivilegesRequest = new RetrieveUserPrivilegesRequest(); userPrivilegesRequest.UserId = userLoggedId; RetrieveUserPrivilegesResponse userPrivilegesResponse = (RetrieveUserPrivilegesResponse)_serviceProxy.Execute(userPrivilegesRequest); // Fixed the GUID for prvReadPOAA. Guid prvReadPOAA = new Guid("{68564CD5-2B2E-11DF-80A6-00137299E1C2}"); if (userPrivilegesResponse.RolePrivileges.Any(r => r.PrivilegeId.Equals(prvReadPOAA))) { Console.WriteLine("This user DOES have prvReadPOAA"); } else { Console.WriteLine("This user DOESN'T have prvReadPOAA"); } Console.WriteLine(); #endregion Check if this user has prvReadPOAA //</snippetRetrieveUserSharedAttributePermissions2> #region Create an account record // Create an account record Account accountRecord = new Account(); accountRecord.Name = "Ane"; accountRecord["secret_phone"] = "123456"; _accountRecordId = _serviceProxy.Create(accountRecord); Console.WriteLine("Account record created."); #endregion Create an account record #region Create POAA entity for field #1 // Create POAA entity for field #1 PrincipalObjectAttributeAccess poaa = new PrincipalObjectAttributeAccess { AttributeId = _secretHomeId, ObjectId = new EntityReference (Account.EntityLogicalName, _accountRecordId), PrincipalId = new EntityReference (SystemUser.EntityLogicalName, userLoggedId), ReadAccess = true, UpdateAccess = true }; _serviceProxy.Create(poaa); Console.WriteLine("POAA record for custom field Secret_Home created."); #endregion Create POAA entity for field #1 #region Create POAA entity for field #2 // Create POAA entity for field #2 poaa = new PrincipalObjectAttributeAccess { AttributeId = _secretPhoneId, ObjectId = new EntityReference (Account.EntityLogicalName, _accountRecordId), PrincipalId = new EntityReference (SystemUser.EntityLogicalName, userLoggedId), ReadAccess = true, UpdateAccess = true }; _serviceProxy.Create(poaa); Console.WriteLine("POAA record for custom field Secret_Phone created."); #endregion Create POAA entity for field #2 #region Retrieve User Shared Attribute Permissions // Create the query for retrieve User Shared Attribute permissions. QueryExpression queryPOAA = new QueryExpression("principalobjectattributeaccess"); queryPOAA.ColumnSet = new ColumnSet (new string[] { "attributeid", "readaccess", "updateaccess", "principalid" }); queryPOAA.Criteria.FilterOperator = LogicalOperator.And; queryPOAA.Criteria.Conditions.Add (new ConditionExpression("objectid", ConditionOperator.Equal, _accountRecordId)); queryPOAA.Criteria.Conditions.Add (new ConditionExpression("principalid", ConditionOperator.EqualUserId)); Console.WriteLine(); Console.WriteLine("POAA for user: "******" principalid: " + ((EntityReference)entity["principalid"]).Id); Console.WriteLine(" attributeid: " + entity["attributeid"].ToString()); Console.WriteLine(" readaccess: " + entity["readaccess"].ToString()); Console.WriteLine(" updateaccess: " + entity["updateaccess"].ToString()); Console.WriteLine(); } } catch (Exception exc) { Console.WriteLine("Error: " + exc.Message); } #endregion Retrieve User Shared Attribute Permissions DeleteRequiredRecords(promptforDelete); } //</snippetRetrieveUserSharedAttributePermissions1> } // 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 = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { // 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, Retrieve, Update and Delete an e-mail attachment. /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> /// </summary> public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); CreateRequiredRecords(); //<snippetCRUDEmailAttachments1> // Create three e-mail attachments for (int i = 0; i < 3; i++) { ActivityMimeAttachment _sampleAttachment = new ActivityMimeAttachment { ObjectId = new EntityReference(Email.EntityLogicalName, _emailId), ObjectTypeCode = Email.EntityLogicalName, Subject = String.Format("Sample Attachment {0}", i), Body = System.Convert.ToBase64String( new ASCIIEncoding().GetBytes("Example Attachment")), FileName = String.Format("ExampleAttachment{0}.txt", i) }; _emailAttachmentId[i] = _serviceProxy.Create(_sampleAttachment); } Console.WriteLine("Created three e-mail attachments for the e-mail activity."); // Retrieve an attachment including its id, subject, filename and body. ActivityMimeAttachment _singleAttachment = (ActivityMimeAttachment)_serviceProxy.Retrieve( ActivityMimeAttachment.EntityLogicalName, _emailAttachmentId[0], new ColumnSet("activitymimeattachmentid", "subject", "filename", "body")); Console.WriteLine("Retrieved an email attachment, {0}.", _singleAttachment.FileName); // Update attachment _singleAttachment.FileName = "ExampleAttachmentUpdated.txt"; _serviceProxy.Update(_singleAttachment); Console.WriteLine("Updated the retrieved e-mail attachment to {0}.", _singleAttachment.FileName); // Retrieve all attachments associated with the email activity. QueryExpression _attachmentQuery = new QueryExpression { EntityName = ActivityMimeAttachment.EntityLogicalName, ColumnSet = new ColumnSet("activitymimeattachmentid"), Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "objectid", Operator = ConditionOperator.Equal, Values = {_emailId} }, new ConditionExpression { AttributeName = "objecttypecode", Operator = ConditionOperator.Equal, Values = {Email.EntityLogicalName} } } } }; EntityCollection results = _serviceProxy.RetrieveMultiple( _attachmentQuery); Console.WriteLine("Retrieved all the e-mail attachments."); //</snippetCRUDEmailAttachments1> 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 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 = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { // 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> /// This method first connects to the Organization service. Afterwards, an /// authorization profile is created, and associated to a team. Then an entity /// is created and permissions for the entity are assigned to the profile. These /// permissions are then retrieved. /// </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 { //<snippetRetrieveSecuredFieldsForAUser1> // 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(); // Create Field Security Profile. FieldSecurityProfile managersProfile = new FieldSecurityProfile(); managersProfile.Name = "Managers"; _profileId = _serviceProxy.Create(managersProfile); Console.Write("Created Profile, "); // Add team to profile. AssociateRequest teamToProfile = new AssociateRequest() { Target = new EntityReference(FieldSecurityProfile.EntityLogicalName, _profileId), RelatedEntities = new EntityReferenceCollection() { new EntityReference(Team.EntityLogicalName, _teamId) }, Relationship = new Relationship("teamprofiles_association") }; _serviceProxy.Execute(teamToProfile); // Add user to the profile. AssociateRequest userToProfile = new AssociateRequest() { Target = new EntityReference(FieldSecurityProfile.EntityLogicalName, _profileId), RelatedEntities = new EntityReferenceCollection() { new EntityReference(SystemUser.EntityLogicalName, _userId) }, Relationship = new Relationship("systemuserprofiles_association") }; _serviceProxy.Execute(userToProfile); // Create custom activity entity. CreateEntityRequest req = new CreateEntityRequest() { Entity = new EntityMetadata { LogicalName = "new_tweet", DisplayName = new Label("Tweet", 1033), DisplayCollectionName = new Label("Tweet", 1033), OwnershipType = OwnershipTypes.UserOwned, SchemaName = "New_Tweet", IsActivity = true, IsAvailableOffline = true, IsAuditEnabled = new BooleanManagedProperty(true), IsMailMergeEnabled = new BooleanManagedProperty(false), }, HasActivities = false, HasNotes = true, PrimaryAttribute = new StringAttributeMetadata() { SchemaName = "Subject", LogicalName = "subject", RequiredLevel = new AttributeRequiredLevelManagedProperty( AttributeRequiredLevel.None), MaxLength = 100, DisplayName = new Label("Subject", 1033) } }; _serviceProxy.Execute(req); Console.Write("Entity Created, "); // Add privileges for the Tweet entity to the Marketing Role. RolePrivilege[] privileges = new RolePrivilege[3]; // SDK: prvCreateActivity privileges[0] = new RolePrivilege(); privileges[0].PrivilegeId = new Guid("{091DF793-FE5E-44D4-B4CA-7E3F580C4664}"); privileges[0].Depth = PrivilegeDepth.Global; // SDK: prvReadActivity privileges[1] = new RolePrivilege(); privileges[1].PrivilegeId = new Guid("{650C14FE-3521-45FE-A000-84138688E45D}"); privileges[1].Depth = PrivilegeDepth.Global; // SDK: prvWriteActivity privileges[2] = new RolePrivilege(); privileges[2].PrivilegeId = new Guid("{0DC8F72C-57D5-4B4D-8892-FE6AAC0E4B81}"); privileges[2].Depth = PrivilegeDepth.Global; // Create and execute the request. AddPrivilegesRoleRequest request = new AddPrivilegesRoleRequest() { RoleId = _roleId, Privileges = privileges }; AddPrivilegesRoleResponse response = (AddPrivilegesRoleResponse)_serviceProxy.Execute(request); // Create custom identity attribute. CreateAttributeRequest attrReq = new CreateAttributeRequest() { Attribute = new StringAttributeMetadata() { LogicalName = "new_identity", DisplayName = new Label("Identity", 1033), SchemaName = "New_Identity", MaxLength = 500, RequiredLevel = new AttributeRequiredLevelManagedProperty( AttributeRequiredLevel.Recommended), IsSecured = true }, EntityName = "new_tweet" }; CreateAttributeResponse identityAttributeResponse = (CreateAttributeResponse)_serviceProxy.Execute(attrReq); _identityId = identityAttributeResponse.AttributeId; Console.Write("Identity Created, "); // Create custom message attribute. attrReq = new CreateAttributeRequest() { Attribute = new StringAttributeMetadata() { LogicalName = "new_message", DisplayName = new Label("Message", 1033), SchemaName = "New_Message", MaxLength = 140, RequiredLevel = new AttributeRequiredLevelManagedProperty( AttributeRequiredLevel.Recommended), IsSecured = true }, EntityName = "new_tweet" }; CreateAttributeResponse messageAttributeResponse = (CreateAttributeResponse)_serviceProxy.Execute(attrReq); _messageId = messageAttributeResponse.AttributeId; Console.Write("Message Created, "); // Create field permission object for Identity. FieldPermission identityPermission = new FieldPermission(); identityPermission.AttributeLogicalName = "new_identity"; identityPermission.EntityName = "new_tweet"; identityPermission.CanRead = new OptionSetValue(FieldPermissionType.Allowed); identityPermission.FieldSecurityProfileId = new EntityReference( FieldSecurityProfile.EntityLogicalName, _profileId); _identityPermissionId = _serviceProxy.Create(identityPermission); Console.Write("Permission Created, "); // Create list for storing retrieved profiles. List<Guid> profileIds = new List<Guid>(); // Build query to obtain the field security profiles. QueryExpression qe = new QueryExpression() { EntityName = FieldSecurityProfile.EntityLogicalName, ColumnSet = new ColumnSet("fieldsecurityprofileid"), LinkEntities = { new LinkEntity { LinkFromEntityName = FieldSecurityProfile.EntityLogicalName, LinkToEntityName = SystemUser.EntityLogicalName, LinkCriteria = { Conditions = { new ConditionExpression("systemuserid", ConditionOperator.Equal, _userId) } } } } }; // Execute the query and obtain the results. RetrieveMultipleRequest rmRequest = new RetrieveMultipleRequest() { Query = qe }; EntityCollection bec = ((RetrieveMultipleResponse)_serviceProxy.Execute( rmRequest)).EntityCollection; // Extract profiles from query result. foreach (FieldSecurityProfile profileEnt in bec.Entities) { profileIds.Add(profileEnt.FieldSecurityProfileId.Value); } Console.Write("Profiles Retrieved, "); // Retrieve attribute permissions of a FieldSecurityProfile. DataCollection<Entity> dc; // Retrieve the attributes. QueryByAttribute qba = new QueryByAttribute(FieldPermission.EntityLogicalName); qba.AddAttributeValue("fieldsecurityprofileid", _profileId); qba.ColumnSet = new ColumnSet("attributelogicalname"); dc = _serviceProxy.RetrieveMultiple(qba).Entities; Console.Write("Attributes Retrieved. "); DeleteRequiredRecords(promptforDelete); } //</snippetRetrieveSecuredFieldsForAUser1> } // 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; } }
public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { 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(); Console.WriteLine("=== Creating and Qualifying Leads ==="); // Create two leads. var lead1 = new Lead { CompanyName = "A. Datum Corporation", FirstName = "Henriette", LastName = "Andersen", Subject = "Sample Lead 1" }; _lead1Id = _serviceProxy.Create(lead1); NotifyEntityCreated(Lead.EntityLogicalName, _lead1Id); var lead2 = new Lead { CompanyName = "Adventure Works", FirstName = "Michael", LastName = "Sullivan", Subject = "Sample Lead 2" }; _lead2Id = _serviceProxy.Create(lead2); NotifyEntityCreated(Lead.EntityLogicalName, _lead2Id); //<snippetWorkingWithLeads1> // Qualify the first lead, creating an account and a contact from it, but // not creating an opportunity. var qualifyIntoAccountContactReq = new QualifyLeadRequest { CreateAccount = true, CreateContact = true, LeadId = new EntityReference(Lead.EntityLogicalName, _lead1Id), Status = new OptionSetValue((int)lead_statuscode.Qualified) }; var qualifyIntoAccountContactRes = (QualifyLeadResponse)_serviceProxy.Execute(qualifyIntoAccountContactReq); Console.WriteLine(" The first lead was qualified."); //</snippetWorkingWithLeads1> foreach (var entity in qualifyIntoAccountContactRes.CreatedEntities) { NotifyEntityCreated(entity.LogicalName, entity.Id); if (entity.LogicalName == Account.EntityLogicalName) { _leadAccountId = entity.Id; } else if (entity.LogicalName == Contact.EntityLogicalName) { _contactId = entity.Id; } } // Retrieve the organization's base currency ID for setting the // transaction currency of the opportunity. var query = new QueryExpression("organization"); query.ColumnSet = new ColumnSet("basecurrencyid"); var result = _serviceProxy.RetrieveMultiple(query); var currencyId = (EntityReference)result.Entities[0]["basecurrencyid"]; // Qualify the second lead, creating an opportunity from it, and not // creating an account or a contact. We use an existing account for the // opportunity customer instead. var qualifyIntoOpportunityReq = new QualifyLeadRequest { CreateOpportunity = true, OpportunityCurrencyId = currencyId, OpportunityCustomerId = new EntityReference( Account.EntityLogicalName, _accountId), Status = new OptionSetValue((int)lead_statuscode.Qualified), LeadId = new EntityReference(Lead.EntityLogicalName, _lead2Id) }; var qualifyIntoOpportunityRes = (QualifyLeadResponse)_serviceProxy.Execute(qualifyIntoOpportunityReq); Console.WriteLine(" The second lead was qualified."); foreach (var entity in qualifyIntoOpportunityRes.CreatedEntities) { NotifyEntityCreated(entity.LogicalName, entity.Id); if (entity.LogicalName == Opportunity.EntityLogicalName) { _opportunityId = entity.Id; } } DeleteRecords(promptforDelete); } }
/// <summary> /// This method first connects to the Organization service. Afterwards, an /// opportunity is created to demonstrate a negative estimated value. This is /// followed by the creation of a quote with a negative product quantity. /// Finally, a sales order with a negative product price is shown. /// </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 { //<snippetWorkingWithNegativePrices1> // 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 Opportunity with negative estimated value // Create a new opportunity with user-specified negative // estimated value. Opportunity opportunity = new Opportunity { Name = "Example Opportunity", CustomerId = new EntityReference(Account.EntityLogicalName, _accountId), PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId), IsRevenueSystemCalculated = false, EstimatedValue = new Money(-400.00m), FreightAmount = new Money(10.00m), ActualValue = new Money(-390.00m), OwnerId = new EntityReference { Id = _salesRepresentativeIds[0], LogicalName = SystemUser.EntityLogicalName } }; _opportunityId = _serviceProxy.Create(opportunity); opportunity.Id = _opportunityId; // Create a catalog product for the opportunity. OpportunityProduct catalogProduct = new OpportunityProduct { OpportunityId = opportunity.ToEntityReference(), ProductId = new EntityReference(Product.EntityLogicalName, _product1Id), UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId), Quantity = 8, Tax = new Money(12.42m), }; _catalogProductId = _serviceProxy.Create(catalogProduct); Console.WriteLine("Created opportunity with negative estimated value."); #endregion #region Quote with negative quantity // Create the quote. Quote quote = new Quote() { CustomerId = new EntityReference(Account.EntityLogicalName, _accountId), Name = "Sample Quote", PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId) }; _quoteId = _serviceProxy.Create(quote); quote.Id = _quoteId; // Set the quote's product quantity to a negative value. QuoteDetail quoteDetail = new QuoteDetail() { ProductId = new EntityReference(Product.EntityLogicalName, _product1Id), Quantity = -4, QuoteId = quote.ToEntityReference(), UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId) }; _quoteDetailId = _serviceProxy.Create(quoteDetail); Console.WriteLine("Created quote with negative quantity."); #endregion #region Sales Order with negative price // Create the sales order. SalesOrder order = new SalesOrder() { Name = "Faux Order", DateFulfilled = new DateTime(2010, 8, 1), PriceLevelId = new EntityReference(PriceLevel.EntityLogicalName, _priceListId), CustomerId = new EntityReference(Account.EntityLogicalName, _accountId), FreightAmount = new Money(20.0M) }; _orderId = _serviceProxy.Create(order); order.Id = _orderId; // Add the product to the order with the price overriden with a // negative value. SalesOrderDetail orderDetail = new SalesOrderDetail() { ProductId = new EntityReference(Product.EntityLogicalName, _product1Id), Quantity = 4, SalesOrderId = order.ToEntityReference(), IsPriceOverridden = true, PricePerUnit = new Money(-40.0M), UoMId = new EntityReference(UoM.EntityLogicalName, _defaultUnitId) }; _orderDetailId = _serviceProxy.Create(orderDetail); Console.WriteLine("Created order with negative price per unit."); #endregion DeleteRequiredRecords(promptforDelete); } //</snippetWorkingWithNegativePrices1> } // 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 connects to the Organization service using an impersonated user /// credential. Afterwards, basic create, retrieve, update, and delete entity /// operations are performed as the impersonated user. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete /// all created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { //<snippetImpersonateWithOnBehalfOfPrivilege1> //<snippetImpersonateWithOnBehalfOfPrivilege2> // Connect to the Organization service. // The using statement ensures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); CreateRequiredRecords(); // Retrieve the system user ID of the user to impersonate. OrganizationServiceContext orgContext = new OrganizationServiceContext(_serviceProxy); _userId = (from user in orgContext.CreateQuery<SystemUser>() where user.FullName == "Kevin Cook" select user.SystemUserId.Value).FirstOrDefault(); // To impersonate another user, set the OrganizationServiceProxy.CallerId // property to the ID of the other user. _serviceProxy.CallerId = _userId; // Instantiate an account object. // See the Entity Metadata topic in the SDK documentation to determine // which attributes must be set for each entity. Account account = new Account { Name = "Fourth Coffee" }; // Create an account record named Fourth Coffee. _accountId = _serviceProxy.Create(account); Console.Write("{0} {1} created, ", account.LogicalName, account.Name); //</snippetImpersonateWithOnBehalfOfPrivilege2> // Retrieve the account containing several of its attributes. // CreatedBy should reference the impersonated SystemUser. // CreatedOnBehalfBy should reference the running SystemUser. ColumnSet cols = new ColumnSet( "name", "createdby", "createdonbehalfby", "address1_postalcode", "lastusedincampaign"); Account retrievedAccount = (Account)_serviceProxy.Retrieve(Account.EntityLogicalName, _accountId, cols); Console.Write("retrieved, "); // Update the postal code attribute. retrievedAccount.Address1_PostalCode = "98052"; // The address 2 postal code was set accidentally, so set it to null. retrievedAccount.Address2_PostalCode = null; // Shows use of a Money value. retrievedAccount.Revenue = new Money(5000000); // Shows use of a boolean value. retrievedAccount.CreditOnHold = false; // Update the account record. _serviceProxy.Update(retrievedAccount); Console.Write("updated, "); // Delete the account record. _serviceProxy.Delete(Account.EntityLogicalName, _accountId); Console.WriteLine("and deleted."); DeleteRequiredRecords(promptforDelete); } //</snippetImpersonateWithOnBehalfOfPrivilege1> } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>) { // You can handle an exception here or pass it back to the calling method. throw; } }
/// <summary> /// Create a view. /// Retrieve Views /// Deactivate a view /// </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> /// <param name="promptForReactivate">When True, the user will be prompted to reactivate /// a view that was deactivated.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete, bool promptForReactivate) { 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 the view. //<snippetWorkWithViews1> System.String layoutXml = @"<grid name='resultset' object='3' jump='name' select='1' preview='1' icon='1'> <row name='result' id='opportunityid'> <cell name='name' width='150' /> <cell name='customerid' width='150' /> <cell name='estimatedclosedate' width='150' /> <cell name='estimatedvalue' width='150' /> <cell name='closeprobability' width='150' /> <cell name='opportunityratingcode' width='150' /> <cell name='opportunitycustomeridcontactcontactid.emailaddress1' width='150' disableSorting='1' /> </row> </grid>"; System.String fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'> <entity name='opportunity'> <order attribute='estimatedvalue' descending='false' /> <filter type='and'> <condition attribute='statecode' operator='eq' value='0' /> </filter> <attribute name='name' /> <attribute name='estimatedvalue' /> <attribute name='estimatedclosedate' /> <attribute name='customerid' /> <attribute name='opportunityratingcode' /> <attribute name='closeprobability' /> <link-entity alias='opportunitycustomeridcontactcontactid' name='contact' from='contactid' to='customerid' link-type='outer' visible='false'> <attribute name='emailaddress1' /> </link-entity> <attribute name='opportunityid' /> </entity> </fetch>"; SavedQuery sq = new SavedQuery { Name = "A New Custom Public View", Description = "A Saved Query created in code", ReturnedTypeCode = "opportunity", FetchXml = fetchXml, LayoutXml = layoutXml, QueryType = 0 }; _customViewId = _serviceProxy.Create(sq); Console.WriteLine("A new view with the name {0} was created.", sq.Name); //</snippetWorkWithViews1> // Retrieve Views //<snippetWorkWithViews2> QueryExpression mySavedQuery = new QueryExpression { ColumnSet = new ColumnSet("savedqueryid", "name", "querytype", "isdefault", "returnedtypecode", "isquickfindquery"), EntityName = SavedQuery.EntityLogicalName, Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "querytype", Operator = ConditionOperator.Equal, Values = {0} }, new ConditionExpression { AttributeName = "returnedtypecode", Operator = ConditionOperator.Equal, Values = {Opportunity.EntityTypeCode} } } } }; RetrieveMultipleRequest retrieveSavedQueriesRequest = new RetrieveMultipleRequest { Query = mySavedQuery }; RetrieveMultipleResponse retrieveSavedQueriesResponse = (RetrieveMultipleResponse)_serviceProxy.Execute(retrieveSavedQueriesRequest); DataCollection<Entity> savedQueries = retrieveSavedQueriesResponse.EntityCollection.Entities; //Display the Retrieved views foreach (Entity ent in savedQueries) { SavedQuery rsq = (SavedQuery)ent; Console.WriteLine("{0} : {1} : {2} : {3} : {4} : {5},", rsq.SavedQueryId, rsq.Name, rsq.QueryType, rsq.IsDefault, rsq.ReturnedTypeCode, rsq.IsQuickFindQuery); } //</snippetWorkWithViews2> // Deactivate a view //<snippetWorkWithViews3> System.String SavedQueryName = "Closed Opportunities in Current Fiscal Year"; QueryExpression ClosedOpportunitiesViewQuery = new QueryExpression { ColumnSet = new ColumnSet("savedqueryid", "statecode", "statuscode"), EntityName = SavedQuery.EntityLogicalName, Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "querytype", Operator = ConditionOperator.Equal, Values = {0} }, new ConditionExpression { AttributeName = "returnedtypecode", Operator = ConditionOperator.Equal, Values = {Opportunity.EntityTypeCode} }, new ConditionExpression { AttributeName = "name", Operator = ConditionOperator.Equal, Values = {SavedQueryName} } } } }; RetrieveMultipleRequest retrieveOpportuntiesViewRequest = new RetrieveMultipleRequest { Query = ClosedOpportunitiesViewQuery }; RetrieveMultipleResponse retrieveOpportuntiesViewResponse = (RetrieveMultipleResponse)_serviceProxy.Execute(retrieveOpportuntiesViewRequest); SavedQuery OpportunityView = (SavedQuery)retrieveOpportuntiesViewResponse.EntityCollection.Entities[0]; _viewOriginalState = (SavedQueryState)OpportunityView.StateCode; _viewOriginalStatus = OpportunityView.StatusCode; SetStateRequest ssreq = new SetStateRequest { EntityMoniker = new EntityReference(SavedQuery.EntityLogicalName, (Guid)OpportunityView.SavedQueryId), State = new OptionSetValue((int)SavedQueryState.Inactive), Status = new OptionSetValue(2) }; _serviceProxy.Execute(ssreq); //</snippetWorkWithViews3> _deactivatedViewId = (Guid)OpportunityView.SavedQueryId; DeleteRequiredRecords(promptForDelete); ReactivateDeactivatedView(promptForReactivate); } } // 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, the /// sample creates a goal and child goals for a particular fiscal period. /// Stretched targets are tracked as well. /// </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 { //<snippetRollupAllGoalsForFiscalPeriodAndStretchedTargetRevenue1> // 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 Create goal metric // Create the metric, setting the Metric Type to 'Count' and enabling // stretch tracking. Metric metric = new Metric() { Name = "Sample Count Metric", IsAmount = false, IsStretchTracked = true }; _metricId = _serviceProxy.Create(metric); metric.Id = _metricId; Console.Write("Created count metric, "); #endregion #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 = metric.ToEntityReference() }; _actualId = _serviceProxy.Create(actual); Console.Write("created completed phone call 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", 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 closed outgoing phone calls. GoalRollupQuery goalRollupQuery2 = new GoalRollupQuery() { Name = "Example Goal Rollup Query", 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='1'/><condition attribute='statecode' operator='eq' value='1' /></filter></entity></fetch>" }; _rollupQueryIds.Add(_serviceProxy.Create(goalRollupQuery2)); goalRollupQuery2.Id = _rollupQueryIds[1]; Console.Write("created rollup queries for phone calls.\n"); Console.WriteLine(); #endregion #region Create goals // Determine current fiscal period and year. // Note: This sample assumes quarterly fiscal periods. DateTime date = DateTime.Now; int quarterNumber = (date.Month - 1) / 3 + 1; int yearNumber = date.Year; // Create three goals: one parent goal and two child goals. Goal parentGoal = new Goal() { Title = "Parent Goal Example", RollupOnlyFromChildGoals = true, ConsiderOnlyGoalOwnersRecords = true, TargetInteger = 8, StretchTargetInteger = 10, IsFiscalPeriodGoal = true, FiscalPeriod = new OptionSetValue(quarterNumber), FiscalYear = new OptionSetValue(yearNumber), MetricId = metric.ToEntityReference(), GoalOwnerId = new EntityReference { Id = _salesManagerId, LogicalName = SystemUser.EntityLogicalName }, OwnerId = new EntityReference { Id = _salesManagerId, LogicalName = SystemUser.EntityLogicalName } }; _parentGoalId = _serviceProxy.Create(parentGoal); parentGoal.Id = _parentGoalId; Console.WriteLine("Created parent goal"); Console.WriteLine("-------------------"); Console.WriteLine("Target: {0}", parentGoal.TargetInteger.Value); Console.WriteLine("Stretch Target: {0}", parentGoal.StretchTargetInteger.Value); Console.WriteLine("Goal owner: {0}", parentGoal.GoalOwnerId.Id); Console.WriteLine("Goal Fiscal Period: {0}", parentGoal.FiscalPeriod.Value); Console.WriteLine("Goal Fiscal Year: {0}", parentGoal.FiscalYear.Value); Console.WriteLine("<End of Listing>"); Console.WriteLine(); Goal firstChildGoal = new Goal() { Title = "First Child Goal Example", ConsiderOnlyGoalOwnersRecords = true, TargetInteger = 5, StretchTargetInteger = 6, IsFiscalPeriodGoal = true, FiscalPeriod = new OptionSetValue(quarterNumber), FiscalYear = new OptionSetValue(yearNumber), MetricId = metric.ToEntityReference(), ParentGoalId = parentGoal.ToEntityReference(), GoalOwnerId = new EntityReference { Id = _salesRepresentativeIds[0], LogicalName = SystemUser.EntityLogicalName }, OwnerId = new EntityReference { Id = _salesManagerId, LogicalName = SystemUser.EntityLogicalName }, RollupQueryActualIntegerId = goalRollupQuery.ToEntityReference() }; _firstChildGoalId = _serviceProxy.Create(firstChildGoal); Console.WriteLine("First child goal"); Console.WriteLine("----------------"); Console.WriteLine("Target: {0}", firstChildGoal.TargetInteger.Value); Console.WriteLine("Stretch Target: {0}", firstChildGoal.StretchTargetInteger.Value); Console.WriteLine("Goal owner: {0}", firstChildGoal.GoalOwnerId.Id); Console.WriteLine("Goal Fiscal Period: {0}", firstChildGoal.FiscalPeriod.Value); Console.WriteLine("Goal Fiscal Year: {0}", firstChildGoal.FiscalYear.Value); Console.WriteLine(); Goal secondChildGoal = new Goal() { Title = "Second Child Goal Example", ConsiderOnlyGoalOwnersRecords = true, TargetInteger = 3, StretchTargetInteger = 4, IsFiscalPeriodGoal = true, FiscalPeriod = new OptionSetValue(quarterNumber), FiscalYear = new OptionSetValue(yearNumber), MetricId = metric.ToEntityReference(), ParentGoalId = parentGoal.ToEntityReference(), GoalOwnerId = new EntityReference { Id = _salesRepresentativeIds[1], LogicalName = SystemUser.EntityLogicalName }, OwnerId = new EntityReference { Id = _salesManagerId, LogicalName = SystemUser.EntityLogicalName }, RollupQueryActualIntegerId = goalRollupQuery2.ToEntityReference() }; _secondChildGoalId = _serviceProxy.Create(secondChildGoal); Console.WriteLine("Second child goal"); Console.WriteLine("-----------------"); Console.WriteLine("Target: {0}", secondChildGoal.TargetInteger.Value); Console.WriteLine("Stretch Target: {0}", secondChildGoal.StretchTargetInteger.Value); Console.WriteLine("Goal owner: {0}", secondChildGoal.GoalOwnerId.Id); Console.WriteLine("Goal Fiscal Period: {0}", secondChildGoal.FiscalPeriod.Value); Console.WriteLine("Goal Fiscal Year: {0}", secondChildGoal.FiscalYear.Value); Console.WriteLine(); #endregion #region Calculate rollup and display result // Calculate roll-up of goals. RecalculateRequest recalculateRequest = new RecalculateRequest() { Target = new EntityReference(Goal.EntityLogicalName, _parentGoalId) }; _serviceProxy.Execute(recalculateRequest); Console.WriteLine("Calculated roll-up of goals."); // Retrieve and report 3 different computed values for the goals // - Percentage // - ComputedTargetAsOfTodayPercentageAchieved // - ComputedTargetAsOfTodayInteger QueryExpression retrieveValues = new QueryExpression() { EntityName = Goal.EntityLogicalName, ColumnSet = new ColumnSet( "title", "percentage", "computedtargetasoftodaypercentageachieved", "computedtargetasoftodayinteger") }; 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: {0}", temp.Percentage); Console.WriteLine("ComputedTargetAsOfTodayPercentageAchieved: {0}", temp.ComputedTargetAsOfTodayPercentageAchieved); Console.WriteLine("ComputedTargetAsOfTodayInteger: {0}", temp.ComputedTargetAsOfTodayInteger.Value); Console.WriteLine("<End of Listing>"); } #endregion DeleteRequiredRecords(promptforDelete); } //</snippetRollupAllGoalsForFiscalPeriodAndStretchedTargetRevenue1> } // 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> /// Shows how to perform the following tasks with solutions: /// - Create a Publisher /// - Retrieve the Default Publisher /// - Create a Solution /// - Retrieve a Solution /// - Add an existing Solution Component /// - Remove a Solution Component /// - Export or Package a Solution /// - Install or Upgrade a solution /// - Delete a Solution /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptForDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); // Call the method to create any data that this sample requires. CreateRequiredRecords(); //<snippetWorkWithSolutions1> //Define a new publisher Publisher _crmSdkPublisher = new Publisher { UniqueName = "sdksamples", FriendlyName = "Microsoft CRM SDK Samples", SupportingWebsiteUrl = "http://msdn.microsoft.com/en-us/dynamics/crm/default.aspx", CustomizationPrefix = "sample", EMailAddress = "*****@*****.**", Description = "This publisher was created with samples from the Microsoft Dynamics CRM SDK" }; //Does publisher already exist? QueryExpression querySDKSamplePublisher = new QueryExpression { EntityName = Publisher.EntityLogicalName, ColumnSet = new ColumnSet("publisherid", "customizationprefix"), Criteria = new FilterExpression() }; querySDKSamplePublisher.Criteria.AddCondition("uniquename", ConditionOperator.Equal, _crmSdkPublisher.UniqueName); EntityCollection querySDKSamplePublisherResults = _serviceProxy.RetrieveMultiple(querySDKSamplePublisher); Publisher SDKSamplePublisherResults = null; //If it already exists, use it if (querySDKSamplePublisherResults.Entities.Count > 0) { SDKSamplePublisherResults = (Publisher)querySDKSamplePublisherResults.Entities[0]; _crmSdkPublisherId = (Guid)SDKSamplePublisherResults.PublisherId; _customizationPrefix = SDKSamplePublisherResults.CustomizationPrefix; } //If it doesn't exist, create it if (SDKSamplePublisherResults == null) { _crmSdkPublisherId = _serviceProxy.Create(_crmSdkPublisher); Console.WriteLine(String.Format("Created publisher: {0}.", _crmSdkPublisher.FriendlyName)); _customizationPrefix = _crmSdkPublisher.CustomizationPrefix; } //</snippetWorkWithSolutions1> //<snippetWorkWithSolutions2> // Retrieve the Default Publisher //The default publisher has a constant GUID value; Guid DefaultPublisherId = new Guid("{d21aab71-79e7-11dd-8874-00188b01e34f}"); Publisher DefaultPublisher = (Publisher)_serviceProxy.Retrieve(Publisher.EntityLogicalName, DefaultPublisherId, new ColumnSet(new string[] {"friendlyname" })); EntityReference DefaultPublisherReference = new EntityReference { Id = DefaultPublisher.Id, LogicalName = Publisher.EntityLogicalName, Name = DefaultPublisher.FriendlyName }; Console.WriteLine("Retrieved the {0}.", DefaultPublisherReference.Name); //</snippetWorkWithSolutions2> //<snippetWorkWithSolutions3> // Create a Solution //Define a solution Solution solution = new Solution { UniqueName = "samplesolution", FriendlyName = "Sample Solution", PublisherId = new EntityReference(Publisher.EntityLogicalName, _crmSdkPublisherId), Description = "This solution was created by the WorkWithSolutions sample code in the Microsoft Dynamics CRM SDK samples.", Version = "1.0" }; //Check whether it already exists QueryExpression queryCheckForSampleSolution = new QueryExpression { EntityName = Solution.EntityLogicalName, ColumnSet = new ColumnSet(), Criteria = new FilterExpression() }; queryCheckForSampleSolution.Criteria.AddCondition("uniquename", ConditionOperator.Equal, solution.UniqueName); //Create the solution if it does not already exist. EntityCollection querySampleSolutionResults = _serviceProxy.RetrieveMultiple(queryCheckForSampleSolution); Solution SampleSolutionResults = null; if (querySampleSolutionResults.Entities.Count > 0) { SampleSolutionResults = (Solution)querySampleSolutionResults.Entities[0]; _solutionsSampleSolutionId = (Guid)SampleSolutionResults.SolutionId; } if (SampleSolutionResults == null) { _solutionsSampleSolutionId = _serviceProxy.Create(solution); } //</snippetWorkWithSolutions3> //<snippetWorkWithSolutions4> // Retrieve a solution String solutionUniqueName = "samplesolution"; QueryExpression querySampleSolution = new QueryExpression { EntityName = Solution.EntityLogicalName, ColumnSet = new ColumnSet(new string[] { "publisherid", "installedon", "version", "versionnumber", "friendlyname" }), Criteria = new FilterExpression() }; querySampleSolution.Criteria.AddCondition("uniquename", ConditionOperator.Equal, solutionUniqueName); Solution SampleSolution = (Solution)_serviceProxy.RetrieveMultiple(querySampleSolution).Entities[0]; //</snippetWorkWithSolutions4> //<snippetWorkWithSolutions5> // Add an existing Solution Component //Add the Account entity to the solution RetrieveEntityRequest retrieveForAddAccountRequest = new RetrieveEntityRequest() { LogicalName = Account.EntityLogicalName }; RetrieveEntityResponse retrieveForAddAccountResponse = (RetrieveEntityResponse)_serviceProxy.Execute(retrieveForAddAccountRequest); AddSolutionComponentRequest addReq = new AddSolutionComponentRequest() { ComponentType = (int)componenttype.Entity, ComponentId = (Guid)retrieveForAddAccountResponse.EntityMetadata.MetadataId, SolutionUniqueName = solution.UniqueName }; _serviceProxy.Execute(addReq); //</snippetWorkWithSolutions5> //<snippetWorkWithSolutions6> // Remove a Solution Component //Remove the Account entity from the solution RetrieveEntityRequest retrieveForRemoveAccountRequest = new RetrieveEntityRequest() { LogicalName = Account.EntityLogicalName }; RetrieveEntityResponse retrieveForRemoveAccountResponse = (RetrieveEntityResponse)_serviceProxy.Execute(retrieveForRemoveAccountRequest); RemoveSolutionComponentRequest removeReq = new RemoveSolutionComponentRequest() { ComponentId = (Guid)retrieveForRemoveAccountResponse.EntityMetadata.MetadataId, ComponentType = (int)componenttype.Entity, SolutionUniqueName = solution.UniqueName }; _serviceProxy.Execute(removeReq); //</snippetWorkWithSolutions6> //<snippetWorkWithSolutions7> // Export or package a solution //Export an a solution ExportSolutionRequest exportSolutionRequest = new ExportSolutionRequest(); exportSolutionRequest.Managed = false; exportSolutionRequest.SolutionName = solution.UniqueName; ExportSolutionResponse exportSolutionResponse = (ExportSolutionResponse)_serviceProxy.Execute(exportSolutionRequest); byte[] exportXml = exportSolutionResponse.ExportSolutionFile; string filename = solution.UniqueName + ".zip"; File.WriteAllBytes(outputDir + filename, exportXml); Console.WriteLine("Solution exported to {0}.", outputDir + filename); //</snippetWorkWithSolutions7> //<snippetWorkWithSolutions8> // Install or Upgrade a Solution byte[] fileBytes = File.ReadAllBytes(ManagedSolutionLocation); ImportSolutionRequest impSolReq = new ImportSolutionRequest() { CustomizationFile = fileBytes }; _serviceProxy.Execute(impSolReq); Console.WriteLine("Imported Solution from {0}", ManagedSolutionLocation); //</snippetWorkWithSolutions8> //<snippetWorkWithSolutions9> // Monitor import success byte[] fileBytesWithMonitoring = File.ReadAllBytes(ManagedSolutionLocation); ImportSolutionRequest impSolReqWithMonitoring = new ImportSolutionRequest() { CustomizationFile = fileBytes, ImportJobId = Guid.NewGuid() }; _serviceProxy.Execute(impSolReqWithMonitoring); Console.WriteLine("Imported Solution with Monitoring from {0}", ManagedSolutionLocation); ImportJob job = (ImportJob)_serviceProxy.Retrieve(ImportJob.EntityLogicalName, impSolReqWithMonitoring.ImportJobId, new ColumnSet(new System.String[] { "data", "solutionname" })); System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); doc.LoadXml(job.Data); String ImportedSolutionName = doc.SelectSingleNode("//solutionManifest/UniqueName").InnerText; String SolutionImportResult = doc.SelectSingleNode("//solutionManifest/result/@result").Value; Console.WriteLine("Report from the ImportJob data"); Console.WriteLine("Solution Unique name: {0}", ImportedSolutionName); Console.WriteLine("Solution Import Result: {0}", SolutionImportResult); Console.WriteLine(""); // This code displays the results for Global Option sets installed as part of a solution. System.Xml.XmlNodeList optionSets = doc.SelectNodes("//optionSets/optionSet"); foreach (System.Xml.XmlNode node in optionSets) { string OptionSetName = node.Attributes["LocalizedName"].Value; string result = node.FirstChild.Attributes["result"].Value; if (result == "success") { Console.WriteLine("{0} result: {1}",OptionSetName, result); } else { string errorCode = node.FirstChild.Attributes["errorcode"].Value; string errorText = node.FirstChild.Attributes["errortext"].Value; Console.WriteLine("{0} result: {1} Code: {2} Description: {3}",OptionSetName, result, errorCode, errorText); } } //</snippetWorkWithSolutions9> //<snippetWorkWithSolutions10> // Delete a solution QueryExpression queryImportedSolution = new QueryExpression { EntityName = Solution.EntityLogicalName, ColumnSet = new ColumnSet(new string[] { "solutionid", "friendlyname" }), Criteria = new FilterExpression() }; queryImportedSolution.Criteria.AddCondition("uniquename", ConditionOperator.Equal, ImportedSolutionName); Solution ImportedSolution = (Solution)_serviceProxy.RetrieveMultiple(queryImportedSolution).Entities[0]; _serviceProxy.Delete(Solution.EntityLogicalName, (Guid)ImportedSolution.SolutionId); Console.WriteLine("Deleted the {0} solution.", ImportedSolution.FriendlyName); //</snippetWorkWithSolutions10> DeleteRequiredRecords(promptForDelete); } } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>) { // You can handle an exception here or pass it back to the calling method. throw; } }