/// <summary>
        /// Distribute <c>CampaignActivity</c>.
        /// Creates the appropriate activity for each member in the list for the specified campaign activity.
        /// <para>
        /// For more information look at https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.distributecampaignactivityrequest(v=crm.8).aspx
        /// </para>
        /// </summary>
        /// <param name="id"><c>CampaignActvity</c> Id</param>
        /// <param name="activityEntity"><c>Activity</c> to be distributed.
        /// This should be <c>phonecall</c> - <c>appointment</c> - <c>letter</c> - <c>fax</c> - <c>email</c>.
        /// </param>
        /// <param name="propagationOwnershipOptions">
        /// <c>Ownership</c> options for the activity
        /// This parameter 's values are;
        /// <c>Caller</c> : All created activities are assigned to the caller of <see cref="IOrganizationService"/>
        /// <c>ListMemberOwner</c> : Created activities are assigned to respective owners of target members.
        /// <c>None</c> : There is no change in ownership for the created activities.
        /// <para>
        /// For more information look at https://msdn.microsoft.com/en-us/library/microsoft.crm.sdk.messages.propagationownershipoptions(v=crm.8).aspx
        /// </para>
        /// </param>
        /// <param name="ownerTypeCode"></param>
        /// <param name="ownerId"></param>
        /// <param name="queueId">
        /// Set this field if you want also add created activities to an <c>Queue</c>.
        /// Method throws an exception (<see cref="ExceptionThrow.IfGuidEmpty(Guid, string, string)"/>) if you set this field to <see cref="Guid.Empty"/>
        /// </param>
        /// <param name="emailTemplateId">
        /// If you distribute <c>CampaignActivity</c> with <c>Email</c> and you want to use existing <c>template</c> set this field.
        /// Method throws an exception (<see cref="ExceptionThrow.IfGuidEmpty(Guid, string, string)"/>) if you set this field to <see cref="Guid.Empty"/>
        /// </param>
        /// <param name="doesPropagate">
        /// Set <c>true</c>, whether the activity is both created and executed. Otherwise set <c>false</c>.
        /// This field's default value is <c>true</c>, so activity will be created and executed (exp: email wil be send)
        /// </param>
        /// <param name="useAsync">
        /// Set <c>true</c>, if you want use an asynchronous job to distribute activities. Otherwise set <c>false</c>.
        /// This field's default value is <c>true</c>
        /// </param>
        /// <param name="sendEmail">
        /// Set <c>true</c> if you distribute <c>CampaignActivity</c> with <c>Email</c> and you want to send created activities.
        /// </param>
        /// <param name="validateActivity">
        /// Validates activity entity with required attributes and using method's enum values
        /// </param>
        /// <returns>
        /// Returns created <c>BulkOperation</c> Id in <see cref="DistributeCampaignActivityResponse.BulkOperationId"/> property.
        /// </returns>
        public DistributeCampaignActivityResponse Distribute(Guid id, Entity activityEntity, PropagationOwnershipOptions propagationOwnershipOptions, PrincipalType ownerTypeCode, Guid ownerId, Guid?queueId, Guid?emailTemplateId, bool doesPropagate = true, bool useAsync = true, bool sendEmail = false, bool validateActivity = true)
        {
            ExceptionThrow.IfGuidEmpty(id, "id");
            ExceptionThrow.IfGuidEmpty(ownerId, "ownerId");

            ValidateEntity(activityEntity);

            if (validateActivity)
            {
                ValidateActivity(id, activityEntity.LogicalName);
            }

            DistributeCampaignActivityRequest request = new DistributeCampaignActivityRequest()
            {
                CampaignActivityId = id,
                Activity           = activityEntity,
                Owner             = new EntityReference(ownerTypeCode.Description(), ownerId),
                OwnershipOptions  = propagationOwnershipOptions,
                PostWorkflowEvent = useAsync,
                Propagate         = doesPropagate,
                SendEmail         = sendEmail
            };

            if (queueId.HasValue)
            {
                ExceptionThrow.IfGuidEmpty(queueId.Value, "queueId");

                request.QueueId = queueId.Value;
            }

            if (emailTemplateId.HasValue)
            {
                ExceptionThrow.IfGuidEmpty(emailTemplateId.Value, "emailTemplateId");

                request.TemplateId = emailTemplateId.Value;
            }

            return((DistributeCampaignActivityResponse)this.OrganizationService.Execute(request));
        }
Esempio n. 2
0
        [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);
            }
        }
Esempio n. 5
0
        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);
            }
        }
Esempio n. 6
0
        /// <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;
            }
        }