protected override bool AddUsersToRoles(List <CRMUser> users, List <CRMRole> roles) { const string AddUsersToRolesKey = "addUsersToRoles"; ConditionalLog.Info("AddUsersToRoles(...). Started.", this, TimerAction.Start, AddUsersToRolesKey); var result = true; foreach (var role in roles) { foreach (var user in users) { var request = new AddMemberListRequest(); request.EntityId = user.ID; request.ListId = role.ID; try { this.CrmService.Execute(request); ConditionalLog.Info(String.Format("AddUsersToRoles(...). User {0} has been added to the {1} role.", user.Name, role.Name), this, TimerAction.Tick, AddUsersToRolesKey); this.CacheService.MembersCache.Remove(role.Name); this.CacheService.MemberOfCache.Remove(user.Name); } catch (Exception e) { ConditionalLog.Error(String.Format("Couldn't add contact {0} to marketing list {1} in CRM.", user.Name, role.Name), e, this); result = false; } } } ConditionalLog.Info("AddUsersToRoles(...). Finished.", this, TimerAction.Stop, AddUsersToRolesKey); return(result); }
private void AddListMember(Guid memberId, Guid listId) { var remove = new AddMemberListRequest { EntityId = memberId, ListId = listId }; XrmService.Execute(remove); }
/// <summary> /// Add single member to marketing list. /// Please note that you can not perform this action if marketing list is <c>locked</c>, please check <c>lockstatus</c> property. /// You can also call <see cref="Unlock(Guid)"/> method. /// <para> /// For more information look at https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.addmemberlistrequest(v=crm.7).aspx /// </para> /// </summary> /// <param name="listId">Marketing List Id</param> /// <param name="memberId"> /// Entity Id. /// Please note that you can add member to list with same type (<c>Account</c>, <c>Contact</c> or <c>Lead</c>), before add member check your marketing list member type /// </param> /// <returns> /// Returns created memberlist Id in <see cref="AddMemberListResponse.Id"/> property. /// </returns> public AddMemberListResponse AddMember(Guid listId, Guid memberId) { ExceptionThrow.IfGuidEmpty(listId, "listId"); ExceptionThrow.IfGuidEmpty(memberId, "memberId"); AddMemberListRequest request = new AddMemberListRequest() { ListId = listId, EntityId = memberId }; return((AddMemberListResponse)this.OrganizationService.Execute(request)); }
public void When_a_member_is_added_to_a_non_existing_list_exception_is_thrown() { var ctx = new XrmFakedContext(); var service = ctx.GetOrganizationService(); AddMemberListRequest marketingList = new AddMemberListRequest(); // Set the properties of the request object. marketingList.EntityId = Guid.NewGuid(); marketingList.ListId = Guid.NewGuid(); // Execute the request. Assert.Throws <FaultException <OrganizationServiceFault> >(() => service.Execute(marketingList)); }
public void When_a_request_is_called_with_an_empty_entityid_parameter_exception_is_thrown() { var ctx = new XrmFakedContext(); var service = ctx.GetOrganizationService(); AddMemberListRequest marketingList = new AddMemberListRequest(); // Set the properties of the request object. marketingList.EntityId = Guid.Empty; marketingList.ListId = Guid.NewGuid(); // Execute the request. Assert.Throws <FaultException <OrganizationServiceFault> >(() => service.Execute(marketingList)); }
public void AddMemberToList(Guid listId, object [] currentRecord) { string joinKey = JoinResolver.BuildExistingCheckKey(currentRecord, this.Configuration.ListMemberMapping, this.dataObject.Metadata); foreach (Guid memberId in this.existingMembers[joinKey]) { AddMemberListRequest addMemberListRequest = new AddMemberListRequest(); addMemberListRequest.ListId = listId; addMemberListRequest.EntityId = memberId; this.service.Execute(addMemberListRequest); } }
public void When_a_member_is_added_to_an_existing_list_member_is_added_successfully_lead() { var ctx = new XrmFakedContext(); var service = ctx.GetOrganizationService(); var list = new Crm.List() { Id = Guid.NewGuid(), ListName = "Some list", CreatedFromCode = new OptionSetValue((int)ListCreatedFromCode.Lead) }; var lead = new Lead() { Id = Guid.NewGuid() }; ctx.Initialize(new List <Entity> { list, lead }); AddMemberListRequest request = new AddMemberListRequest(); request.EntityId = lead.Id; request.ListId = list.ToEntityReference().Id; service.Execute(request); using (var context = new XrmServiceContext(service)) { var member = (from lm in context.CreateQuery <ListMember>() join l in context.CreateQuery <Crm.List>() on lm.ListId.Id equals l.ListId.Value join le in context.CreateQuery <Lead>() on lm.EntityId.Id equals le.LeadId.Value where lm.EntityId.Id == lead.Id where lm.ListId.Id == list.Id select lm ).FirstOrDefault(); Assert.NotNull(member); } }
protected override void Execute(CodeActivityContext executionContext) { #region "Load CRM Service from context" Common objCommon = new Common(executionContext); objCommon.tracingService.Trace("Load CRM Service from context --- OK"); #endregion #region "Read Parameters" EntityReference marketingList = this.MarketingList.Get(executionContext); objCommon.tracingService.Trace(String.Format("marketingList: {0} ", marketingList.Id.ToString())); EntityReference account = this.account.Get(executionContext); EntityReference contact = this.contact.Get(executionContext); EntityReference lead = this.lead.Get(executionContext); #endregion Guid idToAdd = Guid.Empty; if (account != null) { idToAdd = account.Id; } else if (contact != null) { idToAdd = contact.Id; } else if (lead != null) { idToAdd = lead.Id; } objCommon.tracingService.Trace(String.Format("idToAdd: {0} ", idToAdd.ToString())); AddMemberListRequest addRequest = new AddMemberListRequest(); addRequest.ListId = marketingList.Id; addRequest.EntityId = idToAdd; AddMemberListResponse addResponse = (AddMemberListResponse)objCommon.service.Execute(addRequest); }
public void When_a_member_is_added_to_an_existing_list_without_membercode_exception_is_thrown() { var ctx = new XrmFakedContext(); var service = ctx.GetOrganizationService(); var list = new Crm.List() { Id = Guid.NewGuid(), ListName = "Some list" }; ctx.Initialize(new List <Entity> { list }); AddMemberListRequest marketingList = new AddMemberListRequest(); marketingList.EntityId = Guid.NewGuid(); marketingList.ListId = list.ToEntityReference().Id; Assert.Throws <FaultException <OrganizationServiceFault> >(() => service.Execute(marketingList)); }
public void When_a_non_existing_member_is_added_to_an_existing_list_exception_is_thrown() { var ctx = new XrmFakedContext(); var service = ctx.GetOrganizationService(); var list = new Crm.List() { Id = Guid.NewGuid(), ListName = "Some list", CreatedFromCode = new OptionSetValue((int)ListCreatedFromCode.Account) }; ctx.Initialize(new List <Entity> { list }); AddMemberListRequest request = new AddMemberListRequest(); request.EntityId = Guid.NewGuid(); request.ListId = list.ToEntityReference().Id; Assert.Throws <FaultException <OrganizationServiceFault> >(() => service.Execute(request)); }
public void AddSubscribers(string ListId, List <Entities.Subscriber> subscribers) { try { foreach (Entities.Subscriber subscriber in subscribers) { Contact contact = (Contact)context.ContactSet.Where(x => x.EMailAddress1.Equals(subscriber.E_mail)).FirstOrDefault(); Guid listGuid = new Guid(ListId); if (contact == null) { Guid contactGuid = context.Create(new Contact() { EMailAddress1 = subscriber.E_mail, FirstName = subscriber.Name }); var member = new AddMemberListRequest() { EntityId = contactGuid, ListId = listGuid }; context.Execute(member); } else { var member = new AddMemberListRequest() { EntityId = contact.Id, ListId = listGuid }; context.Execute(member); } } context.SaveChanges(); } catch (Exception e) { throw new Exception("Get subscribers CRM (" + e.Message.ToString() + ")"); } }
/// <summary> /// Imports the specified profile. /// </summary> /// <param name="profile">The profile.</param> /// <param name="transportReportFileName">Name of the transport report file.</param> private void Import(NtoNAssociationsTransportProfile profile, string transportReportFileName) { int totalTreatedRecords = 0; int totalImportFailures = 0; int totalImportSuccess = 0; int ReconnectionRetryCount = 5; try { NtoNTransportReport report = new NtoNTransportReport(transportReportFileName); //Get Transport Report if (File.Exists(transportReportFileName)) { report = ReadTransportReport(transportReportFileName); } MSCRMConnection connection = profile.getTargetConneciton(); ; _serviceProxy = cm.connect(connection); IOrganizationService service = (IOrganizationService)_serviceProxy; LogManager.WriteLog("Start importing data in " + connection.ConnectionName); //Mesure import time DateTime importStartDT = DateTime.Now; //es = ReadEnvStructure(profile.SourceConnectionName); foreach (SelectedNtoNRelationship ee in profile.SelectedNtoNRelationships) { //Check if there are any records to import if (ee.ExportedRecords == 0) { continue; } //Mesure import time DateTime entityImportStartDT = DateTime.Now; string entityFolderPath = Folder + "\\" + profile.ProfileName + "\\Data\\" + ee.RelationshipSchemaName; string[] filePaths = Directory.GetFiles(entityFolderPath, "*.xml"); LogManager.WriteLog("Importing " + ee.RelationshipSchemaName + " records."); int treatedRecordsForEntity = 0; int importedRecordsForEntity = 0; int importFailuresForEntity = 0; foreach (string filePath in filePaths) { List<Type> knownTypes = new List<Type>(); knownTypes.Add(typeof(Entity)); XmlDictionaryReaderQuotas XRQ = new XmlDictionaryReaderQuotas(); XRQ.MaxStringContentLength = int.MaxValue; using(FileStream fs = new FileStream(filePath, FileMode.Open)) using (XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(fs, XRQ)) { DataContractSerializer ser = new DataContractSerializer(typeof(EntityCollection), knownTypes); EntityCollection fromDisk = (EntityCollection)ser.ReadObject(reader, true); foreach (Entity en in fromDisk.Entities) { EntityReference relatedEntity1 = new EntityReference(); EntityReference relatedEntity2 = new EntityReference(); try { Guid relatedEntity1Id = getRelatedEntityGuid(en[ee.Entity1IntersectAttribute]); Guid relatedEntity2Id = getRelatedEntityGuid(en[ee.Entity2IntersectAttribute]); relatedEntity1 = new EntityReference { LogicalName = ee.Entity1LogicalName, Id = relatedEntity1Id }; relatedEntity2 = new EntityReference { LogicalName = ee.Entity2LogicalName, Id = relatedEntity2Id }; if (!AlreadyAssociated(_serviceProxy, ee, relatedEntity1Id, relatedEntity2Id)) { if (ee.IntersectEntityName == "listmember") { Guid entity_id = Guid.Empty; Guid list_id = Guid.Empty; if (ee.Entity1LogicalName == "list") { entity_id = relatedEntity2Id; list_id = relatedEntity1Id; } else { entity_id = relatedEntity1Id; list_id = relatedEntity2Id; } AddMemberListRequest request = new AddMemberListRequest(); request.EntityId = entity_id; request.ListId = list_id; AddMemberListResponse response = (AddMemberListResponse)service.Execute(request); } else if (ee.IntersectEntityName == "campaignitem") { Guid entity_id = Guid.Empty; Guid list_id = Guid.Empty; string EntityName = ""; if (ee.Entity1LogicalName == "campaign") { entity_id = relatedEntity2Id; list_id = relatedEntity1Id; EntityName = (string)en["entitytype"]; relatedEntity2.LogicalName = EntityName; } else { entity_id = relatedEntity1Id; list_id = relatedEntity2Id; EntityName = (string)en["entitytype"]; relatedEntity1.LogicalName = EntityName; } AddItemCampaignRequest req = new AddItemCampaignRequest(); req.CampaignId = relatedEntity1Id; req.EntityName = EntityName; req.EntityId = entity_id; AddItemCampaignResponse resp = (AddItemCampaignResponse)service.Execute(req); } else if (ee.IntersectEntityName == "campaignactivityitem") { Guid entity_id = Guid.Empty; Guid list_id = Guid.Empty; string EntityName = ""; if (ee.Entity1LogicalName == "campaignactivity") { entity_id = relatedEntity2Id; list_id = relatedEntity1Id; EntityName = (string)en["itemobjecttypecode"]; relatedEntity2.LogicalName = EntityName; } else { entity_id = relatedEntity1Id; list_id = relatedEntity2Id; EntityName = (string)en["itemobjecttypecode"]; relatedEntity1.LogicalName = EntityName; } AddItemCampaignActivityRequest req = new AddItemCampaignActivityRequest(); req.CampaignActivityId = relatedEntity1Id; req.EntityName = EntityName; req.ItemId = entity_id; AddItemCampaignActivityResponse resp = (AddItemCampaignActivityResponse)service.Execute(req); } else { EntityReferenceCollection relatedEntities = new EntityReferenceCollection(); relatedEntities.Add(relatedEntity2); Relationship relationship = new Relationship(ee.RelationshipSchemaName); relationship.PrimaryEntityRole = EntityRole.Referencing; service.Associate(relatedEntity1.LogicalName, relatedEntity1.Id, relationship, relatedEntities); } } importedRecordsForEntity++; totalImportSuccess++; } catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex) { totalImportFailures++; importFailuresForEntity++; NtoNRelationshipsImportFailure failure = new NtoNRelationshipsImportFailure { CreatedOn = DateTime.Now.ToString(), NtoNRelationshipName = ee.RelationshipSchemaName, Reason = ex.Detail.Message, UrlEntity1 = profile.getSourceConneciton().ServerAddress + "main.aspx?pagetype=entityrecord&etn=" + relatedEntity1.LogicalName + "&id=" + relatedEntity1.Id.ToString(), UrlEntity2 = profile.getSourceConneciton().ServerAddress + "main.aspx?pagetype=entityrecord&etn=" + relatedEntity2.LogicalName + "&id=" + relatedEntity2.Id.ToString() }; report.TotalImportFailures += 1; //Insert the Failure line in the Failures Report WriteNewImportFailureLine(failure, importFailuresReportFileName); } catch (Exception ex) { //Check if the authentification session is expired if (ex.InnerException != null && ex.InnerException.Message.StartsWith("ID3242")) { LogManager.WriteLog("Error:The CRM authentication session expired. Reconnection attempt n° " + ReconnectionRetryCount); ReconnectionRetryCount--; //On 5 failed reconnections exit if (ReconnectionRetryCount == 0) throw; _serviceProxy = cm.connect(connection); service = (IOrganizationService)_serviceProxy; LogManager.WriteLog("Error:The CRM authentication session expired."); totalImportFailures++; importFailuresForEntity++; NtoNRelationshipsImportFailure failure = new NtoNRelationshipsImportFailure { CreatedOn = DateTime.Now.ToString(), NtoNRelationshipName = ee.RelationshipSchemaName, Reason = ex.InnerException.Message, UrlEntity1 = profile.getSourceConneciton().ServerAddress + "main.aspx?pagetype=entityrecord&etn=" + relatedEntity1.LogicalName + "&id=" + relatedEntity1.Id.ToString(), UrlEntity2 = profile.getSourceConneciton().ServerAddress + "main.aspx?pagetype=entityrecord&etn=" + relatedEntity2.LogicalName + "&id=" + relatedEntity2.Id.ToString() }; report.TotalImportFailures += 1; //Insert the Failure line in the Failures Report WriteNewImportFailureLine(failure, importFailuresReportFileName); } else { throw; } } totalTreatedRecords++; treatedRecordsForEntity++; updateTransportReport(report, ee, importedRecordsForEntity, importFailuresForEntity, entityImportStartDT); } } } LogManager.WriteLog("Treated " + treatedRecordsForEntity + " " + ee.RelationshipSchemaName + " records with " + importedRecordsForEntity + " successfully imported records and " + importFailuresForEntity + " failures."); } TimeSpan importTimeSpan = DateTime.Now - importStartDT; LogManager.WriteLog("Import finished for " + connection.ConnectionName + ". Treated " + totalTreatedRecords + " records in " + importTimeSpan.ToString().Substring(0, 10) + ". Successfuly imported " + totalImportSuccess + " records and " + totalImportFailures + " failures."); WriteTransportReport(report, transportReportFileName); } catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex) { LogManager.WriteLog("Error:" + ex.Detail.Message + "\n" + ex.Detail.TraceText); } catch (Exception ex) { if (ex.InnerException != null) LogManager.WriteLog("Error:" + ex.Message + "\n" + ex.InnerException.Message); else { LogManager.WriteLog("Error:" + ex.Message); } } }
[STAThread] // Required to support the interactive login experience static void Main(string[] args) { CrmServiceClient service = null; try { service = SampleHelpers.Connect("Connect"); if (service.IsReady) { // Create any entity records that the demonstration code requires SetUpSample(service); #region Demonstrate var newList = new List() { ListName = "TestList", CreatedFromCode = new OptionSetValue((int)ListCreatedFromCode.Account) }; _newListId = service.Create(newList); for (int j = 0; j < 5; j++) { var addMemberListRequest = new AddMemberListRequest(); addMemberListRequest.EntityId = _accountIdArray[j]; addMemberListRequest.ListId = _newListId; var addMemberListResponse = service.Execute(addMemberListRequest) as AddMemberListResponse; } Guid BOId = CreateAndRetrieveQuickCampaignForMarketingList(service, _templateLetterActivity, _newListId, PropagationOwnershipOptions.ListMemberOwner, true); #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(service, _templateEmailActivity, query, PropagationOwnershipOptions.ListMemberOwner, true); #endregion Demonstrate #region Clean up CleanUpSample(service); #endregion Clean up } else { const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Common Data Service"; if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR)) { Console.WriteLine("Check the connection string values in cds/App.config."); throw new Exception(service.LastCrmError); } else { throw service.LastCrmException; } } } catch (Exception ex) { SampleHelpers.HandleException(ex); } finally { if (service != null) { service.Dispose(); } Console.WriteLine("Press <Enter> to exit."); Console.ReadLine(); } }
public void Execute(IServiceProvider serviceProvider) { IPluginExecutionContext context = (IPluginExecutionContext) serviceProvider.GetService(typeof(IPluginExecutionContext)); IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory)); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); try { if (context.InputParameters.Contains("WebResource")) { EntityReference webResourceRef = (EntityReference)context.InputParameters["WebResource"]; ImportAllSettings settings = null; if (context.InputParameters.Contains("Settings")) { string settingsData = (string)context.InputParameters["Settings"]; if (!String.IsNullOrEmpty(settingsData)) { settings = Common.DeSerializeSettings(settingsData); } } Entity webResource = service.Retrieve(webResourceRef.LogicalName, webResourceRef.Id, new Microsoft.Xrm.Sdk.Query.ColumnSet(true)); if (webResource.Contains("content") && webResource["content"] != null) { var dataSet = Common.ResourceFromString((string)webResource["description"]); string content = Common.GetAttribute <string>(webResource, null, "content"); string fetchXml; string data; Common.ParseContent(content, out fetchXml, out data); List <Entity> entities = Common.DeSerializeEntityList(data); if (entities != null) { string lookupField = null; if (!String.IsNullOrWhiteSpace(dataSet.lookupfield)) { lookupField = dataSet.lookupfield; } foreach (var e in entities) { var metadata = ReferenceResolution.GetMetadata(context, service, e.LogicalName); if (lookupField == null) { lookupField = metadata.PrimaryIdAttribute; } ReferenceResolution.ResolveReferences(context, service, e); if (metadata.IsIntersect == null || !metadata.IsIntersect.Value) { if (lookupField != metadata.PrimaryIdAttribute && !e.Contains(lookupField)) { throw new InvalidPluginExecutionException("Lookup error: The entity being imported does not have '" + lookupField + "' attribute"); } QueryExpression qe = new QueryExpression(e.LogicalName); qe.Criteria.AddCondition(new ConditionExpression(lookupField, ConditionOperator.Equal, lookupField == metadata.PrimaryIdAttribute ? e.Id : e[lookupField])); var existing = service.RetrieveMultiple(qe).Entities.FirstOrDefault(); if (existing != null) { if (!dataSet.createonly || settings != null && settings.alwaysUpdate) { e.Id = existing.Id; service.Update(e); } } else { service.Create(e); } } else { if (e.LogicalName == "listmember") { if (e.Contains("entityid") && e.Contains("listid")) { QueryExpression qe = new QueryExpression("listmember"); qe.Criteria.AddCondition(new ConditionExpression("entityid", ConditionOperator.Equal, ((EntityReference)e["entityid"]).Id)); qe.Criteria.AddCondition(new ConditionExpression("listid", ConditionOperator.Equal, ((EntityReference)e["listid"]).Id)); bool exists = service.RetrieveMultiple(qe).Entities.FirstOrDefault() != null; if (!exists) { AddMemberListRequest amlr = new AddMemberListRequest(); amlr.EntityId = ((EntityReference)e["entityid"]).Id; amlr.ListId = ((EntityReference)e["listid"]).Id; service.Execute(amlr); } } } else { foreach (var r in metadata.ManyToManyRelationships) { if (r.IntersectEntityName == e.LogicalName) { if (e.Contains(r.Entity1IntersectAttribute) && e.Contains(r.Entity2IntersectAttribute) ) { QueryExpression qe = new QueryExpression(r.IntersectEntityName); qe.Criteria.AddCondition(new ConditionExpression(r.Entity1IntersectAttribute, ConditionOperator.Equal, (Guid)e[r.Entity1IntersectAttribute])); qe.Criteria.AddCondition(new ConditionExpression(r.Entity2IntersectAttribute, ConditionOperator.Equal, (Guid)e[r.Entity2IntersectAttribute])); bool exists = service.RetrieveMultiple(qe).Entities.FirstOrDefault() != null; if (!exists && Common.RecordExists(service, r.Entity1LogicalName, r.Entity1IntersectAttribute, (Guid)e[r.Entity1IntersectAttribute]) && Common.RecordExists(service, r.Entity2LogicalName, r.Entity2IntersectAttribute, (Guid)e[r.Entity2IntersectAttribute]) ) { Relationship rs = new Relationship(r.SchemaName); EntityReferenceCollection collection = new EntityReferenceCollection(); collection.Add(new EntityReference(r.Entity2IntersectAttribute) { Id = (Guid)e[r.Entity2IntersectAttribute] }); service.Associate(r.Entity1LogicalName, (Guid)e[r.Entity1IntersectAttribute], rs, collection); } break; } } } } } } } var updatedResource = new Entity(webResource.LogicalName); updatedResource.Id = webResource.Id; dataSet.appliedon = Common.CurrentTime(); dataSet.appliedin = context.OrganizationId.ToString().Replace("{", "").Replace("}", ""); updatedResource["description"] = Common.ResourceToString(dataSet); service.Update(updatedResource); } } } catch (Exception ex) { throw new InvalidPluginExecutionException(ex.Message); } }
/// <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> /// Executes the workflow activity. /// </summary> /// <param name="executionContext">The execution context.</param> protected override void Execute(CodeActivityContext executionContext) { // Create the tracing service ITracingService tracingService = executionContext.GetExtension <ITracingService>(); if (tracingService == null) { throw new InvalidPluginExecutionException("Failed to retrieve tracing service."); } tracingService.Trace("Entered WebFormFill.Execute(), Activity Instance Id: {0}, Workflow Instance Id: {1}", executionContext.ActivityInstanceId, executionContext.WorkflowInstanceId); // Create the context IWorkflowContext context = executionContext.GetExtension <IWorkflowContext>(); if (context == null) { throw new InvalidPluginExecutionException("Failed to retrieve workflow context."); } tracingService.Trace("WebFormFill.Execute(), Correlation Id: {0}, Initiating User: {1}", context.CorrelationId, context.InitiatingUserId); ITracingService t = tracingService; IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>(); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); try { // TODO: Implement your custom Workflow business logic. #region 1. Get the Web Form Fill from the workflow context. t.Trace("1. Get the Form Fill from the workflow context."); cldrkt_webformfill webFormFill = (cldrkt_webformfill)service.Retrieve( context.PrimaryEntityName, context.PrimaryEntityId, new ColumnSet { AllColumns = true }); #endregion 1. Get the Web Form Fill from the workflow context. #region 2. Get the transaction owner and response email sender. QueryExpression userQuery = new QueryExpression { EntityName = SystemUser.EntityLogicalName, ColumnSet = new ColumnSet { AllColumns = true }, Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "domainname", Operator = ConditionOperator.Equal, Values = { "*****@*****.**"}, } } } }; t.Trace("2.1 Get the system user who will send the email."); SystemUser user = (SystemUser)service.RetrieveMultiple(userQuery).Entities.FirstOrDefault(); t.Trace("2.2 The sender is: " + user.FullName.ToString()); #endregion 2. Get the transaction owner and response email sender. #region 3. Look up the Contact from the email address, and create a new Contact if it doesn't already exist. t.Trace("3. Find or create the Contact from the email address." + webFormFill.cldrkt_Email); Contact contact = new Contact { EMailAddress1 = webFormFill.cldrkt_Email, FirstName = webFormFill.cldrkt_FirstName, Id = Guid.NewGuid(), LastName = webFormFill.cldrkt_LastName, Telephone1 = webFormFill.cldrkt_BusinessPhone, }; t.Trace("3.1 Look up the Contact using the email address entered: " + webFormFill.cldrkt_Email.ToString()); QueryExpression contactsQuery = new QueryExpression { EntityName = Contact.EntityLogicalName, ColumnSet = new ColumnSet { AllColumns = true }, Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "emailaddress1", Operator = ConditionOperator.Equal, Values = { contact.EMailAddress1}, } } } }; Contact c = (Contact)service.RetrieveMultiple(contactsQuery).Entities.FirstOrDefault(); if (c != null) { contact.Id = c.Id; // Will overwrite existing Contact data with entered data. contact.ParentCustomerId = c.ParentCustomerId; // So it will be there for the Account lookup. t.Trace("3.2.1 The existing contact is: " + contact.Id.ToString() + " " + contact.EMailAddress1); } else { t.Trace("3.3.1 Create a new contact."); contact.Id = service.Create(contact); t.Trace("3.3.2 The new contact is: " + contact.Id.ToString() + " " + contact.EMailAddress1); } service.Update(contact); #endregion 3. Look up the Contact from the email address, and create a new Contact if it doesn't already exist. #region 4. Look up or create the Account and map this Contact to it. t.Trace("4. Look up or create the Account and map this Contact to it."); //t.Trace("4. Contact is " + contact.FullName); //t.Trace("4. Contact.Id is " + contact.Id); //t.Trace("4. contact.ParentCustomerId is " + contact.ParentCustomerId.ToString()); Account account = new Account { Name = webFormFill.cldrkt_Organization, }; // Look up or create the parent Account. if (contact.ParentCustomerId != null) { t.Trace("4.1 Build the parent account query."); // Look up the parent account. QueryExpression parentAccountQuery = new QueryExpression { EntityName = Account.EntityLogicalName, ColumnSet = new ColumnSet { AllColumns = true }, Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "accountid", Operator = ConditionOperator.Equal, Values = { contact.ParentCustomerId.Id,}, } }, }, }; t.Trace("4.2 Look up Account a."); Account a = (Account)service.RetrieveMultiple(parentAccountQuery).Entities.FirstOrDefault(); t.Trace("4.3 If a exists, use it. Otherwise create a new Account."); if (a != null) { t.Trace("4.3.1 The Account exists."); account = a; t.Trace("4.2.2 The existing Account is " + account.Name); } else { t.Trace("4.3.2 Create a new Account."); account.Id = a.Id; t.Trace("4.3.1 The new Account is " + account.Id.ToString()); } } else { t.Trace("4.4 Create a new Account."); account.Id = service.Create(account); }; // Map the contact to the account. account.PrimaryContactId = new EntityReference { Id = contact.Id, LogicalName = Contact.EntityLogicalName, }; service.Update(account); // Map the account to the contact. contact.ParentCustomerId = new EntityReference { Id = account.Id, LogicalName = Account.EntityLogicalName, }; service.Update(contact); #endregion 4. Look up or create the Account and map this Contact to it. #region 5. Get the Campaign from the Campaign Activity ID and log a Campaign Response. t.Trace("5. Get the Campaign Activity, if any..."); CampaignActivity campaignActivity = new CampaignActivity(); CampaignResponse campaignResponse = new CampaignResponse(); Guid campaignActivityId = Guid.Empty; t.Trace("5.1 webFormFill.cldrkt_CampaignActivityID: " + webFormFill.cldrkt_CampaignActivityID); if (String.IsNullOrWhiteSpace(webFormFill.cldrkt_CampaignActivityID)) { campaignActivityId = Guid.Empty; } else { t.Trace("5.2 We have a webFormFill.cldrkt_CampaignActivityID: " + webFormFill.cldrkt_CampaignActivityID); Guid.TryParse(webFormFill.cldrkt_CampaignActivityID, out campaignActivityId); t.Trace("5.2.1 CampaignActivityID is " + campaignActivityId.ToString()); if (campaignActivityId != Guid.Empty) { t.Trace("5.2.2 Look up the Campaign Activity..."); campaignActivity = (CampaignActivity)service.Retrieve( CampaignActivity.EntityLogicalName, campaignActivityId, new ColumnSet { AllColumns = true }); t.Trace("5.2.3 campaignActivityId: " + campaignActivityId); t.Trace("5.2.4 campaignActivity.Id: " + campaignActivity.Id.ToString()); if (campaignActivity != null) // Found a Campaign Activity. { // Create a Campaign Response. t.Trace("5.3 Create a Campaign Response..."); campaignResponse.ChannelTypeCode = new OptionSetValue((int)636280001); // 636280001: Web Page Form fill campaignResponse.Customer = new ActivityParty[] { new ActivityParty { PartyId = new EntityReference(Contact.EntityLogicalName, contact.Id) } }; campaignResponse.FirstName = webFormFill.cldrkt_FirstName; campaignResponse.LastName = webFormFill.cldrkt_LastName; campaignResponse.EMailAddress = webFormFill.cldrkt_Email; campaignResponse.Telephone = webFormFill.cldrkt_BusinessPhone; campaignResponse.CompanyName = webFormFill.cldrkt_Organization; campaignResponse.PromotionCodeName = webFormFill.cldrkt_PromotionCode; campaignResponse.cldrkt_CampaignActivityId = new EntityReference { Id = campaignActivity.Id, LogicalName = CampaignActivity.EntityLogicalName, }; campaignResponse.OriginatingActivityId = new EntityReference { Id = webFormFill.Id, LogicalName = cldrkt_webformfill.EntityLogicalName, }; campaignResponse.RegardingObjectId = new EntityReference // Required, must be the parent campaign { Id = campaignActivity.RegardingObjectId.Id, LogicalName = Campaign.EntityLogicalName, }; campaignResponse.ReceivedOn = webFormFill.CreatedOn; campaignResponse.Subject = webFormFill.Subject; //TODO: Change to an available field. t.Trace("5.2.5 Create the Campaign Response."); campaignResponse.ActivityId = service.Create(campaignResponse); t.Trace("5.3.1 campaignResponse.ActivityId: " + campaignResponse.ActivityId); t.Trace("5.3.2 campaignResponse.Id: " + campaignResponse.Id.ToString()); // Update the Campaign Response. t.Trace("5.4 Update the Campaign Response."); if (campaignResponse.Id != Guid.Empty) { service.Update(campaignResponse); t.Trace("5.4.1 campaignResponse.Id = " + campaignResponse.Id.ToString()); } // Add the Campaign Activity to the Web Form Fill. t.Trace("5.5. Add the Campaign Activity to the Web Form fill"); webFormFill.cldrkt_Campaign = new EntityReference { Id = campaignActivity.RegardingObjectId.Id, LogicalName = campaignActivity.RegardingObjectId.LogicalName, }; webFormFill.cldrkt_CampaignActivity = new EntityReference { Id = campaignActivity.Id, LogicalName = campaignActivity.LogicalName, }; webFormFill.cldrkt_CampaignResponse = new EntityReference { Id = campaignResponse.Id, LogicalName = campaignResponse.LogicalName, }; t.Trace("5.6 Update the webFormFill."); service.Update(webFormFill); } } } #endregion 5. Get the Campaign from the Campaign Activity ID and log a Campaign Response. #region 6. Create a new Opportunity and map it to the Contact. t.Trace("6. Create a new Opportunity and map it to the Contact. "); string productNumber = // Defaulting to SMSP. The Product Number has to be valid. String.IsNullOrEmpty(webFormFill.cldrkt_ProductNumber) ? "SMSP-License" : webFormFill.cldrkt_ProductNumber; QueryExpression productQuery = new QueryExpression { EntityName = Product.EntityLogicalName, ColumnSet = new ColumnSet { AllColumns = true }, Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "productnumber", Operator = ConditionOperator.Equal, Values = { productNumber}, } } } }; t.Trace("6.1.1 Look up the product. "); Product product = (Product)service.RetrieveMultiple(productQuery).Entities.FirstOrDefault(); t.Trace("6.1.2 product.Id is " + product.Id.ToString() + " product.ProductId is " + product.ProductId); t.Trace("6.1.3 product.ProductId is " + product.Id.ToString() + " "); t.Trace("6.2 Create the Opportunity. "); t.Trace("6.2.0 campaignActivity.Id is " + campaignActivity.Id.ToString()); t.Trace("6.2.1 campaignActivity.RegardingObjectId.Id is " + campaignActivity.RegardingObjectId.Id.ToString()); t.Trace("6.2.2 account.Name and product.ProductNumber are " + account.Name + " " + product.ProductNumber); t.Trace("6.2.3 product.PriceLevelId is " + product.PriceLevelId.Id.ToString()); Opportunity opportunity = new Opportunity { CampaignId = campaignActivity.RegardingObjectId, cldrkt_EstimatedUsers = (int?)webFormFill.cldrkt_ProductQuantity, Name = webFormFill.Subject, // Required. cldrkt_DateofLastContact = webFormFill.CreatedOn, IsRevenueSystemCalculated = true, ParentAccountId = new EntityReference { Id = account.Id, LogicalName = Account.EntityLogicalName, }, ParentContactId = new EntityReference { Id = contact.Id, LogicalName = Contact.EntityLogicalName, }, PriceLevelId = product.PriceLevelId, // Required StepName = "1-Conversation", TransactionCurrencyId = product.TransactionCurrencyId, // Required. }; t.Trace("6.2.5 opportunity.TransactionCurrencyId is " + opportunity.TransactionCurrencyId.Name.ToString()); t.Trace("6.2.6 TransactionCurrencyId.Id is " + opportunity.TransactionCurrencyId.Id.ToString()); t.Trace("6.2.6.1 opportunity.ParentContactId.Id is " + opportunity.ParentContactId.Id.ToString()); opportunity.Id = service.Create(opportunity); service.Update(opportunity); t.Trace("6.2.7 opportunity.Id is " + opportunity.Id.ToString()); t.Trace("6.2.7.1 ShowMe price is " + Helpers.GetShowMePricePerUser((decimal)webFormFill.cldrkt_ProductQuantity)); t.Trace("6.3 Create the OpportunityProduct."); OpportunityProduct opportunityProduct = new OpportunityProduct { OpportunityId = new EntityReference { LogicalName = Opportunity.EntityLogicalName, Id = opportunity.Id, }, ProductId = new EntityReference { LogicalName = Product.EntityLogicalName, Id = product.Id, }, UoMId = new EntityReference { LogicalName = UoM.EntityLogicalName, Id = product.DefaultUoMId.Id, }, Quantity = webFormFill.cldrkt_ProductQuantity, PricePerUnit = new Money { Value = Helpers.GetShowMePricePerUser((decimal)webFormFill.cldrkt_ProductQuantity), }, IsPriceOverridden = true, }; t.Trace("6.3.1 Creating the opportunityProduct. "); opportunityProduct.Id = service.Create(opportunityProduct); t.Trace("6.3.2 opportunityProduct.Id is " + opportunityProduct.Id.ToString()); t.Trace("6.3.3 opportunityProductProductId.Id is " + opportunityProduct.ProductId.Id.ToString()); t.Trace("6.3.4 opportunityProduct.Quantity is " + opportunityProduct.Quantity); t.Trace("6.3.5 opportunityProduct.Quantity.Value is " + opportunityProduct.Quantity.Value); t.Trace("6.3.6 opportunityProduct.PricePerUnit is " + opportunityProduct.PricePerUnit); t.Trace("6.3.7 opportunityProduct.PricePerUnit.Value is " + opportunityProduct.PricePerUnit.Value); service.Update(opportunityProduct); service.Update(opportunity); #endregion 6. Create a new Opportunity and map it to the Contact. #region 7. Get the response email template. t.Trace(" 7. Get the email template from the Web Form Fill, otherwise use a default template"); QueryExpression templateQuery = new QueryExpression { EntityName = Template.EntityLogicalName, ColumnSet = new ColumnSet { AllColumns = true }, Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "title", Operator = ConditionOperator.Equal, Values = { webFormFill.cldrkt_EmailTemplateTitle}, } } } }; Template emailTemplate = new Template(); Guid defaultEmailTemplateId = Guid.Parse("d4fe12fd-72d2-e311-9e62-6c3be5be5e68"); // Default, SMSP demo request Guid emailTemplateId = new Guid(); if (String.IsNullOrEmpty(webFormFill.cldrkt_EmailTemplateTitle)) { emailTemplateId = defaultEmailTemplateId; t.Trace("7.1 No email template set from the web form."); } else { t.Trace("7.2.1 Looking up Template from webFormFill: " + webFormFill.cldrkt_EmailTemplateTitle); emailTemplate = (Template)service.RetrieveMultiple(templateQuery).Entities.FirstOrDefault(); if (emailTemplate == null) { t.Trace("Template is null"); } else { t.Trace("Template is not null."); t.Trace("Template type is: " + emailTemplate.TemplateTypeCode.ToString()); } t.Trace("7.2.1 Looked up Template using the Title. "); emailTemplateId = emailTemplate == null ? defaultEmailTemplateId : emailTemplate.Id; t.Trace("7.2.2 emailTemplateId: " + emailTemplateId.ToString()); } t.Trace("7.3.1 The email template is " + emailTemplate.Title.ToString() + " type of " + emailTemplate.TemplateTypeCode + " Id: " + emailTemplateId.ToString()); #endregion 7. Get the response email template. #region 8. Create and send the response email. t.Trace("8. Create and send the email message."); t.Trace("8. Send from: " + user.FullName.ToString()); t.Trace("8. Send to: " + contact.Id.ToString() + " using template " + emailTemplate.Title + " with Id " + emailTemplateId.ToString()); // Create an email using an Opportunity template. "To" is a Contact type. SendEmailFromTemplateRequest emailUsingTemplateReq = new SendEmailFromTemplateRequest { Target = new Email { To = new ActivityParty[] { new ActivityParty { PartyId = new EntityReference(Contact.EntityLogicalName, opportunity.ParentContactId.Id) } }, From = new ActivityParty[] { new ActivityParty { PartyId = new EntityReference(SystemUser.EntityLogicalName, user.Id) } }, Subject = "", Description = "", DirectionCode = true, }, RegardingId = opportunity.Id, // Required, and the type must match the Email Template type. RegardingType = emailTemplate.TemplateTypeCode, TemplateId = emailTemplateId, }; t.Trace("8.1 Send email to: " + opportunity.ParentContactId.Id.ToString() + " from: " + user.DomainName); t.Trace("8.1.1 Contact ID is: " + contact.Id.ToString() + ", email template is " + emailTemplate.Id.ToString() + ", opportunity is " + opportunity.Id.ToString()); t.Trace("8.1.2 email template id is: " + emailUsingTemplateReq.TemplateId.ToString()); SendEmailFromTemplateResponse email = (SendEmailFromTemplateResponse)service.Execute(emailUsingTemplateReq); t.Trace("8.2 Email sent: " + email.Id.ToString()); #endregion 8. Create and send the response email. #region 9. Add this Contact to the Marketing List, and create the list if it doesn't exist. t.Trace("9. Add this Contact to the Marketing List. " + contact.Id.ToString() + " to List " + webFormFill.cldrkt_AddToMarketingList); List staticContactList = new List { CreatedFromCode = new OptionSetValue((int)2), // Required. Account = 1, Contact = 2, Lead = 4. Id = Guid.NewGuid(), // Required. ListName = webFormFill.cldrkt_AddToMarketingList, // Required. LogicalName = List.EntityLogicalName, OwnerId = new EntityReference { // Required. Id = user.Id, LogicalName = SystemUser.EntityLogicalName, }, StatusCode = new OptionSetValue((int)0), Type = false, // Required. True = dynamic, false = static. }; QueryExpression listQuery = new QueryExpression { EntityName = List.EntityLogicalName, ColumnSet = new ColumnSet { AllColumns = true }, Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "listname", Operator = ConditionOperator.Equal, Values = { webFormFill.cldrkt_AddToMarketingList}, } } } }; t.Trace("9.1 Get this list, if it exists: " + webFormFill.cldrkt_AddToMarketingList); Entity list = service.RetrieveMultiple(listQuery).Entities.FirstOrDefault(); t.Trace("9.2 Look up the list."); if (list == null) { t.Trace("9.3.1 Create a new list: " + staticContactList.Id.ToString()); staticContactList.Id = service.Create(staticContactList); } else { t.Trace("9.3.2 Use the list we found: " + list.Id.ToString()); staticContactList.Id = list.Id; } t.Trace("9.4 Add the Contact " + contact.Id.ToString() + " to List " + staticContactList.Id.ToString()); AddMemberListRequest addMemberListRequest = new AddMemberListRequest { EntityId = contact.Id, ListId = staticContactList.Id, }; service.Execute(addMemberListRequest); #endregion 9. Add this Contact to the Marketing List, and create the list if it doesn't exist. #region 10. Update the entities we've worked on. t.Trace("10. Update the entities we've worked on. "); webFormFill.RegardingObjectId = new EntityReference { Id = contact.Id, LogicalName = Contact.EntityLogicalName, }; service.Update(webFormFill); service.Update(contact); service.Update(opportunityProduct); service.Update(opportunity); service.Update(webFormFill); #endregion 10. Update the entities we've worked on. //throw new InvalidPluginExecutionException("Finished processing the Web Form Fill update."); } catch (FaultException <OrganizationServiceFault> e) { tracingService.Trace("Exception: {0}", e.ToString()); // Handle the exception. throw; } tracingService.Trace("Exiting WebFormFill.Execute(), Correlation Id: {0}", context.CorrelationId); }
private void CreateMarketingList() { Console.WriteLine("=== Creating the Marketing List ==="); // Create the marketing list. Make it static because members are going to be // added to the list. var list = new List { CreatedFromCode = new OptionSetValue((int)ListCreatedFromCode.Contact), ListName = "Sample Contact Marketing List", Type = MarketingListType.Static }; _marketingListId = _serviceProxy.Create(list); NotifyEntityCreated(List.EntityLogicalName, _marketingListId); //<snippetDistributeCampaignFromMarketingList6> // Add a list of contacts to the marketing list. var addMemberListReq = new AddListMembersListRequest { MemberIds = new[] { _contactIdList[0], _contactIdList[2] }, ListId = _marketingListId }; _serviceProxy.Execute(addMemberListReq); Console.WriteLine(" Contacts with GUIDs \r\n\t{{{0}}}\r\n\tand {{{1}}}\r\n were added to the list.", _contactIdList[0], _contactIdList[1]); //</snippetDistributeCampaignFromMarketingList6> //<snippetDistributeCampaignFromMarketingList7> // Copy the marketing list. First create a new one, and then copy over the // members. list.ListName = list.ListName + " Copy"; _copiedMarketingListId = _serviceProxy.Create(list); var copyRequest = new CopyMembersListRequest { SourceListId = _marketingListId, TargetListId = _copiedMarketingListId }; _serviceProxy.Execute(copyRequest); //</snippetDistributeCampaignFromMarketingList7> //<snippetDistributeCampaignFromMarketingList8> // Add a single contact to the copied marketing list. var addMemberReq = new AddMemberListRequest { EntityId = _contactIdList[1], ListId = _copiedMarketingListId }; _serviceProxy.Execute(addMemberReq); Console.WriteLine(" Contact with GUID\r\n\t{{{0}}}\r\n was added to the list.", _contactIdList[1]); //</snippetDistributeCampaignFromMarketingList8> //<snippetDistributeCampaignFromMarketingList9> // Qualify the marketing list. var qualifyRequest = new QualifyMemberListRequest { OverrideorRemove = OverrideOrRemove.Override, MembersId = new[] { _contactIdList[0], _contactIdList[1] }, ListId = _copiedMarketingListId }; _serviceProxy.Execute(qualifyRequest); Console.WriteLine(" Qualified the copied marketing list so that it only\r\n includes the first two members."); //</snippetDistributeCampaignFromMarketingList9> }
/// <summary> /// Add Member List Into Marketing List(마케팅 목록) /// </summary> /// <param name="listId">Marketing List Id</param> /// <param name="ec"></param> /// <param name="continueOnError"></param> public static void AddMemberList(Guid listId, EntityCollection ec, bool continueOnError = true) { var service = Connection.Service; try { var loopCount = (ec.Entities.Count / 1000) + (ec.Entities.Count % 1000 != 0 ? 1 : 0); for (var i = 0; i < loopCount; i++) { var multipleRequest = new ExecuteMultipleRequest() { Settings = new ExecuteMultipleSettings() { ContinueOnError = continueOnError, ReturnResponses = true, }, Requests = new OrganizationRequestCollection() }; var start = (i * 1000); var end = ec.Entities.Count <= (i + 1) * 1000 ? ec.Entities.Count : (i + 1) * 1000; for (var j = start; j < end; j++) { var addMemberListRequest = new AddMemberListRequest() { EntityId = ec.Entities.ElementAt(j).Id, ListId = listId }; multipleRequest.Requests.Add(addMemberListRequest); } // Execute all the requests in the request collection using a single web method call. var multipleResponse = (ExecuteMultipleResponse)service.Execute(multipleRequest); if (!multipleResponse.Responses.Any()) { continue; } foreach (var response in multipleResponse.Responses) { if (response.Fault == null) { continue; } if (response.Fault.InnerFault != null) { //error if (!continueOnError) { throw new Exception(JsonConvert.SerializeObject(response.Fault.InnerFault) + Environment.NewLine + JsonConvert.SerializeObject(ec.Entities[(i * 1000) + response.RequestIndex])); } } else { //error if (!continueOnError) { throw new Exception(JsonConvert.SerializeObject(response.Fault) + Environment.NewLine + JsonConvert.SerializeObject(ec.Entities[(i * 1000) + response.RequestIndex])); } } } } } catch (Exception) { throw; } }
/// <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 = 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(); #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; } }
public void DeserializeData(List <Entity> entities, bool createOnly) { foreach (var e in entities) { var metadata = ReferenceResolution.GetMetadata(Service, e.LogicalName); string lookupField = null; if (lookupField == null) { lookupField = metadata.PrimaryIdAttribute; } ReferenceResolution.ResolveReferences(Service, e); if (metadata.IsIntersect == null || !metadata.IsIntersect.Value) { if (lookupField != metadata.PrimaryIdAttribute && !e.Contains(lookupField)) { throw new InvalidPluginExecutionException("Lookup error: The entity being imported does not have '" + lookupField + "' attribute"); } QueryExpression qe = new QueryExpression(e.LogicalName); qe.Criteria.AddCondition(new ConditionExpression(lookupField, ConditionOperator.Equal, lookupField == metadata.PrimaryIdAttribute ? e.Id : e[lookupField])); var existing = Service.RetrieveMultiple(qe).Entities.FirstOrDefault(); if (existing != null) { if (!createOnly) { e.Id = existing.Id; Service.Update(e); } } else { Service.Create(e); } } else { if (e.LogicalName == "listmember") { if (e.Contains("entityid") && e.Contains("listid")) { QueryExpression qe = new QueryExpression("listmember"); qe.Criteria.AddCondition(new ConditionExpression("entityid", ConditionOperator.Equal, ((EntityReference)e["entityid"]).Id)); qe.Criteria.AddCondition(new ConditionExpression("listid", ConditionOperator.Equal, ((EntityReference)e["listid"]).Id)); bool exists = Service.RetrieveMultiple(qe).Entities.FirstOrDefault() != null; if (!exists) { AddMemberListRequest amlr = new AddMemberListRequest(); amlr.EntityId = ((EntityReference)e["entityid"]).Id; amlr.ListId = ((EntityReference)e["listid"]).Id; Service.Execute(amlr); } } } else { foreach (var r in metadata.ManyToManyRelationships) { if (r.IntersectEntityName == e.LogicalName) { if (e.Contains(r.Entity1IntersectAttribute) && e.Contains(r.Entity2IntersectAttribute) ) { QueryExpression qe = new QueryExpression(r.IntersectEntityName); qe.Criteria.AddCondition(new ConditionExpression(r.Entity1IntersectAttribute, ConditionOperator.Equal, (Guid)e[r.Entity1IntersectAttribute])); qe.Criteria.AddCondition(new ConditionExpression(r.Entity2IntersectAttribute, ConditionOperator.Equal, (Guid)e[r.Entity2IntersectAttribute])); bool exists = Service.RetrieveMultiple(qe).Entities.FirstOrDefault() != null; if (!exists && Common.RecordExists(Service, r.Entity1LogicalName, r.Entity1IntersectAttribute, (Guid)e[r.Entity1IntersectAttribute]) && Common.RecordExists(Service, r.Entity2LogicalName, r.Entity2IntersectAttribute, (Guid)e[r.Entity2IntersectAttribute]) ) { Relationship rs = new Relationship(r.SchemaName); EntityReferenceCollection collection = new EntityReferenceCollection(); collection.Add(new EntityReference(r.Entity2IntersectAttribute) { Id = (Guid)e[r.Entity2IntersectAttribute] }); Service.Associate(r.Entity1LogicalName, (Guid)e[r.Entity1IntersectAttribute], rs, collection); } break; } } } } } } }