Sample: Create, read, and update a category

 

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

Requirements

Note

This sample works with your live production data. It may create real contacts, companies, or leads in your Microsoft Dynamics Marketing environments.

Demonstrates

This sample demonstrates how to create or update categories using Microsoft Dynamics Marketing. Using the SDK, you can only manipulate categories that are available as part of custom fields. You can't use the API messages to work with ordinary categories.

Example

namespace Microsoft.Dynamics.Marketing.SDK.Samples.CategorySample
{
    using System;
    using System.Globalization;
    using System.Collections.Generic;
    using Microsoft.Dynamics.Marketing.SDK.Model;
    using Microsoft.Dynamics.Marketing.SDK.Common;
    using Microsoft.Dynamics.Marketing.SDK.Messages;
    using Microsoft.Dynamics.Marketing.SDK.Messages.Category;
    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 a Category 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 Category.
    /// </remarks>
    public class CategorySample : SdkSample
    {
        /// <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 CategorySample(queueClientProvider);
                sample.Run();
            }
            catch (Exception ex)
            {
                CategorySample.WriteException(ex);
                Console.WriteLine("Press Enter key to exit.");
                Console.ReadLine();
            }
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="CategorySample"/> class.
        /// </summary>
        /// <param name="queueClientProvider">
        /// The QueueClientProvider that’s set up to connect to the SDK queues configured in Microsoft Dynamics Marketing.
        /// </param>
        public CategorySample(IQueueClientProvider queueClientProvider)
        {
            var responseHandlerMapping = new Dictionary<Type, Client.ResponseHandler>
            {
                { typeof(CreateOrUpdateCustomFieldCategoriesResponse), this.ProcessCreateOrUpdateCustomFieldCategoriesResponse },
                { typeof(RetrieveCategoryValuesResponse), this.ProcessRetrieveCustomFieldCategoryValuesResponse },
                { typeof(SdkErrorResponse), this.ProcessSdkErrorResponse }
            };

            this.SetupClient(queueClientProvider, responseHandlerMapping);

            this.SampleMenuActions = new Dictionary<string, Tuple<string, Action>>
            {
                { "1", new Tuple<string, Action>("Create/Update user defined categories", this.CreateOrUpdateUserDefinedCategories) },
                { "2", new Tuple<string, Action>("Retrieve custom fields category values", this.RetrieveCategoryValues) }
            };
        }

        /// <summary>
        /// Demonstrates how to create or update custom categories.
        /// </summary>
        private void CreateOrUpdateUserDefinedCategories()
        {
            Console.WriteLine("This request creates or updates a custom category.");
            Console.Write("Please type the entity type name for custom category => ");
            string entityTypeName = Console.ReadLine();
            if (string.IsNullOrEmpty(entityTypeName))
            {
                Console.WriteLine("Incorrect entity type name");
                return;
            }

            Console.Write("Please type in the name of the custom field => ");
            var fieldName = Console.ReadLine();

            var categories = this.MultiQuestionRequest(
                "Do you want to add a category to the request? (y/n) =>",
                () =>
                {
                    Console.Write("Please type the id for the Category => ");
                    var categoryId = Console.ReadLine();
                    if (string.IsNullOrEmpty(categoryId))
                    {
                        Console.WriteLine("Incorrect Id");
                        return new KeyValuePair<string, string>();
                    }

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

                    return new KeyValuePair<string, string>(categoryId, categoryName);
                });

            var request = new CreateOrUpdateCustomFieldCategoriesRequest
            {
                EntityTypeName = entityTypeName,
                FieldName = fieldName,
                Values = categories
            };

            this.Client.ProcessRequest(request);
        }

        /// <summary>
        /// Demonstrates how to retrieve custom field category values.
        /// </summary>
        private void RetrieveCategoryValues()
        {
            Console.WriteLine("This request retrieves custom field category values.");
            Console.Write("Please type the entity type name for the custom category => ");
            var entityTypeNameInput = Console.ReadLine();
            CategoryValueEntityType entityTypeName;
            var isEnumValid = Enum.TryParse(entityTypeNameInput, out entityTypeName);

            if (string.IsNullOrEmpty(entityTypeNameInput) && !isEnumValid)
            {
                Console.WriteLine("Incorrect entity type name");
                return;
            }

            Console.Write("Please type in the name of the custom field => ");
            var fieldName = Console.ReadLine();

            var companyId = Guid.Empty;
            var languageCode = string.Empty;

            if (entityTypeName == CategoryValueEntityType.Contact)
            {
                Console.Write("Please type in the desired company id => ");
                Guid.TryParse(Console.ReadLine(), out companyId);

                Console.Write("Please type in the desired language => ");
                languageCode = Console.ReadLine();
            }

            var request = new RetrieveCategoryValuesRequest
            {
                EntityTypeName = entityTypeName,
                FieldName = fieldName,
                BelongsToCompanyId = companyId,
                Language = languageCode
            };

            this.Client.ProcessRequest(request);
        }

        /// <summary>
        /// Handles the <see cref="CreateOrUpdateCustomFieldCategoriesResponse"/> that is received from the response queue.
        /// </summary>
        /// <param name="response">The <see cref="CreateOrUpdateCustomFieldCategoriesResponse"/> received after sending a <see cref="CreateOrUpdateCustomFieldCategoriesRequest"/>.</param>
        private void ProcessCreateOrUpdateCustomFieldCategoriesResponse(SdkResponse response)
        {
            var createOrUpdateCustomFieldCategoriesResponse = (CreateOrUpdateCustomFieldCategoriesResponse)response;
            Console.WriteLine("Processing CreateOrUpdateCustomFieldCategoriesResponse.");

            if (!createOrUpdateCustomFieldCategoriesResponse.Succeeded)
            {
                Console.WriteLine("Failed to create/update custom categories");
                return;
            }

            Console.WriteLine("Succeeded to create/update custom categories");
        }

        /// <summary>
        /// Handles the <see cref="CreateOrUpdateCustomFieldCategoriesResponse"/> that is received from the response queue.
        /// </summary>
        /// <param name="response">The <see cref="CreateOrUpdateCustomFieldCategoriesResponse"/> received after sending a <see cref="CreateOrUpdateCustomFieldCategoriesRequest"/>.</param>
        private void ProcessRetrieveCustomFieldCategoryValuesResponse(SdkResponse response)
        {
            var retrieveCategoryValuesResponse = (RetrieveCategoryValuesResponse)response;
            Console.WriteLine("Processing RetrieveCustomFieldCategoryValuesResponse.");

            if (!retrieveCategoryValuesResponse.Succeeded)
            {
                Console.WriteLine("Failed to retrieve category values");
                return;
            }

            var counter = 1;
            foreach (var categoryValue in retrieveCategoryValuesResponse.CategoryValues)
            {
                Console.WriteLine("\nCategory value #{0}", counter++);
                this.PrintCategoryValue(categoryValue);
            }

            Console.WriteLine("Succeeded to retrieve category values");
        }

        /// <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);
        }

        /// <summary>
        /// Prints the category value.
        /// </summary>
        /// <param name="value">The value.</param>
        private void PrintCategoryValue(CategoryValue value)
        {
            Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "Id: {0}", value.Id));
            Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "ValueName: {0}", value.ValueName));
            Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "Language: {0}", value.Language));
            Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "Active: {0}", value.Active));
            Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "Description: {0}", value.Description));
            Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "Account: {0}", value.Account));
        }
    }
}

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.Category
Developer overview of Microsoft Dynamics Marketing
Marketing lists and dynamic segmentation
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