public static void AssociateEntities(IOrganizationService service, string relationshipName, string entityName1, Guid entity1id, string entityName2, Guid entity2id) { if (entityName1 == "campaign" || entityName2 == "campaign") { AddItemCampaignRequest addItemCampaignRequest = new AddItemCampaignRequest(); if (entityName1 == "campaign") { addItemCampaignRequest.CampaignId = entity1id; addItemCampaignRequest.EntityName = entityName2; addItemCampaignRequest.EntityId = entity2id; } else { addItemCampaignRequest.CampaignId = entity2id; addItemCampaignRequest.EntityName = entityName1; addItemCampaignRequest.EntityId = entity1id; } service.Execute(addItemCampaignRequest); } else { AssociateEntitiesRequest associateEntitiesRequest = new AssociateEntitiesRequest(); associateEntitiesRequest.RelationshipName = relationshipName; associateEntitiesRequest.Moniker1 = new EntityReference(entityName1, entity1id); associateEntitiesRequest.Moniker2 = new EntityReference(entityName2, entity2id); service.Execute(associateEntitiesRequest); } }
public void PerformTestSetup() { MessageName = "AddItem"; var listEntity = EntityFactory.CreateMarketingList(); var campaignEntity = EntityFactory.CreateCampaign(); var targetEntity = EntityFactory.CreateCampaignActivity(campaignEntity.ToEntityReference()); var addItemCampaignRequest = new AddItemCampaignRequest { CampaignId = campaignEntity.Id, EntityId = listEntity.Id, EntityName = listEntity.LogicalName }; OrganizationService.Execute(addItemCampaignRequest); AddItemCampaignActivityRequest = new AddItemCampaignActivityRequest { CampaignActivityId = targetEntity.Id, ItemId = listEntity.Id, EntityName = listEntity.LogicalName }; }
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 campaign = this.Campaign.Get(executionContext); objCommon.tracingService.Trace(String.Format("campaign: {0} ", campaign.Id.ToString())); #endregion var request = new AddItemCampaignRequest { CampaignId = campaign.Id, EntityId = marketingList.Id, EntityName = "list", }; objCommon.service.Execute(request); }
/// <summary> /// Pazarlama Listesi(SMS)'ni ana Kmapanya'ya ve Kampanya Listesi(SMS)'ne bağlar. /// </summary> /// <param name="service"></param> /// <param name="CampaignId"></param> /// <param name="CampaignActivityId"></param> /// <param name="listId"></param> private static void CreateListCompaignActivityConnectionForSmsCampaignActivity(IOrganizationService service, Guid CampaignId, Guid CampaignActivityId, Guid listId) { #region | Members | Entity List = new Entity("list"); //MarketingList #endregion | Members | try { #region | Create List - CampaignActivity Connection | AddItemCampaignRequest req = new AddItemCampaignRequest(); req.CampaignId = CampaignId; req.EntityName = List.LogicalName; req.EntityId = listId; AddItemCampaignResponse resp = (AddItemCampaignResponse)service.Execute(req); AddItemCampaignActivityRequest req2 = new AddItemCampaignActivityRequest(); req2.CampaignActivityId = CampaignActivityId; req2.EntityName = List.LogicalName; req2.ItemId = listId; AddItemCampaignActivityResponse resp2 = (AddItemCampaignActivityResponse)service.Execute(req2); #endregion | Create List - CampaignActivity Connection | } catch (Exception ex) { throw new Exception("CreateListCompaignActivityConnectionForSmsCampaignActivity"); } }
/// <summary> /// Add an item to <c>Campaign</c>. /// <para> /// For more information look at https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.additemcampaignrequest(v=crm.8).aspx /// </para> /// </summary> /// <param name="campaignId"><c>Campaign</c> Id</param> /// <param name="itemType"><see cref="ItemTypeCode"/></param> /// <param name="itemId">Item Id</param> /// <returns> /// Returns created Item Id in <see cref="AddItemCampaignResponse.CampaignItemId"/> property. /// </returns> public AddItemCampaignResponse AddItem(Guid campaignId, ItemTypeCode itemType, Guid itemId) { ExceptionThrow.IfGuidEmpty(campaignId, "campaignId"); ExceptionThrow.IfGuidEmpty(itemId, "itemId"); AddItemCampaignRequest request = new AddItemCampaignRequest() { CampaignId = campaignId, EntityId = itemId, EntityName = itemType.Description() }; return((AddItemCampaignResponse)this.OrganizationService.Execute(request)); }
public void PerformTestSetup() { MessageName = "AddItem"; var targetEntity = EntityFactory.CreateCampaign(); var listEntity = EntityFactory.CreateMarketingList(); AddItemCampaignRequest = new AddItemCampaignRequest { CampaignId = targetEntity.Id, EntityId = listEntity.Id, EntityName = listEntity.LogicalName }; }
[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 // Create FetchXml for marketing list's query which locates accounts // in Seattle. String fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'> <entity name='account'> <attribute name='name' /> <attribute name='address1_city' /> <attribute name='primarycontactid' /> <attribute name='telephone1' /> <attribute name='accountid' /> <order attribute='name' descending='false' /> <filter type='and'> <condition attribute='address1_city' operator='eq' value='seattle' /> </filter> </entity> </fetch>"; // Create dynamic list. Set the type to true to declare a dynamic // list. List dynamicList = new List() { Type = true, ListName = "Dynamic List", CreatedFromCode = new OptionSetValue((int)ListCreatedFromCode.Account), Query = fetchXml }; _dynamicListId = service.Create(dynamicList); dynamicList.Id = _dynamicListId; Console.WriteLine("Created dynamic list."); #endregion #region Associate dynamic list to campaign // Create a campaign. var campaign = new Campaign() { Name = "Sample Campaign" }; _campaignId = service.Create(campaign); campaign.Id = _campaignId; // Add the dynamic list to the campaign. var addListToCampaignRequest = new AddItemCampaignRequest() { CampaignId = _campaignId, EntityId = _dynamicListId, EntityName = List.EntityLogicalName, }; service.Execute(addListToCampaignRequest); Console.WriteLine("Added dynamic list to the campaign."); // Create a campaign activity to distribute fax to the list members. CampaignActivity campaignActivity = new CampaignActivity() { Subject = "Sample Campaign Activity", ChannelTypeCode = new OptionSetValue((int)CampaignActivityChannelTypeCode.Fax), RegardingObjectId = campaign.ToEntityReference() }; _campaignActivityId = service.Create(campaignActivity); // Add dynamic list to campaign activity. var addListToCampaignActivityRequest = new AddItemCampaignActivityRequest() { CampaignActivityId = _campaignActivityId, ItemId = _dynamicListId, EntityName = List.EntityLogicalName }; service.Execute(addListToCampaignActivityRequest); Console.WriteLine("Added dynamic list to the campaign activity."); #endregion #region Associate static list to campaign // Copy the dynamic list to a static list. var copyRequest = new CopyDynamicListToStaticRequest() { ListId = _dynamicListId }; var copyResponse = (CopyDynamicListToStaticResponse)service.Execute(copyRequest); _staticListId = copyResponse.StaticListId; Console.WriteLine("Copied dynamic list to a static list."); // Add the static list to the campaign. var addStaticListToCampaignRequest = new AddItemCampaignRequest() { CampaignId = _campaignId, EntityId = _staticListId, EntityName = List.EntityLogicalName }; service.Execute(addStaticListToCampaignRequest); Console.WriteLine("Added static list to the campaign."); // Add the static list to the campaign activity. var addStaticListToCampaignActivityRequest = new AddItemCampaignActivityRequest() { CampaignActivityId = _campaignActivityId, ItemId = _staticListId, EntityName = List.EntityLogicalName }; service.Execute(addStaticListToCampaignActivityRequest); Console.WriteLine("Added static list to the campaign's activity."); #endregion #region Create fax for campaign's activity // Create a fax. var fax = new Fax() { Subject = "Example Fax" }; Console.WriteLine("Created fax for campaign's activity."); #endregion Create fax for campaign's activity #region Distribute fax to the marketing list // Distribute the campaign activity to the marketing lists. var distributeRequest = new DistributeCampaignActivityRequest() { CampaignActivityId = _campaignActivityId, Activity = fax, Owner = new EntityReference("systemuser", _salesManagerId), Propagate = true, SendEmail = false, PostWorkflowEvent = true }; service.Execute(distributeRequest); Console.WriteLine("Distributed fax to the marketing lists."); #endregion Distribute fax to the marketing list #region Retrieve collection of entities from marketing list // Retrieve a collection of entities that correspond // to all of the members in a marketing list // This approach of retrieving list members allows you to dynamically // retrieve the members of a list programmatically without requiring // knowledge of the member entity type. OrganizationServiceContext orgContext = new OrganizationServiceContext(service); var member = (from mb in orgContext.CreateQuery <List>() where mb.Id == _dynamicListId select mb).FirstOrDefault(); string fetchQuery = member.Query; var memberRequest = new RetrieveMultipleRequest(); FetchExpression fetch = new FetchExpression(fetchQuery); memberRequest.Query = fetch; var memberResponse = (RetrieveMultipleResponse)service.Execute(memberRequest); Console.WriteLine("Retrieved collection of entities from a marketing list."); #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(); } }
/// <summary> /// This method first connects to the Organization service. Afterwards a dynamic /// list is created and associated to the campaign and the campaign's activity. /// Then the dynamic list is copied to a static list and associated with the same /// campaign and campaign activity. Finally the sample distributes the campaign /// to both the dynamic and static lists. /// </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 Create Dynamic List // Create FetchXml for marketing list's query which locates accounts // in Seattle. String fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'> <entity name='account'> <attribute name='name' /> <attribute name='address1_city' /> <attribute name='primarycontactid' /> <attribute name='telephone1' /> <attribute name='accountid' /> <order attribute='name' descending='false' /> <filter type='and'> <condition attribute='address1_city' operator='eq' value='seattle' /> </filter> </entity> </fetch>"; // Create dynamic list. Set the type to true to declare a dynamic // list. List dynamicList = new List() { Type = true, ListName = "Dynamic List", CreatedFromCode = new OptionSetValue((int)ListCreatedFromCode.Account), Query = fetchXml }; _dynamicListId = _serviceProxy.Create(dynamicList); dynamicList.Id = _dynamicListId; Console.WriteLine("Created dynamic list."); #endregion #region Associate dynamic list to campaign // Create a campaign. Campaign campaign = new Campaign() { Name = "Sample Campaign" }; _campaignId = _serviceProxy.Create(campaign); campaign.Id = _campaignId; // Add the dynamic list to the campaign. AddItemCampaignRequest addListToCampaignRequest = new AddItemCampaignRequest() { CampaignId = _campaignId, EntityId = _dynamicListId, EntityName = List.EntityLogicalName, }; _serviceProxy.Execute(addListToCampaignRequest); Console.WriteLine("Added dynamic list to the campaign."); // Create a campaign activity to distribute fax to the list members. CampaignActivity campaignActivity = new CampaignActivity() { Subject = "Sample Campaign Activity", ChannelTypeCode = new OptionSetValue((int)CampaignActivityChannelTypeCode.Fax), RegardingObjectId = campaign.ToEntityReference() }; _campaignActivityId = _serviceProxy.Create(campaignActivity); // Add dynamic list to campaign activity. AddItemCampaignActivityRequest addListToCampaignActivityRequest = new AddItemCampaignActivityRequest() { CampaignActivityId = _campaignActivityId, ItemId = _dynamicListId, EntityName = List.EntityLogicalName }; _serviceProxy.Execute(addListToCampaignActivityRequest); Console.WriteLine("Added dynamic list to the campaign activity."); #endregion #region Associate static list to campaign // Copy the dynamic list to a static list. CopyDynamicListToStaticRequest copyRequest = new CopyDynamicListToStaticRequest() { ListId = _dynamicListId }; CopyDynamicListToStaticResponse copyResponse = (CopyDynamicListToStaticResponse)_serviceProxy.Execute(copyRequest); _staticListId = copyResponse.StaticListId; Console.WriteLine("Copied dynamic list to a static list."); // Add the static list to the campaign. AddItemCampaignRequest addStaticListToCampaignRequest = new AddItemCampaignRequest() { CampaignId = _campaignId, EntityId = _staticListId, EntityName = List.EntityLogicalName }; _serviceProxy.Execute(addStaticListToCampaignRequest); Console.WriteLine("Added static list to the campaign."); // Add the static list to the campaign activity. AddItemCampaignActivityRequest addStaticListToCampaignActivityRequest = new AddItemCampaignActivityRequest() { CampaignActivityId = _campaignActivityId, ItemId = _staticListId, EntityName = List.EntityLogicalName }; _serviceProxy.Execute(addStaticListToCampaignActivityRequest); Console.WriteLine("Added static list to the campaign's activity."); #endregion #region Create fax for campaign's activity // Create a fax. Fax fax = new Fax() { Subject = "Example Fax" }; Console.WriteLine("Created fax for campaign's activity."); #endregion Create fax for campaign's activity #region Distribute fax to the marketing list // Distribute the campaign activity to the marketing lists. DistributeCampaignActivityRequest distributeRequest = new DistributeCampaignActivityRequest() { CampaignActivityId = _campaignActivityId, Activity = fax, Owner = new EntityReference("systemuser", _salesManagerId), Propagate = true, SendEmail = false, PostWorkflowEvent = true }; _serviceProxy.Execute(distributeRequest); Console.WriteLine("Distributed fax to the marketing lists."); #endregion Distribute fax to the marketing list #region Retrieve collection of entities from marketing list // Retrieve a collection of entities that correspond // to all of the members in a marketing list // This approach of retrieving list members allows you to dynamically // retrieve the members of a list programmatically without requiring // knowledge of the member entity type. OrganizationServiceContext orgContext = new OrganizationServiceContext(_serviceProxy); var member = (from mb in orgContext.CreateQuery <List>() where mb.Id == _dynamicListId select mb).FirstOrDefault(); string fetchQuery = member.Query; RetrieveMultipleRequest memberRequest = new RetrieveMultipleRequest(); FetchExpression fetch = new FetchExpression(fetchQuery); memberRequest.Query = fetch; RetrieveMultipleResponse memberResponse = (RetrieveMultipleResponse)_serviceProxy.Execute(memberRequest); Console.WriteLine("Retrieved collection of entities from a marketing list."); #endregion Retrieve collection of entities from marketing list DeleteRequiredRecords(promptforDelete); } } // Catch any service fault exceptions that Microsoft Dynamics CRM throws. catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ) { // You can handle an exception here or pass it back to the calling method. throw; } }
private void DistributeCampaign() { Console.WriteLine("=== Creating and Distributing the Campaign ==="); // Create the campaign. var campaign = new Campaign { Name = "Sample Campaign" }; _originalCampaignId = _serviceProxy.Create(campaign); NotifyEntityCreated(Campaign.EntityLogicalName, _originalCampaignId); //<snippetDistributeCampaignFromMarketingList1> // Copy the campaign. var campaignCopyRequest = new CopyCampaignRequest { BaseCampaign = _originalCampaignId }; var copyCampaignResponse = (CopyCampaignResponse)_serviceProxy.Execute(campaignCopyRequest); _campaignId = copyCampaignResponse.CampaignCopyId; Console.WriteLine(" Copied the campaign to new campaign with GUID \r\n\t{{{0}}}", _campaignId); //</snippetDistributeCampaignFromMarketingList1> var activity = new CampaignActivity { Subject = "Sample phone call", ChannelTypeCode = new OptionSetValue((int)CampaignActivityChannelTypeCode.Phone), RegardingObjectId = new EntityReference( Campaign.EntityLogicalName, _campaignId) }; _campaignActivityId = _serviceProxy.Create(activity); NotifyEntityCreated(CampaignActivity.EntityLogicalName, _campaignActivityId); // Find the current user to determine who the owner of the activity should be. var whoAmI = new WhoAmIRequest(); var currentUser = (WhoAmIResponse)_serviceProxy.Execute(whoAmI); //<snippetDistributeCampaignFromMarketingList2> // Add the marketing list created earlier to the campaign. var addListToCampaignRequest = new AddItemCampaignRequest { CampaignId = _campaignId, EntityId = _copiedMarketingListId, EntityName = List.EntityLogicalName, }; _serviceProxy.Execute(addListToCampaignRequest); Console.WriteLine(" Added the marketing list to the campaign."); //</snippetDistributeCampaignFromMarketingList2> //<snippetDistributeCampaignFromMarketingList3> // Add the marketing list created earlier to the campaign activity. var addListToActivityRequest = new AddItemCampaignActivityRequest { CampaignActivityId = _campaignActivityId, ItemId = _copiedMarketingListId, EntityName = List.EntityLogicalName }; _serviceProxy.Execute(addListToActivityRequest); Console.WriteLine(" Added the marketing list to the campaign activity."); //</snippetDistributeCampaignFromMarketingList3> // Create the phone call to use for distribution. var phonecall = new PhoneCall { Subject = "Sample Phone Call" }; //<snippetDistributeCampaignFromMarketingList4> // Distribute and execute the campaign activity. // PostWorkflowEvent signals Microsoft Dynamics CRM to actually create the phone call activities. // Propagate also signals to Microsoft Dynamics CRM to create the phone call activities. // OwnershipOptions indicates whom the created activities should be assigned // to. var distributeRequest = new DistributeCampaignActivityRequest { Activity = phonecall, CampaignActivityId = _campaignActivityId, Owner = new EntityReference( SystemUser.EntityLogicalName, currentUser.UserId), OwnershipOptions = PropagationOwnershipOptions.Caller, PostWorkflowEvent = true, Propagate = true, SendEmail = false, }; var distributeResponse = (DistributeCampaignActivityResponse)_serviceProxy.Execute(distributeRequest); Console.WriteLine(" Distributed and executed the campaign activity to the marketing list."); //</snippetDistributeCampaignFromMarketingList4> //<snippetDistributeCampaignFromMarketingList5> // Retrieve the members that were distributed to. var retrieveMembersRequest = new RetrieveMembersBulkOperationRequest { BulkOperationId = distributeResponse.BulkOperationId, BulkOperationSource = (int)BulkOperationSource.CampaignActivity, EntitySource = (int)EntitySource.Contact, Query = new QueryExpression(Contact.EntityLogicalName) }; var retrieveMembersResponse = (RetrieveMembersBulkOperationResponse) _serviceProxy.Execute(retrieveMembersRequest); Console.WriteLine(" Contacts with the following GUIDs were distributed to:"); //</snippetDistributeCampaignFromMarketingList5> foreach (var member in retrieveMembersResponse.EntityCollection.Entities) { Console.WriteLine("\t{{{0}}}", member.Id); } }
/// <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); } } }
/// <summary> /// This method first connects to the Organization service. Afterwards a dynamic /// list is created and associated to the campaign and the campaign's activity. /// Then the dynamic list is copied to a static list and associated with the same /// campaign and campaign activity. Finally the sample distributes the campaign /// to both the dynamic and static lists. /// </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 { //<snippetMarketingAutomation1> // Connect to the Organization service. // The using statement assures that the service proxy will be properly disposed. using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,serverConfig.Credentials, serverConfig.DeviceCredentials)) { // This statement is required to enable early-bound type support. _serviceProxy.EnableProxyTypes(); CreateRequiredRecords(); #region Create Dynamic List // Create FetchXml for marketing list's query which locates accounts // in Seattle. String fetchXml = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'> <entity name='account'> <attribute name='name' /> <attribute name='address1_city' /> <attribute name='primarycontactid' /> <attribute name='telephone1' /> <attribute name='accountid' /> <order attribute='name' descending='false' /> <filter type='and'> <condition attribute='address1_city' operator='eq' value='seattle' /> </filter> </entity> </fetch>"; //<snippetAddItemCampaign> // Create dynamic list. Set the type to true to declare a dynamic // list. List dynamicList = new List() { Type = true, ListName = "Dynamic List", CreatedFromCode = new OptionSetValue((int)ListCreatedFromCode.Account), Query = fetchXml }; _dynamicListId = _serviceProxy.Create(dynamicList); dynamicList.Id = _dynamicListId; Console.WriteLine("Created dynamic list."); #endregion #region Associate dynamic list to campaign // Create a campaign. Campaign campaign = new Campaign() { Name = "Sample Campaign" }; _campaignId = _serviceProxy.Create(campaign); campaign.Id = _campaignId; // Add the dynamic list to the campaign. AddItemCampaignRequest addListToCampaignRequest = new AddItemCampaignRequest() { CampaignId = _campaignId, EntityId = _dynamicListId, EntityName = List.EntityLogicalName, }; _serviceProxy.Execute(addListToCampaignRequest); Console.WriteLine("Added dynamic list to the campaign."); //</snippetAddItemCampaign> //<snippetAddItemCampaignActivity> // Create a campaign activity to distribute fax to the list members. CampaignActivity campaignActivity = new CampaignActivity() { Subject = "Sample Campaign Activity", ChannelTypeCode = new OptionSetValue((int)CampaignActivityChannelTypeCode.Fax), RegardingObjectId = campaign.ToEntityReference() }; _campaignActivityId = _serviceProxy.Create(campaignActivity); // Add dynamic list to campaign activity. AddItemCampaignActivityRequest addListToCampaignActivityRequest = new AddItemCampaignActivityRequest() { CampaignActivityId = _campaignActivityId, ItemId = _dynamicListId, EntityName = List.EntityLogicalName }; _serviceProxy.Execute(addListToCampaignActivityRequest); Console.WriteLine("Added dynamic list to the campaign activity."); //</snippetAddItemCampaignActivity> #endregion #region Associate static list to campaign //<snippetCopyDynamicListToStatic> // Copy the dynamic list to a static list. CopyDynamicListToStaticRequest copyRequest = new CopyDynamicListToStaticRequest() { ListId = _dynamicListId }; CopyDynamicListToStaticResponse copyResponse = (CopyDynamicListToStaticResponse)_serviceProxy.Execute(copyRequest); _staticListId = copyResponse.StaticListId; Console.WriteLine("Copied dynamic list to a static list."); //</snippetCopyDynamicListToStatic> // Add the static list to the campaign. AddItemCampaignRequest addStaticListToCampaignRequest = new AddItemCampaignRequest() { CampaignId = _campaignId, EntityId = _staticListId, EntityName = List.EntityLogicalName }; _serviceProxy.Execute(addStaticListToCampaignRequest); Console.WriteLine("Added static list to the campaign."); // Add the static list to the campaign activity. AddItemCampaignActivityRequest addStaticListToCampaignActivityRequest = new AddItemCampaignActivityRequest() { CampaignActivityId = _campaignActivityId, ItemId = _staticListId, EntityName = List.EntityLogicalName }; _serviceProxy.Execute(addStaticListToCampaignActivityRequest); Console.WriteLine("Added static list to the campaign's activity."); #endregion #region Create fax for campaign's activity // Create a fax. Fax fax = new Fax() { Subject = "Example Fax" }; Console.WriteLine("Created fax for campaign's activity."); #endregion Create fax for campaign's activity #region Distribute fax to the marketing list //<snippetDistributeCampaignActivity> // Distribute the campaign activity to the marketing lists. DistributeCampaignActivityRequest distributeRequest = new DistributeCampaignActivityRequest() { CampaignActivityId = _campaignActivityId, Activity = fax, Owner = new EntityReference("systemuser", _salesManagerId), Propagate = true, SendEmail = false, PostWorkflowEvent = true }; _serviceProxy.Execute(distributeRequest); Console.WriteLine("Distributed fax to the marketing lists."); //</snippetDistributeCampaignActivity> #endregion Distribute fax to the marketing list #region Retrieve collection of entities from marketing list // Retrieve a collection of entities that correspond // to all of the members in a marketing list // This approach of retrieving list members allows you to dynamically // retrieve the members of a list programmatically without requiring // knowledge of the member entity type. OrganizationServiceContext orgContext = new OrganizationServiceContext(_serviceProxy); var member = (from mb in orgContext.CreateQuery<List>() where mb.Id == _dynamicListId select mb).FirstOrDefault(); string fetchQuery = member.Query; RetrieveMultipleRequest memberRequest = new RetrieveMultipleRequest(); FetchExpression fetch = new FetchExpression(fetchQuery); memberRequest.Query = fetch; RetrieveMultipleResponse memberResponse = (RetrieveMultipleResponse)_serviceProxy.Execute(memberRequest); Console.WriteLine("Retrieved collection of entities from a marketing list."); #endregion Retrieve collection of entities from marketing list DeleteRequiredRecords(promptforDelete); } //</snippetMarketingAutomation1> } // 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; } }