Sample: Create and update external entities

 

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\ExternalEntitySample

Requirements

Note

This sample works with your live production data. It might add, update, or delete external entities in your Microsoft Dynamics Marketing environment.

Demonstrates

This sample demonstrates how to create, update, and delete external entities using Dynamics Marketing.

Example

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

    /// <summary>
    /// Demonstrates how to manipulate external entities via the SDK.
    /// </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 external entities.
    /// </remarks>
    public class ExternalEntitySample : SdkSample
    {
        /// <summary>
        /// Starting point for the sample.
        /// </summary>
        /// <param name="args">Arguments needed for authentication.</param>
        public static void Main(string[] args)
        {
            try
            {
                // Creates the QueueClientProvider that will connect to the queues, test them, and then provide them to the client when needed.
                var queueClientProvider = CreateQueueClientProviderFromArgs(args);

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

        /// <summary>
        /// Initializes a new instance of the <see cref="ExternalEntitySample"/> class.
        /// </summary>
        /// <param name="queueClientProvider">The QueueClientProvider that is set up to connect to the SDK queues configured in Microsoft Dynamics Marketing.</param>
        public ExternalEntitySample(IQueueClientProvider queueClientProvider)
        {
            var responseHandlerMapping = new Dictionary<Type, Client.ResponseHandler>
            {
               { typeof(CreateOrUpdateExternalEntityResponse), this.ProcessCreateOrUpdateExternalEntityResponse },
               { typeof(RetrieveExternalEntityResponse), this.ProcessRetrieveExternalEntityResponse },
               { typeof(RetrieveExternalEntityTypesResponse), this.ProcessRetrieveExternalEntityTypesResponse },
               { typeof(RetrieveExternalIdsResponse), this.ProcessRetrieveExternalEntityIds },
               { typeof(DeleteExternalEntityResponse), this.ProcessDeleteExternalEntityResponse },
               { typeof(DeleteExternalEntityTypeResponse), this.ProcessDeleteExternalEntityTypeResponse }
            };

            this.SetupClient(queueClientProvider, responseHandlerMapping);

            this.SampleMenuActions = new Dictionary<string, Tuple<string, Action>>
            {
                { "1", new Tuple<string, Action>("CreateOrUpdateExternal Entity", this.CreateOrUpdateExternalEntity) },
                { "2", new Tuple<string, Action>("Retrieve Entity", this.RetrieveExternalEntity) },
                { "3", new Tuple<string, Action>("Retrieve Entity types.", this.RetrieveExternalEntityTypes) },
                { "4", new Tuple<string, Action>("Retrieve Entity IDs", this.RetrieveExternalEntityIds) },
                { "5", new Tuple<string, Action>("Delete single entity", this.DeleteExternalEntity) },
                { "6", new Tuple<string, Action>("Delete category", this.DeleteExternalEntityType) }
            };
        }

        /// <summary>
        /// Demonstrates CreateOrUpdateExternalEntityRequest and CreateOrUpdateExternalEntityResponse.
        /// </summary>
        private void CreateOrUpdateExternalEntity()
        {
            Console.WriteLine("This request creates or updates an external entity of a given type and external id.");
            Console.Write("Category:");
            var externalEntityType = Console.ReadLine();

            Console.Write("Name:");
            var name = Console.ReadLine();

            Console.Write("External id:");
            var externalid = Console.ReadLine();

            var request = new CreateOrUpdateExternalEntityRequest()
            {
                ExternalEntity = new ExternalEntity
                {
                    Name = name,
                    Active = true,
                    ExternalId = externalid,
                    CategoryName = externalEntityType
                }
            };

            this.Client.ProcessRequest(request);
        }

        /// <summary>
        /// Handles the CreateOrUpdateExternalEntityResponse received from the response queue.
        /// </summary>
        /// <param name="response">The CreateOrUpdateExternalEntityResponse received after sending an CreateOrUpdateExternalEntityRequest.</param>
        private void ProcessCreateOrUpdateExternalEntityResponse(SdkResponse response)
        {
            var createOrUpdateExternalEntityResponse = (CreateOrUpdateExternalEntityResponse)response;
            Console.WriteLine("Processing CreateOrUpdateExternalEntityResponse.");

            var externalEntity = createOrUpdateExternalEntityResponse.ExternalEntity;
            if (externalEntity != null)
            {
                Console.WriteLine("Inserted/Updated external entity: {0}", externalEntity.Name);
            }
            else
            {
                Console.WriteLine("Something went wrong : {0}", createOrUpdateExternalEntityResponse.Message);
            }
        }

        /// <summary>
        /// Demonstrates the RetrieveExternalEntityRequest and RetrieveExternalEntityResponse.
        /// </summary>
        private void RetrieveExternalEntity()
        {
            Console.WriteLine("This request retrieves an external entity of a given type and external id.");
            Console.Write("Category:");
            var externalEntityCategory = Console.ReadLine();

            Console.Write("External id:");
            var externalid = Console.ReadLine();

            var request = new RetrieveExternalEntityRequest()
            {
                CategoryName = externalEntityCategory,
                ExternalId = externalid
            };

            this.Client.ProcessRequest(request);
        }

        /// <summary>
        /// Handles the RetrieveExternalEntityResponse received from the response queue.
        /// </summary>
        /// <param name="response">The RetrieveExternalEntityResponse received after sending a RetrieveExternalEntityResponse.</param>
        private void ProcessRetrieveExternalEntityResponse(SdkResponse response)
        {
            var retrieveExternalEntityResponse = (RetrieveExternalEntityResponse)response;
            Console.WriteLine("Processing RetrieveExternalEntityResponse.");

            var externalEntity = retrieveExternalEntityResponse.ExternalEntity;
            if (externalEntity != null)
            {
                this.DisplayEntity(externalEntity);
            }
            else
            {
                Console.WriteLine("Something went wrong : {0}", retrieveExternalEntityResponse.Message);
            }
        }

        /// <summary>
        /// Demonstrates the RetrieveExternalEntityTypesRequest and RetrieveExternalEntityTypesResponse.
        /// </summary>
        private void RetrieveExternalEntityTypes()
        {
            Console.WriteLine("This request retrieves all external entity types.");
            var request = new RetrieveExternalEntityTypesRequest()
            {
            };

            this.Client.ProcessRequest(request);
        }

        /// <summary>
        /// Handles the RetrieveExternalEntityTypesResponse received from the response queue.
        /// </summary>
        /// <param name="response">The RetrieveExternalEntityResponse received after sending a RetrieveExternalEntityResponse.</param>
        private void ProcessRetrieveExternalEntityTypesResponse(SdkResponse response)
        {
            var retrieveExternalEntityResponse = (RetrieveExternalEntityTypesResponse)response;
            Console.WriteLine("Processing RetrieveExternalEntityTypesResponse.");

            Console.WriteLine("Received {0} types of external entities.", retrieveExternalEntityResponse.ExternalEntityTypes.Count());
            foreach (var typeName in retrieveExternalEntityResponse.ExternalEntityTypes)
            {
                Console.WriteLine(typeName);
            }
        }

        /// <summary>
        /// Handles the RetrieveExternalEntityTypesResponse received from the response queue.
        /// </summary>
        /// <param name="response">The RetrieveExternalEntityResponse received after sending a RetrieveExternalEntityResponse.</param>
        private void ProcessRetrieveExternalEntityIds(SdkResponse response)
        {
            var retrieveExternalEntityResponse = (RetrieveExternalIdsResponse)response;
            Console.WriteLine("Processing RetrieveExternalIdsResponse.");

            Console.WriteLine("Received {0} entity Ids.", retrieveExternalEntityResponse.ExternalIds.Count());
            foreach (var id in retrieveExternalEntityResponse.ExternalIds)
            {
                Console.WriteLine(id);
            }
        }

        /// <summary>
        /// Demonstrates the RetrieveExternalEntityTypesRequest and RetrieveExternalEntityTypesResponse.
        /// </summary>
        private void RetrieveExternalEntityIds()
        {
            Console.WriteLine("This request retrieves all ids of external entities of a given category.");
            Console.Write("Category:");
            var externalEntityCategory = Console.ReadLine();

            var request = new RetrieveExternalIdsRequest()
            {
                CategoryName = externalEntityCategory
            };

            this.Client.ProcessRequest(request);
        }

        /// <summary>
        /// Handles the RetrieveExternalIdsResponse received from the response queue.
        /// </summary>
        /// <param name="response">The RetrieveExternalIdsResponse received after sending a RetrieveExternalIdsRequest.</param>
        private void ProcessRetrieveExternalIdsResponse(SdkResponse response)
        {
            var retrieveExternalIdsResponse = (RetrieveExternalIdsResponse)response;
            Console.WriteLine("Processing RetrieveExternalIdsResponse.");

            Console.WriteLine("Received {0} entity Ids.", retrieveExternalIdsResponse.ExternalIds.Count());
            foreach (var externalId in retrieveExternalIdsResponse.ExternalIds)
            {
                Console.WriteLine(externalId);
            }
        }

        /// <summary>
        /// Demonstrates DeleteExternalEntityRequest and DeleteExternalEntityResponse.
        /// </summary>
        private void DeleteExternalEntity()
        {
            Console.WriteLine("This request deletes a single external entity given category and external id.");
            Console.Write("Category:");
            var category = Console.ReadLine();

            Console.Write("External id:");
            var externalid = Console.ReadLine();

            var request = new DeleteExternalEntityRequest()
            {
                ExternalId = externalid,
                CategoryName = category
            };

            this.Client.ProcessRequest(request);
        }

        /// <summary>
        /// Handles the DeleteExternalEntityResponse received from the response queue.
        /// </summary>
        /// <param name="response">The DeleteExternalEntityResponse received after sending a DeleteExternalEntityRequest.</param>
        private void ProcessDeleteExternalEntityResponse(SdkResponse response)
        {
            var deleteExternalEntityResponse = (DeleteExternalEntityResponse)response;
            Console.WriteLine("Processing DeleteExternalEntityResponse.");

            if (deleteExternalEntityResponse.Succeeded)
            {
                Console.WriteLine("{0}", deleteExternalEntityResponse.Message);
            }
            else
            {
                Console.WriteLine("Something went wrong : {0}", deleteExternalEntityResponse.Message);
            }
        }

        /// <summary>
        /// Demonstrates DeleteExternalEntityTypeRequest and DeleteExternalEntityTypeResponse.
        /// </summary>
        private void DeleteExternalEntityType()
        {
            Console.WriteLine("This request deletes a category of external entities.");
            Console.Write("Category:");
            var category = Console.ReadLine();

            var request = new DeleteExternalEntityTypeRequest()
            {
                CategoryName = category
            };

            this.Client.ProcessRequest(request);
        }

        /// <summary>
        /// Handles the DeleteExternalEntityTypeResponse received from the response queue.
        /// </summary>
        /// <param name="response">The DeleteExternalEntityTypeResponse received after sending a DeleteExternalEntityTypeRequest.</param>
        private void ProcessDeleteExternalEntityTypeResponse(SdkResponse response)
        {
            var deleteExternalEntityTypeResponse = (DeleteExternalEntityTypeResponse)response;
            Console.WriteLine("Processing DeleteExternalEntityTypeResponse.");

            if (deleteExternalEntityTypeResponse.Succeeded)
            {
                Console.WriteLine("{0}", deleteExternalEntityTypeResponse.Message);
            }
            else
            {
                Console.WriteLine("Something went wrong : {0}", deleteExternalEntityTypeResponse.Message);
            }
        }

        /// <summary>
        /// Displays the data of the given external entity.
        /// </summary>
        /// <param name="externalEntity">The external entity to display.</param>
        private void DisplayEntity(ExternalEntity externalEntity)
        {
            Console.WriteLine(
                @"
                External Id: {0}
                Category: {1}
                Active: {2}
                ",
                externalEntity.ExternalId,
                externalEntity.CategoryName,
                externalEntity.Active);
        }
    }
}

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.Model
Microsoft.Dynamics.Marketing.SDK.Messages.ExternalEntity
Developer overview of Microsoft Dynamics Marketing
Provide customized data to your users
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