private void ImportStub(DynamicsCrmConnection dynamicsCrmConnection, DatabaseStub stub, DatabaseWebCampaign webCampaign, DatabaseWebCampaign.CollectTypeEnum collectType) { List <string> keyFields; if (webCampaign == null) { keyFields = new List <string>(); } else { keyFields = webCampaign.KeyFields; } List <DatabaseStubElement> contentList = Utilities.LinqExtension.DistinctBy(stub.Contents, content => content.Key).ToList(); contentList = contentList.Where(content => content.Key != null).ToList(); Dictionary <string, string> allContent = contentList.ToDictionary(content => content.Key, content => content.Value); Dictionary <string, string> keyContent = allContent.Where(content => keyFields.Contains(content.Key)).ToDictionary(content => content.Key, content => content.Value); Contact contact = null; int?numberOfMatchingContacts = null; if (keyContent.Any()) { List <Contact> matchingContacts = Contact.ReadFromFetchXml(dynamicsCrmConnection, new List <string> { "contactid", "ownerid" }, keyContent); numberOfMatchingContacts = matchingContacts.Count; if (numberOfMatchingContacts == 1) { contact = matchingContacts.Single(); } } Lead lead = Lead.Create(dynamicsCrmConnection, allContent); Guid?owner = null; if (webCampaign != null) { lead.campaign = webCampaign.FormId; owner = webCampaign.FormOwner; } if (contact != null && owner.HasValue == false) { if (owner.HasValue == false) { owner = contact.owner; } } switch (collectType) { case DatabaseWebCampaign.CollectTypeEnum.LeadOgContactHvisContactIkkeFindes: if (contact == null && numberOfMatchingContacts == 0) { contact = Contact.Create(dynamicsCrmConnection, allContent); contact.InsertWithoutRead(); if (owner.HasValue) { contact.owner = owner; contact.Assign(); } } break; } lead.subject = _databaseImportFromStub.Name; if (contact != null) { lead.parentcontact = contact.Id; } lead.InsertWithoutRead(); if (owner.HasValue) { lead.owner = owner; lead.Assign(); } if (webCampaign != null && webCampaign.mailrelaygroupid.HasValue) { AddMailrelaySubscriberFromLead.CreateIfValid(Connection, lead.Id, $"Auto subscribe from {_databaseImportFromStub.Name}", _databaseImportFromStub.urlLoginName, lead.emailaddress1, webCampaign); } }