private static void LabUsingLinqCreateContacts(IOrganizationService service) { using (var orgContext = new ServiceContext(service)) { var contact = new Contact() { FirstName = "Alan", LastName = "Smith" }; orgContext.AddObject(contact); var contact2 = new Contact() { FirstName = "Ben", LastName = "Andrews" }; orgContext.AddObject(contact2); var contact3 = new Contact() { FirstName = "Colin", LastName = "Wilcox" }; orgContext.AddObject(contact3); orgContext.SaveChanges(); } }
public void Add(TimeoutData timeout) { var context = new ServiceContext(account.TableEndpoint.ToString(), account.Credentials); var hash = Hash(timeout); TimeoutDataEntity timeoutDataEntity; if (TryGetTimeoutData(context, hash, string.Empty, out timeoutDataEntity)) return; var stateAddress = Upload(timeout.State, hash); var headers = Serialize(timeout.Headers); if (!TryGetTimeoutData(context, timeout.Time.ToString(partitionKeyScope), stateAddress, out timeoutDataEntity)) context.AddObject(ServiceContext.TimeoutDataEntityTableName, new TimeoutDataEntity(timeout.Time.ToString(partitionKeyScope), stateAddress) { Destination = timeout.Destination.ToString(), SagaId = timeout.SagaId, StateAddress = stateAddress, Time = timeout.Time, CorrelationId = timeout.CorrelationId, OwningTimeoutManager = timeout.OwningTimeoutManager, Headers = headers }); if (timeout.SagaId != default(Guid) && !TryGetTimeoutData(context, timeout.SagaId.ToString(), stateAddress, out timeoutDataEntity)) context.AddObject(ServiceContext.TimeoutDataEntityTableName, new TimeoutDataEntity(timeout.SagaId.ToString(), stateAddress) { Destination = timeout.Destination.ToString(), SagaId = timeout.SagaId, StateAddress = stateAddress, Time = timeout.Time, CorrelationId = timeout.CorrelationId, OwningTimeoutManager = timeout.OwningTimeoutManager, Headers = headers }); context.AddObject(ServiceContext.TimeoutDataEntityTableName, new TimeoutDataEntity(stateAddress, string.Empty) { Destination = timeout.Destination.ToString(), SagaId = timeout.SagaId, StateAddress = stateAddress, Time = timeout.Time, CorrelationId = timeout.CorrelationId, OwningTimeoutManager = timeout.OwningTimeoutManager, Headers = headers }); context.SaveChanges(); }
public void AddObject(string entityName, object entity) { var entitySets = EdmModel.EntityContainers().SelectMany(container => container.EntitySets()); var entitySet = entitySets.First(es => es.Name == entityName.InflectTo().Pluralized); ServiceContext.AddObject(entitySet.Name, entity); }
public void AddObject(string entityName, object entity) { var entitySets = EdmModel.EntityContainers().SelectMany(container => container.EntitySets()); var entitySet = entitySets.First(es => es.Name == entityName.InflectTo().Pluralized); ServiceContext.AddObject(entitySet.Name, entity); _changeTrackingEnabled = true; if (entity != null) { ToggleChangeTracker(entity, true); } }
public void Notify(MessageContracts.StockNotifyRequestMessage request) { using (OrganizationServiceProxy proxy = CRMHelper.Connect()) { ServiceContext context = new ServiceContext(proxy); foreach(StockItemDataContract item in request.Items) { bool add = false; new_stock record = (from a in context.new_stockSet where a.new_vinnumber == item.Stock.new_vinnumber select a).FirstOrDefault(); if(record == null) { add = true; record = new new_stock(); } record.new_internalvehiclenumber = item.Stock.new_internalvehiclenumber; record.new_vinnumber = item.Stock.new_vinnumber; record.new_enginenumber = item.Stock.new_enginenumber; record.new_sapvehiclemodelcode = item.Stock.new_sapvehiclemodelcode; record.new_plantsap = item.Stock.new_plantsap; record.new_storagelocation = item.Stock.new_storagelocation; record.new_stockvalue = item.Stock.new_stockvalue; record.new_status = item.Stock.new_status; record.new_vehicleguid = item.Stock.new_vehicleguid; if(add) context.AddObject(record); else context.UpdateObject(record); } context.SaveChanges(); } }
private void ConfigureActivityFeeds() { Console.WriteLine("== Configuring Activity Feeds =="); // Get the original systemuser config in order to keep a copy for reverting // after the sample has completed. _originalSystemUserConfig = (from c in _serviceContext.msdyn_PostConfigSet where c.msdyn_EntityName == SystemUser.EntityLogicalName select new msdyn_PostConfig { msdyn_PostConfigId = c.msdyn_PostConfigId, msdyn_ConfigureWall = c.msdyn_ConfigureWall, msdyn_EntityName = c.msdyn_EntityName }).FirstOrDefault(); // Retrieve or Create an instance of msdyn_PostConfig to enable activity // feeds for leads (or make sure they are already enabled). // If a new msdyn_PostConfig record gets created, activity feeds for // systemusers will be enabled automatically. _leadConfig = (from c in _serviceContext.msdyn_PostConfigSet where c.msdyn_EntityName == Lead.EntityLogicalName select new msdyn_PostConfig { msdyn_PostConfigId = c.msdyn_PostConfigId, msdyn_EntityName = c.msdyn_EntityName, msdyn_ConfigureWall = c.msdyn_ConfigureWall }).FirstOrDefault(); if (_leadConfig == null) { // Create the configuration record for leads. _leadConfig = new msdyn_PostConfig { msdyn_EntityName = Lead.EntityLogicalName, msdyn_ConfigureWall = true }; _serviceContext.AddObject(_leadConfig); _serviceContext.SaveChanges(); Console.WriteLine( " The lead activity feed wall configuration was created."); } else { // Store the original Lead Config so that we can revert changes later. _originalLeadConfig = CloneRelevantConfiguration(_leadConfig); if (!_leadConfig.msdyn_ConfigureWall.HasValue || !_leadConfig.msdyn_ConfigureWall.Value) { _leadConfig.msdyn_ConfigureWall = true; _serviceContext.UpdateObject(_leadConfig); _serviceContext.SaveChanges(); Console.WriteLine( " The lead activity feed wall was enabled."); } } // Get the original systemuser config in order to keep a copy for reverting // after the sample has completed. _systemuserConfig = (from c in _serviceContext.msdyn_PostConfigSet where c.msdyn_EntityName == SystemUser.EntityLogicalName select new msdyn_PostConfig { msdyn_PostConfigId = c.msdyn_PostConfigId, msdyn_ConfigureWall = c.msdyn_ConfigureWall, msdyn_EntityName = c.msdyn_EntityName }).FirstOrDefault(); // Ensure that the wall for systemuser is enabled if there is already a // systemuser configuration defined. if (_systemuserConfig != null && (!_systemuserConfig.msdyn_ConfigureWall.HasValue || !_systemuserConfig.msdyn_ConfigureWall.Value)) { _systemuserConfig.msdyn_ConfigureWall = true; _serviceContext.UpdateObject(_systemuserConfig); _serviceContext.SaveChanges(); Console.WriteLine(" The systemuser activity feed wall was enabled."); } // Publish the lead and systemuser entities so that they will have record // walls on their forms. PublishSystemUserAndLead(); // Activate the auto post rule configurations. New Lead qualified should be // activated automatically when the rule is generated by CRM. var leadRules = (from r in _serviceContext.msdyn_PostRuleConfigSet where r.msdyn_RuleId == "LeadQualify.Yes.Rule" || r.msdyn_RuleId == "LeadCreate.Rule" select r).ToList(); if (leadRules.Count() != 2) { throw new InvalidSampleExecutionException( " One or both of the lead config rules do not exist. This can be fixed by deleting the lead post config."); } foreach (var configRule in leadRules) { _postRuleConfigs.Add(configRule); ActivateRuleConfig(configRule); } }
public void Notify(Toyota.Tsusho.CRM.API.MessageContracts.OrderNotifyRequestMessage request) { using (OrganizationServiceProxy proxy = CRMHelper.Connect()) { ServiceContext context = new ServiceContext(proxy); foreach (OrderItemDataContract item in request.Items) { bool add = false; Entity entity = null; Invoice record = (from a in context.InvoiceSet where a.new_saporderno == item.Invoice.new_saporderno select a).FirstOrDefault(); if (record == null) { add = true; record = new Invoice(); } //CustomerId Lookup Contact contact = (from c in context.ContactSet where c.new_customeraccountnumber == item.Invoice.CustomerId.Name select c).FirstOrDefault(); if (contact == null) throw new Exception(String.Format("No Contact could be retrieved for {0}", item.Invoice.CustomerId.Name)); //SalesOrder SalesOrder order = null; if (item.Invoice.SalesOrderId != null) { order = (from o in context.SalesOrderSet where o.new_DBMOrderNumber == item.Invoice.SalesOrderId.Name select o).FirstOrDefault(); } //SalesOffice Territory salesOffice = null; if (item.Invoice.new_salesoffice != null) { entity = (from s in context.CreateQuery("territory") where s["new_sapcode"] == item.Invoice.new_salesoffice.Name select s).FirstOrDefault(); if (entity != null) salesOffice = entity.ToEntity<Territory>(); } //Plant entity = (from p in context.CreateQuery("territory") where p["new_sapcode"] == item.Invoice.new_plant.Name select p).FirstOrDefault(); Territory plant = null; if(entity != null) plant = entity.ToEntity<Territory>(); //new_invoicetype new_invoicetype invoiceType = null; if(item.Invoice.new_invoicetype != null) { entity = (from it in context.CreateQuery("new_invoicetype") where it["new_typeidinvoice"] == item.Invoice.new_invoicetype.Name select it).FirstOrDefault(); if(entity != null) invoiceType = entity.ToEntity<new_invoicetype>(); } //Populate Order Fields record.new_saporderno = item.Invoice.new_saporderno; record.new_client = item.Invoice.new_client; if (contact != null) record.CustomerId = contact.ToEntityReference(); if (order != null) record.SalesOrderId = order.ToEntityReference(); record.new_precedingdocument = item.Invoice.new_precedingdocument; if (salesOffice != null) record.new_salesoffice = salesOffice.ToEntityReference(); if(plant != null) record.new_plant = plant.ToEntityReference(); record.new_customeradviser = item.Invoice.new_customeradviser; record.new_billingdate = item.Invoice.new_billingdate; record.new_licenseplatenumber = item.Invoice.new_licenseplatenumber; record.new_country = item.Invoice.new_country; record.new_counterreading = item.Invoice.new_counterreading; record.new_counterunit = item.Invoice.new_counterunit; record.new_orderstatus = item.Invoice.new_orderstatus; record.new_netvalue = item.Invoice.new_netvalue; record.new_vehicleguid = item.Invoice.new_vehicleguid; if (invoiceType != null) record.new_invoicetype = invoiceType.ToEntityReference(); if (add) context.AddObject(record); else context.UpdateObject(record); //Invoice Detail //We will nowdelete all line item s and readd them //if we do not do this we will get duplicate records. if (record.invoice_details != null) { foreach (InvoiceDetail detail in record.invoice_details) context.DeleteObject(detail); } foreach (InvoiceDetail lineItem in item.InvoiceDetails) { InvoiceDetail detail = new InvoiceDetail(); //new_material new_modelsalescode material = null; if(detail.new_material != null) { material = (from m in context.new_modelsalescodeSet where m.new_name == lineItem.new_material.Name select m).FirstOrDefault(); } //Plant Territory detailPlant = null; if (lineItem.new_plant != null) { entity = (from p in context.CreateQuery("territory") where p["new_sapcode"] == lineItem.new_plant.Name select p).FirstOrDefault(); if (entity != null) detailPlant = entity.ToEntity<Territory>(); } //Populate Invoice Detail detail.LineItemNumber = lineItem.LineItemNumber; detail.new_pricingreferencematerial = lineItem.new_pricingreferencematerial; detail.new_lvhierno = lineItem.new_lvhierno; if (material != null) detail.new_material = material.ToEntityReference(); detail.new_materialgroup = lineItem.new_materialgroup; detail.ProductDescription = lineItem.ProductDescription; detail.IsPriceOverridden = lineItem.IsPriceOverridden; detail.IsProductOverridden = lineItem.IsProductOverridden; detail.new_description1 = lineItem.new_description1; detail.new_itemcategory = lineItem.new_itemcategory; detail.new_deleteitem = lineItem.new_deleteitem; detail.Quantity = lineItem.Quantity; detail.new_targetqtyuom = lineItem.new_targetqtyuom; detail.new_baseunit = lineItem.new_baseunit; detail.new_targetqtyuom = lineItem.new_targetqtyuom; detail.new_division = lineItem.new_division; detail.PricePerUnit = lineItem.PricePerUnit; detail.new_salesunit = lineItem.new_salesunit; if (detailPlant != null) detail.new_plant = detailPlant.ToEntityReference(); detail.new_storagelocation = lineItem.new_storagelocation; context.AddRelatedObject(record, new Relationship("invoice_details"), detail); } } context.SaveChanges(); } }
private void UpdateSuccesfullRead(ServiceContext context, TimeoutManagerDataEntity read) { if (read == null) { read = new TimeoutManagerDataEntity(Configure.EndpointName, string.Empty){ LastSuccessfullRead = DateTime.UtcNow }; context.AddObject(ServiceContext.TimeoutManagerDataEntityTableName, read); } else { read.LastSuccessfullRead = DateTime.UtcNow; context.UpdateObject(read); } context.SaveChanges(SaveChangesOptions.ReplaceOnUpdate); }
private void MigrateExistingTimeouts(ServiceContext context) { var existing = (from c in context.TimeoutData where c.PartitionKey == "TimeoutData" select c).ToList(); foreach(var timeout in existing) { TimeoutDataEntity timeoutDataEntity; if (!TryGetTimeoutData(context, timeout.Time.ToString(partitionKeyScope), timeout.RowKey, out timeoutDataEntity)) context.AddObject(ServiceContext.TimeoutDataEntityTableName, new TimeoutDataEntity(timeout.Time.ToString(partitionKeyScope), timeout.RowKey) { Destination = timeout.Destination, SagaId = timeout.SagaId, StateAddress = timeout.RowKey, Time = timeout.Time, CorrelationId = timeout.CorrelationId, OwningTimeoutManager = timeout.OwningTimeoutManager }); if (!TryGetTimeoutData(context, timeout.SagaId.ToString(), timeout.RowKey, out timeoutDataEntity)) context.AddObject(ServiceContext.TimeoutDataEntityTableName, new TimeoutDataEntity(timeout.SagaId.ToString(), timeout.RowKey) { Destination = timeout.Destination, SagaId = timeout.SagaId, StateAddress = timeout.RowKey, Time = timeout.Time, CorrelationId = timeout.CorrelationId, OwningTimeoutManager = timeout.OwningTimeoutManager }); if (!TryGetTimeoutData(context, timeout.RowKey, string.Empty, out timeoutDataEntity)) context.AddObject(ServiceContext.TimeoutDataEntityTableName, new TimeoutDataEntity(timeout.RowKey, string.Empty) { Destination = timeout.Destination, SagaId = timeout.SagaId, StateAddress = timeout.RowKey, Time = timeout.Time, CorrelationId = timeout.CorrelationId, OwningTimeoutManager = timeout.OwningTimeoutManager }); context.DeleteObject(timeout); context.SaveChanges(); } }
/// <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 }
public void Insert(PerformanceLog item) { ServiceContext.AddObject(PerformanceLogContext.PerformanceLogTableName, item); ServiceContext.SaveChanges(); }
/// <summary> /// This method creates any entity records that this sample requires. /// Creates the email activity. /// </summary> public static void CreateRequiredRecords(CrmServiceClient service) { // Create leads for relating activity feed records to. Since there is an // active post rule config for creation of a new lead, creating the leads // should add an auto post to the record wall for each of the leads. _lead1 = new Lead { CompanyName = "A. Datum Corporation", FirstName = "Henriette", MiddleName = "Thaulow", LastName = "Andersen", Subject = "Activity Feeds Sample 1" }; _serviceContext.AddObject(_lead1); _lead2 = new Lead { CompanyName = "Adventure Works", FirstName = "Mary", MiddleName = "Kay", LastName = "Andersen", Subject = "Activity Feeds Sample 2" }; _serviceContext.AddObject(_lead2); _lead3 = new Lead { CompanyName = "Fabrikam, Inc.", FirstName = "Andrew", LastName = "Sullivan", Subject = "Activity Feeds Sample 3" }; _serviceContext.AddObject(_lead3); _serviceContext.SaveChanges(); var columnSet = new ColumnSet(true); _lead1 = (Lead)service.Retrieve( Lead.EntityLogicalName, _lead1.Id, columnSet); _lead2 = (Lead)service.Retrieve( Lead.EntityLogicalName, _lead2.Id, columnSet); _lead3 = (Lead)service.Retrieve( Lead.EntityLogicalName, _lead3.Id, columnSet); Console.WriteLine("Required records have been created."); }