/// <summary> /// Creates any entity records that this sample requires. /// </summary> public void CreateRequiredRecords() { #region Create or Retrieve the necessary system users // Retrieve the ldapPath String ldapPath = String.Empty; // Retrieve the sales team - 1 sales manager and 2 sales representatives. _salesManagerId = SystemUserProvider.RetrieveSalesManager(_serviceProxy, ref ldapPath); _salesRepresentativeIds = SystemUserProvider.RetrieveSalespersons(_serviceProxy, ref ldapPath); #endregion #region Create PhoneCall record and supporting account Account account = new Account { Name = "Margie's Travel", Address1_PostalCode = "99999" }; _accountId = (_serviceProxy.Create(account)); account.Id = _accountId; // Create Guids for PhoneCalls _phoneCallId = Guid.NewGuid(); _phoneCall2Id = Guid.NewGuid(); // Create ActivityPartys for the phone calls' "From" field. ActivityParty activityParty = new ActivityParty() { PartyId = account.ToEntityReference(), ActivityId = new EntityReference { Id = _phoneCallId, LogicalName = PhoneCall.EntityLogicalName, }, ParticipationTypeMask = new OptionSetValue(9), }; ActivityParty activityPartyClosed = new ActivityParty() { PartyId = account.ToEntityReference(), ActivityId = new EntityReference { Id = _phoneCall2Id, LogicalName = PhoneCall.EntityLogicalName, }, ParticipationTypeMask = new OptionSetValue(9) }; // Create an open phone call. PhoneCall phoneCall = new PhoneCall() { Id = _phoneCallId, Subject = "Sample Phone Call", DirectionCode = false, To = new ActivityParty[] { activityParty }, OwnerId = new EntityReference("systemuser", _salesRepresentativeIds[0]), ActualEnd = DateTime.Now }; _serviceProxy.Create(phoneCall); // Close the first phone call. SetStateRequest closePhoneCall = new SetStateRequest() { EntityMoniker = phoneCall.ToEntityReference(), State = new OptionSetValue(1), Status = new OptionSetValue(4) }; _serviceProxy.Execute(closePhoneCall); // Create a second phone call. phoneCall = new PhoneCall() { Id = _phoneCall2Id, Subject = "Sample Phone Call 2", DirectionCode = true, To = new ActivityParty[] { activityParty }, OwnerId = new EntityReference("systemuser", _salesRepresentativeIds[1]), ActualEnd = DateTime.Now }; _serviceProxy.Create(phoneCall); // Close the second phone call. closePhoneCall = new SetStateRequest() { EntityMoniker = phoneCall.ToEntityReference(), State = new OptionSetValue(1), Status = new OptionSetValue(4) }; _serviceProxy.Execute(closePhoneCall); #endregion }
/// <summary> /// Creates any entity records that this sample requires. /// </summary> public void CreateRequiredRecords() { #region Create or Retrieve the necessary system users // Retrieve a sales manager. _salesManagerId = SystemUserProvider.RetrieveMarketingManager(_serviceProxy); #endregion #region Create PhoneCall record and supporting account Account newAccount = new Account { Name = "Margie's Travel", Address1_PostalCode = "99999" }; _accountId = (_serviceProxy.Create(newAccount)); newAccount.Id = _accountId; // Create Guids for PhoneCalls _phoneCallId = Guid.NewGuid(); _phoneCall2Id = Guid.NewGuid(); // Create ActivityPartys for the phone calls' "From" field. ActivityParty activityParty = new ActivityParty() { PartyId = newAccount.ToEntityReference(), ActivityId = new EntityReference { Id = _phoneCallId, LogicalName = PhoneCall.EntityLogicalName, }, ParticipationTypeMask = new OptionSetValue(9) }; ActivityParty activityPartyClosed = new ActivityParty() { PartyId = newAccount.ToEntityReference(), ActivityId = new EntityReference { Id = _phoneCall2Id, LogicalName = PhoneCall.EntityLogicalName, }, ParticipationTypeMask = new OptionSetValue(9) }; // Create an open phone call. PhoneCall phoneCall = new PhoneCall() { Id = _phoneCallId, Subject = "Sample Phone Call", DirectionCode = false, To = new ActivityParty[] { activityParty } }; _serviceProxy.Create(phoneCall); // Create a second phone call to close phoneCall = new PhoneCall() { Id = _phoneCall2Id, Subject = "Sample Phone Call 2", DirectionCode = false, To = new ActivityParty[] { activityParty }, ActualEnd = DateTime.Now }; _serviceProxy.Create(phoneCall); // Close the second phone call. SetStateRequest closePhoneCall = new SetStateRequest() { EntityMoniker = phoneCall.ToEntityReference(), State = new OptionSetValue(1), Status = new OptionSetValue(4) }; _serviceProxy.Execute(closePhoneCall); #endregion }
/// <summary> /// Creates any entity records that this sample requires. /// </summary> public void CreateRequiredRecords() { #region create kb articles Console.WriteLine(" Creating KB Articles"); _subjectId = ( from subject in _context.SubjectSet where subject.Title == "Default Subject" select subject.Id ).First(); var kbArticleTemplateId = ( from articleTemplate in _context.KbArticleTemplateSet where articleTemplate.Title == "Standard KB Article" select articleTemplate.Id ).FirstOrDefault(); if (kbArticleTemplateId != Guid.Empty) { // create a KB article _articles[0] = new KbArticle() { // set the article properties Title = "Searching the knowledge base", ArticleXml = @" <articledata> <section id='0'> <content><![CDATA[This is a sample article about searching the knowledge base.]]></content> </section> <section id='1'> <content><![CDATA[Knowledge bases contain information useful for various people.]]></content> </section> </articledata>", // use the built-in "Standard KB Article" template KbArticleTemplateId = new EntityReference(KbArticleTemplate.EntityLogicalName, kbArticleTemplateId), // use the default subject SubjectId = new EntityReference(Subject.EntityLogicalName, _subjectId), KeyWords = "Searching Knowledge base" }; _context.AddObject(_articles[0]); _articles[1] = new KbArticle() { Title = "What's in a knowledge base", ArticleXml = @" <articledata> <section id='0'> <content><![CDATA[This is a sample article about what would be in a knowledge base.]]></content> </section> <section id='1'> <content><![CDATA[This section contains more information.]]></content> </section> </articledata>", KbArticleTemplateId = new EntityReference(KbArticleTemplate.EntityLogicalName, kbArticleTemplateId), SubjectId = new EntityReference(Subject.EntityLogicalName, _subjectId), KeyWords = "Knowledge base" }; _context.AddObject(_articles[1]); _articles[2] = new KbArticle() { Title = "Searching the knowledge base from code", ArticleXml = @" <articledata> <section id='0'> <content><![CDATA[This article covers searching the knowledge base from code.]]></content> </section> <section id='1'> <content><![CDATA[This section contains more information.]]></content> </section> </articledata>", KbArticleTemplateId = new EntityReference(KbArticleTemplate.EntityLogicalName, kbArticleTemplateId), SubjectId = new EntityReference(Subject.EntityLogicalName, _subjectId), KeyWords = "Knowledge base code" }; _context.AddObject(_articles[2]); _context.SaveChanges(); } else { throw new ArgumentException("Standard Article Templates are missing"); } #endregion #region Submit the articles Console.WriteLine(" Submitting the articles"); foreach (var article in _articles) { _context.Execute(new SetStateRequest { EntityMoniker = article.ToEntityReference(), State = new OptionSetValue((int)KbArticleState.Unapproved), Status = new OptionSetValue((int)kbarticle_statuscode.Unapproved) }); } #endregion #region Approve and Publish the article Console.WriteLine(" Publishing articles"); foreach (var article in _articles) { _context.Execute(new SetStateRequest { EntityMoniker = article.ToEntityReference(), State = new OptionSetValue((int)KbArticleState.Published), Status = new OptionSetValue((int)kbarticle_statuscode.Published) }); } #endregion #region Waiting for publishing to finish // Wait 20 seconds to ensure that data will be available // Full-text indexing Console.WriteLine(" Waiting 20 seconds to ensure indexing has completed on the new records."); System.Threading.Thread.Sleep(20000); Console.WriteLine(); #endregion #region Add cases to KbArticles // Create UoM _uomSchedule = new UoMSchedule() { Name = "Sample unit group", BaseUoMName = "Sample base unit" }; _context.AddObject(_uomSchedule); _context.SaveChanges(); _uom = (from uom in _context.UoMSet where uom.Name == _uomSchedule.BaseUoMName select uom).First(); Console.WriteLine(" Creating an account and incidents for the KB articles"); var whoami = (WhoAmIResponse)_context.Execute(new WhoAmIRequest()); _account = new Account() { Name = "Coho Winery", }; _context.AddObject(_account); _context.SaveChanges(); _product = new Product() { Name = "Sample Product", ProductNumber = "0", ProductStructure = new OptionSetValue(1), DefaultUoMScheduleId = _uomSchedule.ToEntityReference(), DefaultUoMId = _uom.ToEntityReference() }; _context.AddObject(_product); _context.SaveChanges(); // Publish Product SetStateRequest publishRequest = new SetStateRequest { EntityMoniker = new EntityReference(Product.EntityLogicalName, _product.Id), State = new OptionSetValue((int)ProductState.Active), Status = new OptionSetValue(1) }; _context.Execute(publishRequest); _incident = new Incident() { Title = "A sample incident", OwnerId = new EntityReference(SystemUser.EntityLogicalName, whoami.UserId), KbArticleId = _articles[0].ToEntityReference(), CustomerId = _account.ToEntityReference(), SubjectId = new EntityReference(Subject.EntityLogicalName, _subjectId), ProductId = _product.ToEntityReference() }; _context.AddObject(_incident); _context.SaveChanges(); #endregion }
/// <summary> /// This method first creates an account and a lead, then initializes a new /// account from the already existing account and a new opportunity from the /// already existing lead. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { // Connect to the Organization service. // The using statement assures that the service proxy will be properly // disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); CreateRequiredRecords(); #region Initialize Account from Account Console.WriteLine(); Console.WriteLine(" Initializing new Account from the initial Account"); // Create the request object InitializeFromRequest initialize = new InitializeFromRequest(); // Set the properties of the request object initialize.TargetEntityName = Account.EntityLogicalName.ToString(); // Create the EntityMoniker initialize.EntityMoniker = _initialAccount.ToEntityReference(); // Execute the request InitializeFromResponse initialized = (InitializeFromResponse)_serviceProxy.Execute(initialize); if (initialized.Entity != null) { Console.WriteLine(" New Account initialized successfully"); } Console.WriteLine(); #endregion #region Initialize Opportunity from Lead Console.WriteLine(" Initializing an Opportunity from the initial Lead"); // Create the request object initialize.TargetEntityName = Opportunity.EntityLogicalName.ToString(); // Create the EntityMoniker initialize.EntityMoniker = _initialLead.ToEntityReference(); // Execute the request initialized = (InitializeFromResponse)_serviceProxy.Execute(initialize); if (initialized.Entity != null & amp; & initialized.Entity.LogicalName == Opportunity.EntityLogicalName) { var opportunity = (Opportunity)initialized.Entity; Console.WriteLine(" New Opportunity initialized successfully (Name={0})", opportunity.Name); } #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 and creates the /// OrganizationServiceContext. Then, several entity creation and relationship /// operations are performed. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { //<snippetBasicContextExamples1> // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); _service = (IOrganizationService)_serviceProxy; CreateRequiredRecords(); // The OrganizationServiceContext is an object that wraps the service // proxy and allows creating/updating multiple records simultaneously. _orgContext = new OrganizationServiceContext(_service); // Create a new contact called Mary Kay Andersen. var contact = new Contact() { FirstName = "Mary Kay", LastName = "Andersen", Address1_Line1 = "23 Market St.", Address1_City = "Sammamish", Address1_StateOrProvince = "MT", Address1_PostalCode = "99999", Telephone1 = "12345678", EMailAddress1 = "*****@*****.**", Id = Guid.NewGuid() }; _contactId = contact.Id; _orgContext.AddObject(contact); Console.Write("Instantiating contact, "); // Create an account called Contoso. var account = new Account() { Name = "Contoso", Address1_City = "Redmond", // set the account category to 'Preferred Customer' AccountCategoryCode = new OptionSetValue(1), LastUsedInCampaign = DateTime.Now, MarketCap = new Money(120000), DoNotEMail = true, Description = "Contoso is a fictional company!", Id = Guid.NewGuid(), }; _accountId = account.Id; Console.Write("instantiating account, "); // Set Mary Kay Andersen as the primary contact _orgContext.AddRelatedObject( contact, new Relationship("account_primary_contact"), account); SaveChangesHelper(contact, account); Console.WriteLine("and creating both records in CRM."); // Remove the primary contact value from Mary Kay Andersen _orgContext.Attach(contact); _orgContext.DeleteLink( contact, new Relationship("account_primary_contact"), account); SaveChangesHelper(contact, account); Console.Write("Removing primary contact status, "); // Add Mary Kay Andersen to the contact list for the account Contoso. _orgContext.Attach(account); _orgContext.Attach(contact); _orgContext.AddLink( account, new Relationship("contact_customer_accounts"), contact); SaveChangesHelper(contact, account); Console.WriteLine("and adding contact to account's contact list."); // Add a note with a document attachment to the contact's record. var attachment = File.OpenRead("sample.txt"); var data = new byte[attachment.Length]; attachment.Read(data, 0, (int)attachment.Length); var note = new Annotation() { Subject = "Note subject...", NoteText = "Note Details....", DocumentBody = Convert.ToBase64String(data), FileName = Path.GetFileName(attachment.Name), MimeType = "text/plain", Id = Guid.NewGuid(), // Associate the note to the contact. ObjectId = contact.ToEntityReference(), ObjectTypeCode = Contact.EntityLogicalName }; _annotationId = note.Id; Console.Write("Instantiating a note, "); _orgContext.AddObject(note); _orgContext.Attach(contact); // Set the contact as the Regarding attribute of the note. _orgContext.AddLink( contact, new Relationship("Contact_Annotation"), note); SaveChangesHelper(note, contact); Console.WriteLine("creating the note in CRM and linking to contact."); // Change the owning user of the contact Mary Kay Andersen // Find a user with an email address of "*****@*****.**" var newOwner = (from u in _orgContext.CreateQuery <SystemUser>() where u.InternalEMailAddress == "*****@*****.**" select u).Single(); AssignRequest assignRequest = new AssignRequest() { Target = contact.ToEntityReference(), Assignee = newOwner.ToEntityReference() }; _orgContext.Execute(assignRequest); Console.WriteLine("Changing ownership of contact record."); // Create a new price list called Retail Price List. var priceList = new PriceLevel() { Name = "Retail Price List", BeginDate = DateTime.Now, EndDate = DateTime.Now, Description = "Contoso's primary pricelist.", Id = Guid.NewGuid() }; _priceLevelId = priceList.Id; _orgContext.AddObject(priceList); Console.Write("Instantiating price list "); // Create a new product called Widget A. var newProduct = new Product() { Name = "Widget A", Description = "Industrial widget for hi-tech industries", ProductStructure = new OptionSetValue(1), // 1 = Product QuantityOnHand = 2, ProductNumber = "WIDG-A", Price = new Money(decimal.Parse("12.50")), QuantityDecimal = 2, // Sets the Decimals Supported value Id = Guid.NewGuid(), DefaultUoMScheduleId = new EntityReference( UoMSchedule.EntityLogicalName, _orgContext.CreateQuery <UoMSchedule>().First().Id), DefaultUoMId = new EntityReference( UoM.EntityLogicalName, _orgContext.CreateQuery <UoM>().First().Id) }; _productId = newProduct.Id; _orgContext.AddObject(newProduct); Console.WriteLine("and product."); SaveChangesHelper(priceList, newProduct); // Add Widget A to the Retail Price List. var priceLevelProduct = new ProductPriceLevel() { ProductId = newProduct.ToEntityReference(), UoMId = newProduct.DefaultUoMId, Amount = new Money(decimal.Parse("12.50")), PriceLevelId = priceList.ToEntityReference(), Id = Guid.NewGuid() }; _productPriceLevelId = priceLevelProduct.Id; _orgContext.AddObject(priceLevelProduct); Console.Write("Associating product to price list, "); // Publish the product SetStateRequest publishRequest = new SetStateRequest { EntityMoniker = newProduct.ToEntityReference(), State = new OptionSetValue((int)ProductState.Active), Status = new OptionSetValue(1) }; _serviceProxy.Execute(publishRequest); Console.WriteLine("and publishing the product."); // Create a new quote for Contoso. var newQuote = new Quote() { Name = "Quotation for Contoso", // Sets the pricelist to the one we've just created PriceLevelId = priceList.ToEntityReference(), Id = Guid.NewGuid(), CustomerId = account.ToEntityReference() }; _quoteId = newQuote.Id; _orgContext.AddObject(newQuote); _orgContext.Attach(account); _orgContext.AddLink( newQuote, new Relationship("quote_customer_accounts"), account); Console.Write("Instantiating a quote, "); // Add a quote product to this quote. var quoteProduct = new QuoteDetail() { ProductId = newProduct.ToEntityReference(), Quantity = 1, QuoteId = newQuote.ToEntityReference(), UoMId = newProduct.DefaultUoMId, Id = Guid.NewGuid() }; _quoteDetailId = quoteProduct.Id; _orgContext.AddObject(quoteProduct); Console.WriteLine("and adding product to quote."); // Create a sales opportunity with Contoso. var oppty = new Opportunity() { Name = "Interested in Widget A", EstimatedCloseDate = DateTime.Now.AddDays(30.0), EstimatedValue = new Money(decimal.Parse("300000.00")), CloseProbability = 25, // 25% probability of closing this deal IsRevenueSystemCalculated = false, // user-calculated revenue OpportunityRatingCode = new OptionSetValue(2), // warm CustomerId = account.ToEntityReference(), Id = Guid.NewGuid() }; _opportunityId = oppty.Id; _orgContext.AddObject(oppty); Console.Write("Instantiating opportunity, "); //_orgContext.AddLink( // oppty, // new Relationship("opportunity_customer_accounts"), // account); SaveChangesHelper(priceList, newQuote, newProduct, priceLevelProduct, quoteProduct, oppty, account); Console.WriteLine("and creating all records in CRM."); // Associate quote to contact, which adds the Contact record in the // "Other Contacts" section of a Quote record. _orgContext.Attach(contact); _orgContext.Attach(newQuote); _orgContext.AddLink( contact, new Relationship("contactquotes_association"), newQuote); SaveChangesHelper(contact, newQuote); Console.WriteLine("Associating contact and quote."); // Create a case for Mary Kay Andersen. var serviceRequest = new Incident() { Title = "Problem with Widget B", PriorityCode = new OptionSetValue(1), // 1 = High CaseOriginCode = new OptionSetValue(1), // 1 = Phone CaseTypeCode = new OptionSetValue(2), // 2 = Problem SubjectId = new EntityReference( Subject.EntityLogicalName, _orgContext.CreateQuery <Subject>() .First().Id), // use the default subject Description = "Customer can't switch the product on.", FollowupBy = DateTime.Now.AddHours(3.0), // follow-up in 3 hours CustomerId = contact.ToEntityReference(), Id = Guid.NewGuid() }; _incidentId = serviceRequest.Id; _orgContext.AddObject(serviceRequest); _orgContext.Attach(contact); _orgContext.AddLink( serviceRequest, new Relationship("incident_customer_contacts"), contact); SaveChangesHelper(serviceRequest, contact); Console.WriteLine("Creating service case for contact."); // Deactivate the Mary Kay Andersen contact record. SetStateRequest setInactiveRequest = new SetStateRequest { EntityMoniker = contact.ToEntityReference(), State = new OptionSetValue((int)ContactState.Inactive), Status = new OptionSetValue(2) }; _orgContext.Execute(setInactiveRequest); Console.WriteLine("Deactivating the contact record."); DeleteRequiredRecords(promptforDelete); } //</snippetBasicContextExamples1> } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ) { // You can handle an exception here or pass it back to the calling method. throw; } }
/// <summary> /// This method first connects to the Organization service and creates the /// OrganizationServiceContext. Then, several entity creation and relationship /// operations are performed. /// </summary> /// <param name="serverConfig">Contains server connection information.</param> /// <param name="promptforDelete">When True, the user will be prompted to delete all /// created entities.</param> public void Run(ServerConnection.Configuration serverConfig, bool promptforDelete) { try { //<snippetBasicContextExamples1> // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); _service = (IOrganizationService)_serviceProxy; CreateRequiredRecords(); // The OrganizationServiceContext is an object that wraps the service // proxy and allows creating/updating multiple records simultaneously. _orgContext = new OrganizationServiceContext(_service); // Create a new contact called Mary Kay Andersen. var contact = new Contact() { FirstName = "Mary Kay", LastName = "Andersen", Address1_Line1 = "23 Market St.", Address1_City = "Sammamish", Address1_StateOrProvince = "MT", Address1_PostalCode = "99999", Telephone1 = "12345678", EMailAddress1 = "*****@*****.**", Id = Guid.NewGuid() }; _contactId = contact.Id; _orgContext.AddObject(contact); Console.Write("Instantiating contact, "); // Create an account called Contoso. var account = new Account() { Name = "Contoso", Address1_City = "Redmond", // set the account category to 'Preferred Customer' AccountCategoryCode = new OptionSetValue(1), LastUsedInCampaign = DateTime.Now, MarketCap = new Money(120000), DoNotEMail = true, Description = "Contoso is a fictional company!", Id = Guid.NewGuid(), }; _accountId = account.Id; Console.Write("instantiating account, "); // Set Mary Kay Andersen as the primary contact _orgContext.AddRelatedObject( contact, new Relationship("account_primary_contact"), account); SaveChangesHelper(contact, account); Console.WriteLine("and creating both records in CRM."); // Remove the primary contact value from Mary Kay Andersen _orgContext.Attach(contact); _orgContext.DeleteLink( contact, new Relationship("account_primary_contact"), account); SaveChangesHelper(contact, account); Console.Write("Removing primary contact status, "); // Add Mary Kay Andersen to the contact list for the account Contoso. _orgContext.Attach(account); _orgContext.Attach(contact); _orgContext.AddLink( account, new Relationship("contact_customer_accounts"), contact); SaveChangesHelper(contact, account); Console.WriteLine("and adding contact to account's contact list."); // Add a note with a document attachment to the contact's record. var attachment = File.OpenRead("sample.txt"); var data = new byte[attachment.Length]; attachment.Read(data, 0, (int)attachment.Length); var note = new Annotation() { Subject = "Note subject...", NoteText = "Note Details....", DocumentBody = Convert.ToBase64String(data), FileName = Path.GetFileName(attachment.Name), MimeType = "text/plain", Id = Guid.NewGuid(), // Associate the note to the contact. ObjectId = contact.ToEntityReference(), ObjectTypeCode = Contact.EntityLogicalName }; _annotationId = note.Id; Console.Write("Instantiating a note, "); _orgContext.AddObject(note); _orgContext.Attach(contact); // Set the contact as the Regarding attribute of the note. _orgContext.AddLink( contact, new Relationship("Contact_Annotation"), note); SaveChangesHelper(note, contact); Console.WriteLine("creating the note in CRM and linking to contact."); // Change the owning user of the contact Mary Kay Andersen // Find a user with an email address of "*****@*****.**" var newOwner = (from u in _orgContext.CreateQuery<SystemUser>() where u.InternalEMailAddress == "*****@*****.**" select u).Single(); AssignRequest assignRequest = new AssignRequest() { Target = contact.ToEntityReference(), Assignee = newOwner.ToEntityReference() }; _orgContext.Execute(assignRequest); Console.WriteLine("Changing ownership of contact record."); // Create a new price list called Retail Price List. var priceList = new PriceLevel() { Name = "Retail Price List", BeginDate = DateTime.Now, EndDate = DateTime.Now, Description = "Contoso's primary pricelist.", Id = Guid.NewGuid() }; _priceLevelId = priceList.Id; _orgContext.AddObject(priceList); Console.Write("Instantiating price list "); // Create a new product called Widget A. var newProduct = new Product() { Name = "Widget A", Description = "Industrial widget for hi-tech industries", ProductStructure = new OptionSetValue(1), // 1 = Product QuantityOnHand = 2, ProductNumber = "WIDG-A", Price = new Money(decimal.Parse("12.50")), QuantityDecimal = 2, // Sets the Decimals Supported value Id = Guid.NewGuid(), DefaultUoMScheduleId = new EntityReference( UoMSchedule.EntityLogicalName, _orgContext.CreateQuery<UoMSchedule>().First().Id), DefaultUoMId = new EntityReference( UoM.EntityLogicalName, _orgContext.CreateQuery<UoM>().First().Id) }; _productId = newProduct.Id; _orgContext.AddObject(newProduct); Console.WriteLine("and product."); SaveChangesHelper(priceList, newProduct); // Add Widget A to the Retail Price List. var priceLevelProduct = new ProductPriceLevel() { ProductId = newProduct.ToEntityReference(), UoMId = newProduct.DefaultUoMId, Amount = new Money(decimal.Parse("12.50")), PriceLevelId = priceList.ToEntityReference(), Id = Guid.NewGuid() }; _productPriceLevelId = priceLevelProduct.Id; _orgContext.AddObject(priceLevelProduct); Console.Write("Associating product to price list, "); // Publish the product SetStateRequest publishRequest = new SetStateRequest { EntityMoniker = newProduct.ToEntityReference(), State = new OptionSetValue((int)ProductState.Active), Status = new OptionSetValue(1) }; _serviceProxy.Execute(publishRequest); Console.WriteLine("and publishing the product."); // Create a new quote for Contoso. var newQuote = new Quote() { Name = "Quotation for Contoso", // Sets the pricelist to the one we've just created PriceLevelId = priceList.ToEntityReference(), Id = Guid.NewGuid(), CustomerId = account.ToEntityReference() }; _quoteId = newQuote.Id; _orgContext.AddObject(newQuote); _orgContext.Attach(account); _orgContext.AddLink( newQuote, new Relationship("quote_customer_accounts"), account); Console.Write("Instantiating a quote, "); // Add a quote product to this quote. var quoteProduct = new QuoteDetail() { ProductId = newProduct.ToEntityReference(), Quantity = 1, QuoteId = newQuote.ToEntityReference(), UoMId = newProduct.DefaultUoMId, Id = Guid.NewGuid() }; _quoteDetailId = quoteProduct.Id; _orgContext.AddObject(quoteProduct); Console.WriteLine("and adding product to quote."); // Create a sales opportunity with Contoso. var oppty = new Opportunity() { Name = "Interested in Widget A", EstimatedCloseDate = DateTime.Now.AddDays(30.0), EstimatedValue = new Money(decimal.Parse("300000.00")), CloseProbability = 25, // 25% probability of closing this deal IsRevenueSystemCalculated = false, // user-calculated revenue OpportunityRatingCode = new OptionSetValue(2), // warm CustomerId = account.ToEntityReference(), Id = Guid.NewGuid() }; _opportunityId = oppty.Id; _orgContext.AddObject(oppty); Console.Write("Instantiating opportunity, "); //_orgContext.AddLink( // oppty, // new Relationship("opportunity_customer_accounts"), // account); SaveChangesHelper(priceList, newQuote, newProduct, priceLevelProduct, quoteProduct, oppty, account); Console.WriteLine("and creating all records in CRM."); // Associate quote to contact, which adds the Contact record in the // "Other Contacts" section of a Quote record. _orgContext.Attach(contact); _orgContext.Attach(newQuote); _orgContext.AddLink( contact, new Relationship("contactquotes_association"), newQuote); SaveChangesHelper(contact, newQuote); Console.WriteLine("Associating contact and quote."); // Create a case for Mary Kay Andersen. var serviceRequest = new Incident() { Title = "Problem with Widget B", PriorityCode = new OptionSetValue(1), // 1 = High CaseOriginCode = new OptionSetValue(1), // 1 = Phone CaseTypeCode = new OptionSetValue(2), // 2 = Problem SubjectId = new EntityReference( Subject.EntityLogicalName, _orgContext.CreateQuery<Subject>() .First().Id), // use the default subject Description = "Customer can't switch the product on.", FollowupBy = DateTime.Now.AddHours(3.0), // follow-up in 3 hours CustomerId = contact.ToEntityReference(), Id = Guid.NewGuid() }; _incidentId = serviceRequest.Id; _orgContext.AddObject(serviceRequest); _orgContext.Attach(contact); _orgContext.AddLink( serviceRequest, new Relationship("incident_customer_contacts"), contact); SaveChangesHelper(serviceRequest, contact); Console.WriteLine("Creating service case for contact."); // Deactivate the Mary Kay Andersen contact record. SetStateRequest setInactiveRequest = new SetStateRequest { EntityMoniker = contact.ToEntityReference(), State = new OptionSetValue((int)ContactState.Inactive), Status = new OptionSetValue(2) }; _orgContext.Execute(setInactiveRequest); Console.WriteLine("Deactivating the contact record."); DeleteRequiredRecords(promptforDelete); } //</snippetBasicContextExamples1> } // 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; } }