/// <summary> /// Obtain the key/value pairs for a CampaignActivity. /// </summary> /// <param name="campaign">CampaignActivity to turn into key/value pairs.</param> /// <returns>Key/value pairs representing this CampaignActivity.</returns> internal static IEnumerable <KeyValuePair <string, string> > GetParameters(CampaignActivity campaign) { if (!String.IsNullOrEmpty(campaign.Name)) { yield return(KeyValuePair.Create("cn", campaign.Name)); } if (!String.IsNullOrEmpty(campaign.Source)) { yield return(KeyValuePair.Create("cs", campaign.Source)); } if (!String.IsNullOrEmpty(campaign.Medium)) { yield return(KeyValuePair.Create("cm", campaign.Medium)); } if (!String.IsNullOrEmpty(campaign.Term)) { yield return(KeyValuePair.Create("ck", campaign.Term)); } if (!String.IsNullOrEmpty(campaign.Content)) { yield return(KeyValuePair.Create("cc", campaign.Content)); } }
public CampaignActivityEditModel GetActivityEditModel(long activityId, long campaignId) { CampaignActivity activity = null; if (activityId > 0) { activity = _campaignActivityRepository.GetById(activityId); } var campaign = _campaignRepository.GetById(campaignId); var model = activity != null?CampaignActivityDomainToModel(activity) : new CampaignActivityEditModel(); model.CampaigndId = campaignId; model.CampaignStartDate = campaign.StartDate; model.CampaignEndDate = campaign.EndDate; if (activityId > 0) { var activityAssignments = _campaignActivityAssignmentRepository.GetByCampaignActivityId(model.ActivityId); if (activityAssignments != null && activityAssignments.Any()) { var assignedUserNamePair = _organizationRoleUserRepository.GetNameIdPairofUsers(activityAssignments.Select(x => x.AssignedToOrgRoleUserId).ToArray()); model.Assignments = GetCampaignAssignments(assignedUserNamePair, model.ActivityId); } } return(model); }
/// <summary> /// Obtain the key/value pairs for a CampaignActivity. /// </summary> /// <param name="campaign">CampaignActivity to turn into key/value pairs.</param> /// <returns>Key/value pairs representing this CampaignActivity.</returns> internal static IEnumerable <KeyValuePair <string, string> > GetParameters(CampaignActivity campaign) { yield return(KeyValuePair.Create("utmcsr", campaign.Source)); if (!String.IsNullOrEmpty(campaign.Name)) { yield return(KeyValuePair.Create("utmccn", campaign.Name)); } if (!String.IsNullOrEmpty(campaign.Medium)) { yield return(KeyValuePair.Create("utmcmd", campaign.Medium)); } if (!String.IsNullOrEmpty(campaign.Term)) { yield return(KeyValuePair.Create("utmctr", campaign.Term)); } if (!String.IsNullOrEmpty(campaign.Content)) { yield return(KeyValuePair.Create("utmcct", campaign.Content)); } yield return(KeyValuePair.Create(campaign.IsNewVisit ? "utmcn" : "utmcr", "1")); }
public void UrchinActivityParameterBuilder_GetParameter_For_CampaignActivity_Returns_Correct_Values() { var activity = new CampaignActivity("source"); var parameters = UrchinActivityParameterBuilder.GetParameters(activity).ToDictionary(k => k.Key, v => v.Value); Assert.AreEqual("source", parameters["utmcsr"]); }
public void UrchinActivityParameterBuilder_GetParameter_For_CampaignActivity_Returns_Correct_Keys_When_Not_IsNewVisit() { var activity = new CampaignActivity("source"); var results = UrchinActivityParameterBuilder.GetParameters(activity).ToDictionary(k => k.Key, v => v); var expectedKeys = new[] { "utmcsr", "utmcr" }; CollectionAssert.AreEquivalent(expectedKeys, results.Keys); }
public void CampaignActivity_Constructor_With_All_Parameters_Sets_Correct_Properties() { var activity = new CampaignActivity("source"); Assert.AreEqual("source", activity.Source); Assert.IsNull(activity.Name); Assert.IsNull(activity.Medium); Assert.IsNull(activity.Term); Assert.IsNull(activity.Content); }
private CampaignActivityEditModel CampaignActivityDomainToModel(CampaignActivity activity) { return(new CampaignActivityEditModel { ActivityId = activity.Id, ActivityDate = activity.ActivityDate, Sequence = activity.Sequence, ActivityType = activity.TypeId, DirectMailType = activity.DirectMailTypeId ?? 0, Name = EnumExtension.GetDescription(((CampaignActivityType)activity.TypeId)) }); }
public async Task SaveTracking(Guid id) { try { _automailerContext.CampaignActivities.Add(CampaignActivity.Create(id)); await _automailerContext.SaveChangesAsync(); } catch (Exception ex) { _logger.LogError(ex.Message); } }
public CampaignActivity Save(CampaignActivity domainObject) { using (var adapter = PersistenceLayer.GetDataAccessAdapter()) { var entity = Mapper.Map <CampaignActivity, CampaignActivityEntity>(domainObject); if (!adapter.SaveEntity(entity, true)) { throw new PersistenceFailureException("Could not save Call Upload "); } return(Mapper.Map <CampaignActivityEntity, CampaignActivity>(entity)); } }
public void CampaignActivity_Properties_Can_Be_Set() { var activity = new CampaignActivity("source") { Name = "name", Medium = "medium", Term = "term", Content = "content", IsNewVisit = true }; Assert.AreEqual("name", activity.Name); Assert.AreEqual("medium", activity.Medium); Assert.AreEqual("term", activity.Term); Assert.AreEqual("content", activity.Content); Assert.AreEqual(true, activity.IsNewVisit); }
private void SaveActivity(long orgRoleId, long campaignId, CampaignActivityEditModel model) { CampaignActivity campaignActivity = null; if (model.ActivityId > 0) { campaignActivity = _campaignActivityRepository.GetById(model.ActivityId); } var activity = GetCampaignActivityModeltoDomain(campaignActivity, model, orgRoleId, campaignId); activity = _campaignActivityRepository.Save(activity); _campaignActivityAssignmentRepository.DeleteByCampaignId(activity.Id); if (model.Assignments != null && model.Assignments.Any()) { _campaignActivityAssignmentRepository.Save(activity.Id, model.Assignments.Select(x => x.AssignedOrgRoleUserId)); } }
public void UrchinActivityParameterBuilder_GetParameter_For_CampaignActivity_Returns_Correct_Optional_Values() { var activity = new CampaignActivity("source") { Name = "name", Medium = "medium", Term = "term", Content = "content" }; var parameters = UrchinActivityParameterBuilder.GetParameters(activity).ToDictionary(k => k.Key, v => v.Value); Assert.AreEqual("source", parameters["utmcsr"]); Assert.AreEqual("name", parameters["utmccn"]); Assert.AreEqual("medium", parameters["utmcmd"]); Assert.AreEqual("term", parameters["utmctr"]); Assert.AreEqual("content", parameters["utmcct"]); }
private CampaignActivity GetCampaignActivityModeltoDomain(CampaignActivity domain, CampaignActivityEditModel model, long orgRoleId, long campaignId) { domain = domain ?? new CampaignActivity { DataRecorderMetaData = new DataRecorderMetaData(orgRoleId, DateTime.Now, DateTime.Now) }; domain.Sequence = model.Sequence; domain.TypeId = model.ActivityType; domain.DirectMailTypeId = (model.ActivityType == (long)CampaignActivityType.DirectMail) ? (long?)model.DirectMailType : null; if (model.ActivityDate.HasValue) { domain.ActivityDate = model.ActivityDate.Value; } domain.CampaignId = campaignId; domain.DataRecorderMetaData.DataRecorderModifier = new OrganizationRoleUser(orgRoleId); domain.DataRecorderMetaData.DateModified = DateTime.Now; return(domain); }
public void MeasurementActivityParameterBuilder_GetParameter_For_CampaignActivity_Returns_Correct_Values() { var activity = new CampaignActivity("source") { Name = "name", Medium = "medium", Term = "term", Content = "content" }; var parameters = MeasurementActivityParameterBuilder.GetParameters(activity).ToDictionary(k => k.Key, v => v.Value); Assert.AreEqual(5, parameters.Keys.Count); Assert.AreEqual("source", parameters["cs"]); Assert.AreEqual("name", parameters["cn"]); Assert.AreEqual("medium", parameters["cm"]); Assert.AreEqual("term", parameters["ck"]); Assert.AreEqual("content", parameters["cc"]); }
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> /// 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>(); ITracingService t = tracingService; if (tracingService == null) { throw new InvalidPluginExecutionException("Failed to retrieve tracing service."); } tracingService.Trace("Entered DistributeCampaignActivityEmails.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("DistributeCampaignActivityEmails.Execute(), Correlation Id: {0}, Initiating User: {1}", context.CorrelationId, context.InitiatingUserId); IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>(); IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId); t.Trace("Get the inputEntity. "); Entity inputEntity = service.Retrieve( context.PrimaryEntityName, context.PrimaryEntityId, new ColumnSet { AllColumns = true }); t.Trace("Cast to a CampaignActivity. "); CampaignActivity entity = (CampaignActivity)inputEntity; try { // This custom workflow runs a DistributeCampaignActivityRequest using the email // template Guid set in the Campaign Activity. # region Campaign Activity entity error checking. t.Trace("Error checking. "); // Make sure this entity is a Campaign Activity, its Status Reason is Open, and it // has a valid Email Template. if (inputEntity.LogicalName != "campaignactivity") { t.Trace("This isn't a Campaign Activity."); throw new InvalidPluginExecutionException(); } if (String.IsNullOrEmpty(entity.cldrkt_EmailTemplateID)) { t.Trace("The email template field is empty."); throw new InvalidPluginExecutionException(); } Guid emailTemplateId = Guid.Empty; Guid.TryParse(entity.cldrkt_EmailTemplateID, out emailTemplateId); // Guid.Empty if false. if (emailTemplateId == Guid.Empty) { t.Trace("The email template field has data, but it isn't a valid Guid."); throw new InvalidPluginExecutionException(); } QueryExpression templateQuery = new QueryExpression { EntityName = Template.EntityLogicalName, ColumnSet = new ColumnSet { AllColumns = true }, Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = "templateid", Operator = ConditionOperator.Equal, Values = { emailTemplateId}, } } } }; t.Trace("Looking up the email Template."); Entity template = service.RetrieveMultiple(templateQuery).Entities.FirstOrDefault(); if (template == null) { t.Trace("This is a valid Guid, but it doesn't match an existing email template."); throw new InvalidPluginExecutionException(); } # endregion
/// <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; } }
/// <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 GetCampaignResponseFromWebPageView.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("GetCampaignResponseFromWebPageView.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 { // If we have a CampaignActivityId in the URL, create a CampaignResponse and map it // to the Web Page View. If we have a CampaignResponseCustomer in the URL, add that // Contact to the CampaignResponse and Web Page View. // Get the Page View from the workflow context. t.Trace("1. Get the Page View from the workflow context and default the driving variables."); cldrkt_pageview pageView = (cldrkt_pageview)service.Retrieve( context.PrimaryEntityName, context.PrimaryEntityId, new ColumnSet { AllColumns = true }); CampaignActivity campaignActivity = new CampaignActivity(); CampaignResponse campaignResponse = new CampaignResponse(); Contact contact = new Contact(); #region Process the Campaign Customer, if any. // Get the Campaign Customer, if any. t.Trace("c1. Get the Campaign Customer, if any..."); Guid contactId = Guid.Empty; t.Trace("pageView.cldrkt_CampaignResponseCustomerId: " + pageView.cldrkt_CampaignResponseCustomerId); if (String.IsNullOrWhiteSpace(pageView.cldrkt_CampaignResponseCustomerId)) { contactId = Guid.Empty; t.Trace("contactId: " + contactId.ToString()); } else { Guid.TryParse(pageView.cldrkt_CampaignResponseCustomerId, out contactId); if (contactId != Guid.Empty) { t.Trace("c2. Look up the Campaign Customer..."); contact = (Contact)service.Retrieve(Contact.EntityLogicalName, contactId, new ColumnSet { AllColumns = true }); t.Trace("contactId: " + contactId.ToString()); t.Trace("contact.Id: " + contact.Id.ToString()); if (contact != null) { // Add the Campaign Activity Customer to the Campaign Response and Page View t.Trace("c3. Add the Campaign Activity Customer to the Campaign Response and Page View"); campaignResponse.Customer = new ActivityParty[] { new ActivityParty {PartyId = new EntityReference (contact.LogicalName, contact.Id)} }; pageView.cldrkt_CampaignResponseCustomer = new EntityReference { Id = contact.Id, LogicalName = contact.LogicalName, }; } } } #endregion Process the Campaign Customer, if any. #region Process the Campaign Activity, if any. // Get the Campaign Activity, if any. t.Trace("ca1. Get the Campaign Activity, if any..."); Guid campaignActivityId = Guid.Empty; t.Trace("pageView.cldrkt_CampaignActivityId: " + pageView.cldrkt_CampaignActivityId); if (String.IsNullOrWhiteSpace(pageView.cldrkt_CampaignActivityId)) { campaignActivityId = Guid.Empty; t.Trace("campaignActivityId: " + campaignActivityId); } else { Guid.TryParse(pageView.cldrkt_CampaignActivityId, out campaignActivityId); if (campaignActivityId != Guid.Empty) // Look up the Campaign Activity { t.Trace("ca2. Look up the Campaign Activity..."); campaignActivity = (CampaignActivity)service.Retrieve( CampaignActivity.EntityLogicalName, campaignActivityId, new ColumnSet { AllColumns = true }); t.Trace("campaignActivityId: " + campaignActivityId); t.Trace("campaignActivity.Id: " + campaignActivity.Id.ToString()); if (campaignActivity != null) // Process for a Campaign Activity { // Create a Campaign Response. t.Trace("ca3. Create a Campaign Response..."); campaignResponse.ChannelTypeCode = new OptionSetValue(636280000); campaignResponse.OriginatingActivityId = new EntityReference { Id = campaignActivity.Id, LogicalName = CampaignActivity.EntityLogicalName, }; campaignResponse.RegardingObjectId = new EntityReference // Required, must be the parent campaign { Id = campaignActivity.RegardingObjectId.Id, LogicalName = Campaign.EntityLogicalName, }; campaignResponse.ReceivedOn = pageView.CreatedOn; campaignResponse.Subject = pageView.cldrkt_name; campaignResponse.ActivityId = service.Create(campaignResponse); t.Trace("campaignResponse.ActivityId: " + campaignResponse.ActivityId); t.Trace("campaignResponse.Id: " + campaignResponse.Id.ToString()); // Update the Campaign Response. t.Trace("ca4. Update the Campaign Response."); t.Trace("campaignResponse.Id: " + campaignResponse.Id); if (campaignResponse.Id != Guid.Empty) { service.Update(campaignResponse); t.Trace("campaignResponse.Id = " + campaignResponse.Id.ToString()); } // Add the Campaign Activity to the Page View. t.Trace("4. Add the Campaign Activity to the Page View"); pageView.cldrkt_Campaign = new EntityReference { Id = campaignActivity.RegardingObjectId.Id, LogicalName = campaignActivity.RegardingObjectId.LogicalName, }; pageView.cldrkt_CampaignActivity = new EntityReference { Id = campaignActivity.Id, LogicalName = campaignActivity.LogicalName, }; pageView.cldrkt_CampaignResponse = new EntityReference { Id = campaignResponse.Id, LogicalName = campaignResponse.LogicalName, }; } } } #endregion Process the Campaign Activity, if any. #region Set the day of the week, in Pacific Time Zone from UTC cldrkt_createdon. DateTime createdOn = (DateTime)pageView["createdon"]; createdOn = DateTime.SpecifyKind(createdOn, DateTimeKind.Utc); TimeZoneInfo timeZone = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time"); string dayOfWeek = TimeZoneInfo.ConvertTimeFromUtc(createdOn, timeZone).DayOfWeek.ToString().Substring(0, 3); // Get the Days of the Week Option Set metadata. RetrieveOptionSetRequest optionSetRequest = new RetrieveOptionSetRequest { Name = "cldrkt_daysoftheweek" }; RetrieveOptionSetResponse optionSetResponse = (RetrieveOptionSetResponse)service.Execute(optionSetRequest); OptionSetMetadata optionSetMetaData = (OptionSetMetadata)optionSetResponse.OptionSetMetadata; // Look up the OptionSetValue Value using dayOfWeek. OptionSetValue optionSetValue = new OptionSetValue { Value = (Int32)optionSetMetaData.Options .FirstOrDefault(o => o.Label.UserLocalizedLabel.Label == dayOfWeek).Value, }; // outputDayOfTheWeek.Set(executionContext, dayOfWeek); pageView["cldrkt_createdonweekdayoptionset"] = optionSetValue; #endregion Set the day of the week, in Pacific Time Zone from UTC cldrkt_createdon. // Update the Page View. t.Trace("10. Update the Page View."); service.Update(pageView); // throw new InvalidPluginExecutionException("Finished processing the Page View update."); } catch (FaultException<OrganizationServiceFault> e) { tracingService.Trace("Exception: {0}", e.ToString()); // Handle the exception. throw; } tracingService.Trace("Exiting GetCampaignResponseFromWebPageView.Execute(), Correlation Id: {0}", context.CorrelationId); }
private IEnumerable <CampaignActivityAssignmentEditModel> GetActivityAssignment(IEnumerable <CampaignActivityAssignment> activityAssignments, IEnumerable <CampaignActivityAssignment> campaignActivityAssignment, CampaignActivity activity) { var activityAssigmentList = new List <CampaignActivityAssignmentEditModel>(); if (activityAssignments != null && campaignActivityAssignment.Any()) { var assignedUserNamePair = _organizationRoleUserRepository.GetNameIdPairofUsers( activityAssignments.Select(x => x.AssignedToOrgRoleUserId).ToArray()); activityAssigmentList.AddRange(assignedUserNamePair.Select(assignment => new CampaignActivityAssignmentEditModel { AssignedOrgRoleUserId = assignment.FirstValue, Name = assignment.SecondValue, CampaignActivityId = activity.Id })); } return(activityAssigmentList); }
/// <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; } }
[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> /// 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); }