Sample: Create, read, update, and delete lead (including UDF custom fields)

 

Applies To: Dynamics Marketing

This sample code is for Microsoft Dynamics Marketing. The sample code can be found in the following location after you download and install the Microsoft Dynamics Marketing SDK:

Samples\CS\LeadSample

Requirements

Note

This sample works with your live production data. It might create real leads in your Microsoft Dynamics Marketing environment.

Demonstrates

This sample demonstrates how to create, retrieve, update, and delete a lead using Dynamics Marketing.

Example

namespace Microsoft.Dynamics.Marketing.SDK.Samples.LeadSample
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using Microsoft.Dynamics.Marketing.SDK.Common;
    using Microsoft.Dynamics.Marketing.SDK.Messages;
    using Microsoft.Dynamics.Marketing.SDK.Messages.Lead;
    using Microsoft.Dynamics.Marketing.SDK.Model;
    using Microsoft.Dynamics.Marketing.SDK.Samples.SdkClient;
    using Microsoft.Dynamics.Marketing.SDK.Samples.SdkSample;

    /// <summary>
    /// Demonstrates how to perform create, read, update, and delete operations on the Lead entity.
    /// </summary>
    /// <remarks>
    /// Depending on which part of the sample you run, some prior set up is required.
    /// For all of the options in this sample you must have the SDK configured with your Microsoft Azure Service Bus queues on the Integration Options page in Microsoft Dynamics Marketing.
    /// You must also have permissions enabled for lead
    /// </remarks>
    public class LeadSample : SdkSample
    {
        private bool updateRequestSent;

        /// <summary>
        /// Starting point for the sample.
        /// </summary>
        /// <param name="args">Arguments needed for authentication.</param>
        public static void Main(string[] args)
        {
            try
            {
                // This creates the QueueClientProvider that connects to the queues, tests them, and then provides them to the client when needed.
                var queueClientProvider = CreateQueueClientProviderFromArgs(args);

                // This runs the sample that shows a menu of possible requests.
                var sample = new LeadSample(queueClientProvider);
                sample.Run();
            }
            catch (Exception ex)
            {
                LeadSample.WriteException(ex);
                Console.WriteLine("Press Enter key to exit.");
                Console.ReadLine();
            }
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="LeadSample"/> class.
        /// </summary>
        /// <param name="queueClientProvider">
        /// The QueueClientProvider that’s set up to connect to the SDK queues configured in Microsoft Dynamics Marketing.
        /// </param>
        public LeadSample(IQueueClientProvider queueClientProvider)
        {
            this.updateRequestSent = false;
            var responseHandlerMapping = new Dictionary<Type, Client.ResponseHandler>
            {
                { typeof(RetrieveLeadResponse), this.ProcessRetrieveLeadResponse },
                { typeof(CreateOrUpdateLeadResponse), this.ProcessCreateOrUpdateLeadResponse },
                { typeof(DeleteLeadResponse), this.ProcessDeleteLeadResponse },
                { typeof(RetrieveLeadPrioritiesResponse), this.ProcessRetrieveLeadPrioritiesResponse },
                { typeof(RetrieveLeadStatusesResponse), this.ProcessRetrieveLeadStatusesResponse },
                { typeof(RetrieveTerritoriesResponse), this.ProcessRetrieveTerritoriesResponse },
                { typeof(RetrieveSalesRatingsResponse), this.ProcessRetrieveSalesRatingsResponse },
                { typeof(RetrieveLeadsResponse), this.ProcessRetrieveLeadsResponse },
                { typeof(SdkErrorResponse), this.ProcessSdkErrorResponse }
            };

            this.SetupClient(queueClientProvider, responseHandlerMapping);

            this.SampleMenuActions = new Dictionary<string, Tuple<string, Action>>
            {
                { "1", new Tuple<string, Action>("Retrieve a lead", this.RetrieveLead) },
                { "2", new Tuple<string, Action>("Create a lead", this.CreateLead) },
                { "3", new Tuple<string, Action>("Update a lead", this.UpdateLead) },
                { "4", new Tuple<string, Action>("Delete a lead", this.DeleteLead) },
                { "5", new Tuple<string, Action>("Retrieve a list of priorities", this.RetrieveLeadPriorities) },
                { "6", new Tuple<string, Action>("Retrieve a list of statuses", this.RetrieveLeadStatuses) },
                { "7", new Tuple<string, Action>("Retrieve a list of territories", this.RetrieveTerritories) },
                { "8", new Tuple<string, Action>("Retrieve a list of sales ratings", this.RetrieveSalesRatings) },
                { "9", new Tuple<string, Action>("Retrieve multiple Leads", this.RetrieveLeads) },
            };
        }

        /// <summary>
        /// Demonstrates RetrieveLeadRequest and RetrieveLeadResponse.
        /// </summary>
        private void RetrieveLead()
        {
            Console.WriteLine("This request retrieves a lead.");
            Console.Write("Please type the ID (GUID) for the lead to retrieve => ");
            Guid id;
            if (Guid.TryParse(Console.ReadLine(), out id))
            {
                var request = new RetrieveLeadRequest { LeadId = id };
                this.Client.ProcessRequest(request);
            }
            else
            {
                Console.WriteLine("Incorrect ID");
            }
        }

        /// <summary>
        /// Handles the RetrieveLeadResponse that is received from the response queue. Displays the lead.
        /// </summary>
        /// <param name="response">The RetrieveLeadResponse received after sending a RetrieveLeadRequest.</param>
        private void ProcessRetrieveLeadResponse(SdkResponse response)
        {
            var retrieveLeadResponse = (RetrieveLeadResponse)response;
            Console.WriteLine("Processing RetrieveLeadResponse.");

            if (this.updateRequestSent)
            {
                Console.WriteLine("Old name for lead: " + retrieveLeadResponse.Lead.Name);
                Console.Write("Please type the new Name for the lead => ");
                var name = Console.ReadLine();
                if (string.IsNullOrEmpty(name))
                {
                    Console.WriteLine("Incorrect Name");
                    return;
                }

                var lead = retrieveLeadResponse.Lead;
                lead.Name = name;
                var request = new CreateOrUpdateLeadRequest { Lead = lead };
                this.Client.ProcessRequest(request);
            }
            else
            {
                this.PrintLead(retrieveLeadResponse.Lead);
            }
        }

        /// <summary>
        /// Print the content of a lead.
        /// </summary>
        /// <param name="lead">The lead</param>
        private void PrintLead(Lead lead)
        {
            foreach (var propertyInfo in lead.GetType().GetProperties().ToList())
            {
                var value = propertyInfo.GetValue(lead);
                var company = value as Company;
                if (company != null)
                {
                    Console.WriteLine(propertyInfo.Name + ":" + company.Id + " (" + company.Name + ")");
                    continue;
                }

                var contact = value as Contact;
                if (contact != null)
                {
                    Console.WriteLine(propertyInfo.Name + ":" + contact.Id + " (" + contact.FirstName + " " + contact.LastName + ")");
                    continue;
                }

                var campaign = value as Campaign;
                if (campaign != null)
                {
                    Console.WriteLine(propertyInfo.Name + ":" + campaign.Id + " (" + campaign.Name + ")");
                    continue;
                }

                var program = value as Program;
                if (program != null)
                {
                    Console.WriteLine(propertyInfo.Name + ":" + program.Id + " (" + program.Name + ")");
                    continue;
                }

                if (string.CompareOrdinal(propertyInfo.Name, "OriginOfChanges") == 0)
                {
                    Console.WriteLine(propertyInfo.Name + ":" + string.Join(";", ((ICollection<string>)value).Distinct()));
                    continue;
                }

                if (propertyInfo.Name == "CustomFields")
                {
                    var customFields = (Dictionary<string, object>)value;
                    foreach (var customField in customFields)
                    {
                        var category = customField.Value as Category;
                        if (category != null)
                        {
                            Console.WriteLine(customField.Key + "Id:" + category.Id);
                            Console.WriteLine(customField.Key + "Name:" + category.Name);
                        }
                        else
                        {
                            Console.WriteLine(customField.Key + ":" + customField.Value);
                        }
                    }
                }
                else
                {
                    if (propertyInfo.PropertyType == typeof(LeadStatus))
                    {
                        if (value == null)
                        {
                            Console.WriteLine(propertyInfo.Name + ":");
                        }
                        else
                        {
                            Console.WriteLine(propertyInfo.Name + ":" + ((LeadStatus)value).Name);
                        }
                    }
                    else
                    {
                        if (propertyInfo.PropertyType == typeof(LeadPriority))
                        {
                            if (value == null)
                            {
                                Console.WriteLine(propertyInfo.Name + ":");
                            }
                            else
                            {
                                Console.WriteLine(propertyInfo.Name + ":" + ((LeadPriority)value).Name);
                            }
                        }
                        else
                        {
                            Console.WriteLine(propertyInfo.Name + ":" + value);
                        }
                    }
                }
            }
        }

        /// <summary>
        /// Demonstrates how to create a lead.
        /// </summary>
        private void CreateLead()
        {
            Console.WriteLine("This request creates a lead.");
            Console.Write("Please type the ID (GUID) for the new lead => ");
            Guid id;
            if (!Guid.TryParse(Console.ReadLine(), out id))
            {
                Console.WriteLine("Incorrect ID");
                return;
            }

            Console.Write("Please type the name for the new lead => ");
            var name = Console.ReadLine();
            if (string.IsNullOrEmpty(name))
            {
                Console.WriteLine("Incorrect Name");
                return;
            }

            Console.Write("Please type the ID (GUID) for the company that the new lead belongs to => ");
            Guid belongsToCompanyId;
            if (!Guid.TryParse(Console.ReadLine(), out belongsToCompanyId))
            {
                Console.WriteLine("Incorrect belongs to ID");
                return;
            }

            var lead = new Lead
                           {
                               Id = id,
                               Name = name,
                               BelongsToCompany = new Company { Id = belongsToCompanyId },
                               Date = DateTime.UtcNow
                           };

            var request = new CreateOrUpdateLeadRequest { Lead = lead };
            this.Client.ProcessRequest(request);
        }

        /// <summary>
        /// Demonstrates how to update a lead.
        /// </summary>
        private void UpdateLead()
        {
            Console.WriteLine("This request updates a lead.");
            Console.Write("Please type the ID (GUID) for the lead => ");
            Guid id;
            if (!Guid.TryParse(Console.ReadLine(), out id))
            {
                Console.WriteLine("Incorrect ID");
                return;
            }

            this.updateRequestSent = true;
            var request = new RetrieveLeadRequest { LeadId = id };
            this.Client.ProcessRequest(request);
        }

        /// <summary>
        /// Handles the <see cref="CreateOrUpdateLeadResponse"/> that is received from the response queue. Displays the lead.
        /// </summary>
        /// <param name="response">The <see cref="CreateOrUpdateLeadResponse"/> received after sending a <see cref="CreateOrUpdateLeadRequest"/>.</param>
        private void ProcessCreateOrUpdateLeadResponse(SdkResponse response)
        {
            var createOrUpdateLeadResponse = (CreateOrUpdateLeadResponse)response;
            Console.WriteLine("Processing CreateOrUpdateLeadResponse.");

            if (!createOrUpdateLeadResponse.Succeeded)
            {
                Console.WriteLine("Failed to create/update lead");
                return;
            }

            Console.WriteLine("The create/update lead");
            this.PrintLead(createOrUpdateLeadResponse.Lead);
            this.updateRequestSent = false;
        }

        /// <summary>
        /// Demonstrates how to delete a lead.
        /// </summary>
        private void DeleteLead()
        {
            Console.WriteLine("This request deletes a lead.");
            Console.Write("Please type the ID (GUID) for the lead => ");
            Guid id;
            if (!Guid.TryParse(Console.ReadLine(), out id))
            {
                Console.WriteLine("Incorrect ID");
                return;
            }

            var request = new DeleteLeadRequest { LeadId = id };
            this.Client.ProcessRequest(request);
        }

        /// <summary>
        /// Handles the DeleteLeadResponse that is received from the response queue.
        /// </summary>
        /// <param name="response">The DeleteLeadResponse received after sending a DeleteLeadRequest.</param>
        private void ProcessDeleteLeadResponse(SdkResponse response)
        {
            var deleteLeadResponse = (DeleteLeadResponse)response;
            Console.WriteLine("Processing DeleteLeadResponse.");

            Console.WriteLine(deleteLeadResponse.Succeeded ? "Lead deleted" : "Failed to delete lead");
        }

        /// <summary>
        /// Demonstrates how to retrieve lead priorities.
        /// </summary>
        private void RetrieveLeadPriorities()
        {
            Console.WriteLine("This request retrieves a list of lead priorities.");
            var request = new RetrieveLeadPrioritiesRequest();
            this.Client.ProcessRequest(request);
        }

        /// <summary>
        /// Handles the RetrieveLeadPrioritiesResponse that is received from the response queue.
        /// </summary>
        /// <param name="response">The RetrieveLeadPrioritiesResponse received after sending a RetrieveLeadPrioritiesRequest.</param>
        private void ProcessRetrieveLeadPrioritiesResponse(SdkResponse response)
        {
            var retrieveLeadPrioritiesResponse = (RetrieveLeadPrioritiesResponse)response;
            Console.WriteLine("Processing RetrieveLeadPrioritiesResponse.");

            if (retrieveLeadPrioritiesResponse.Succeeded)
            {
                Console.WriteLine("List of lead priorities");
                Console.WriteLine("ID\t\t\t\t\tName");
                foreach (var priority in retrieveLeadPrioritiesResponse.LeadPriorities)
                {
                    Console.WriteLine(priority.Id + "\t" + priority.Name);
                }
            }
            else
            {
                Console.WriteLine("Failed to retrieve lead priorities");
            }
        }

        /// <summary>
        /// Demonstrates how to retrieve lead statuses.
        /// </summary>
        private void RetrieveLeadStatuses()
        {
            Console.WriteLine("This request retrieves a list of lead statuses.");
            var request = new RetrieveLeadStatusesRequest();
            this.Client.ProcessRequest(request);
        }

        /// <summary>
        /// Handles the RetrieveLeadStatusesResponse that is received from the response queue.
        /// </summary>
        /// <param name="response">The RetrieveLeadStatusesResponse received after sending a RetrieveLeadStatusesRequest.</param>
        private void ProcessRetrieveLeadStatusesResponse(SdkResponse response)
        {
            var retrieveLeadStatusesResponse = (RetrieveLeadStatusesResponse)response;
            Console.WriteLine("Processing RetrieveLeadStatusesResponse.");

            if (retrieveLeadStatusesResponse.Succeeded)
            {
                Console.WriteLine("List of lead statuses");
                Console.WriteLine("ID\t\t\t\t\tName");
                foreach (var status in retrieveLeadStatusesResponse.LeadStatuses)
                {
                    Console.WriteLine(status.Id + "\t" + status.Name);
                }
            }
            else
            {
                Console.WriteLine("Failed to retrieve lead statuses");
            }
        }

        /// <summary>
        /// Demonstrates how to retrieve territories.
        /// </summary>
        private void RetrieveTerritories()
        {
            Console.WriteLine("This request retrieves a list of territories.");
            var request = new RetrieveTerritoriesRequest();
            this.Client.ProcessRequest(request);
        }

        /// <summary>
        /// Handles the RetrieveTerritoriesResponse that is received from the response queue.
        /// </summary>
        /// <param name="response">The RetrieveTerritoriesResponse received after sending a RetrieveTerritoriesRequest.</param>
        private void ProcessRetrieveTerritoriesResponse(SdkResponse response)
        {
            var retrieveTerritoriesResponse = (RetrieveTerritoriesResponse)response;
            Console.WriteLine("Processing RetrieveTerritoriesResponse.");

            if (retrieveTerritoriesResponse.Succeeded)
            {
                Console.WriteLine("List of territories");
                Console.WriteLine("ID\t\t\t\t\tName");
                foreach (var territory in retrieveTerritoriesResponse.Territories)
                {
                    Console.WriteLine(territory.Id + "\t" + territory.Name);
                }
            }
            else
            {
                Console.WriteLine("Failed to retrieve territories");
            }
        }

        /// <summary>
        /// Demonstrates how to retrieve sales ratings.
        /// </summary>
        private void RetrieveSalesRatings()
        {
            Console.WriteLine("This request retrieves a list of sales ratings.");
            var request = new RetrieveSalesRatingsRequest();
            this.Client.ProcessRequest(request);
        }

        /// <summary>
        /// Handles the RetrieveSalesRatingsResponse that is received from the response queue.
        /// </summary>
        /// <param name="response">The RetrieveSalesRatingsResponse received after sending a RetrieveSalesRatingsRequest.</param>
        private void ProcessRetrieveSalesRatingsResponse(SdkResponse response)
        {
            var retrieveSalesRatingsResponse = (RetrieveSalesRatingsResponse)response;
            Console.WriteLine("Processing RetrieveSalesRatingsResponse.");

            if (retrieveSalesRatingsResponse.Succeeded)
            {
                Console.WriteLine("List of sales ratings");
                Console.WriteLine("ID\t\t\t\t\tName");
                foreach (var salesRating in retrieveSalesRatingsResponse.SalesRatings)
                {
                    Console.WriteLine(salesRating.Id + "\t" + salesRating.Name);
                }
            }
            else
            {
                Console.WriteLine("Failed to retrieve sales ratings");
            }
        }

        /// <summary>
        /// Demonstrates how to retrieve multiple leads.
        /// </summary>
        private void RetrieveLeads()
        {
            Console.WriteLine("This request will retrieve multiple Leads.");
            Console.Write("Filter on Origin of changes =>");
            var originOfChange = Console.ReadLine();

            Console.Write("Enter offset - or empty for the first set of records =>");
            var offset = Console.ReadLine();
            int skipNumberOfRecords = 0;
            int.TryParse(offset, out skipNumberOfRecords);

            var request = new RetrieveLeadsRequest { MaxNumberOfRecordsToGet = 100, OriginOfChange = originOfChange, SkipNumberOfRecords = skipNumberOfRecords };
            this.Client.ProcessRequest(request);
        }

        /// <summary>
        /// Handles the RetrieveLeadsResponse that is received from the response queue. Displays the leads.
        /// </summary>
        /// <param name="response">The RetrieveLeadsResponse received after sending a RetrieveLeadsRequest.</param>
        private void ProcessRetrieveLeadsResponse(SdkResponse response)
        {
            var retrieveLeadsResponse = (RetrieveLeadsResponse)response;
            Console.WriteLine("Processing RetrieveLeadsResponse.");

            var counter = 1;
            foreach (var lead in retrieveLeadsResponse.Leads)
            {
                Console.WriteLine("\nLead #{0}", counter++);
                this.PrintLead(lead);
            }
        }

        /// <summary>
        /// Handles the <see cref="SdkErrorResponse"/> received from the response queue. Displays the error message.
        /// </summary>
        /// <param name="response">The <see cref="SdkErrorResponse"/> received after sending an <see cref="SdkRequest"/>.</param>
        private void ProcessSdkErrorResponse(SdkResponse response)
        {
            var sdkErrorResponse = (SdkErrorResponse)response;
            Console.WriteLine("An SdkErrorResponse was received.");
            Console.WriteLine("Error message: {0}", sdkErrorResponse.Message);
        }
    }
}

Troubleshooting

  • If the response isn’t received in time, you’ll get the following error message:

    “The request has been sent but the response was not received. You may want to wait a few more seconds and try to receive the response again or try increasing the ResponseMessageTimeout in client.cs. “

    Some of the possible reasons why the response wasn’t received:

    • The server took longer than expected to process this response. Try selecting Option A, to see the response. If this issue occurs frequently, consider changing the value of the ResponseMessageTimeout constant in your client.cs file.

    • Either your client is looking at the wrong response queue, or Microsoft Dynamics Marketing is unable to write to the response queue due to a configuration error. To learn how to set up your queues correctly, see Getting started with the SDK.

  • If you don’t receive a response immediately, try using the Get all responses for this session option. Sometimes a response may take longer than the default time-out period.

  • If you never receive the response, make sure your request and response queue names and namespace match the details you provided on Home > Settings > Administrator > Integration Options. More information: Site configuration and integration settings.

See Also

Microsoft.Dynamics.Marketing.SDK.Common
Microsoft.Dynamics.Marketing.SDK.Messages
Microsoft.Dynamics.Marketing.SDK.Messages.Lead
Microsoft.Dynamics.Marketing.SDK.Model
Developer overview of Microsoft Dynamics Marketing
Manage leads, contacts, and company
Getting started with the SDK
Quick start with sample code
Sample code
Assembly included in the Microsoft Dynamics Marketing SDK
Programming reference for Microsoft Dynamics Marketing