Sample: Create, read, update, and delete a company (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\CompanySample

Requirements

Note

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

Demonstrates

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

Example

namespace Microsoft.Dynamics.Marketing.SDK.Samples.CompanySample
{
    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.Company;
    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 Company entity.
    /// </summary>
    /// <remarks>
    /// Depending on which part of the sample you run, some prior setup 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 Company.
    /// </remarks>
    public class CompanySample : 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 CompanySample(queueClientProvider);
                sample.Run();
            }
            catch (Exception ex)
            {
                CompanySample.WriteException(ex);
                Console.WriteLine("Press Enter key to exit.");
                Console.ReadLine();
            }
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="CompanySample"/> class.
        /// </summary>
        /// <param name="queueClientProvider">
        /// The QueueClientProvider that is set up to connect to the SDK queues configured in Microsoft Dynamics Marketing.
        /// </param>
        public CompanySample(IQueueClientProvider queueClientProvider)
        {
            this.updateRequestSent = false;
            var responseHandlerMapping = new Dictionary<Type, Client.ResponseHandler>
            {
                { typeof(RetrieveCompanyResponse), this.ProcessRetrieveCompanyResponse },
                { typeof(CreateOrUpdateCompanyResponse), this.ProcessCreateOrUpdateCompanyResponse },
                { typeof(DeleteCompanyResponse), this.ProcessDeleteCompanyResponse },
                { typeof(ActivateCompanyResponse), this.ProcessActivateCompanyResponse },
                { typeof(RetrieveCompaniesResponse), this.ProcessRetrieveCompaniesResponse },
                { typeof(SdkErrorResponse), this.ProcessSdkErrorResponse }
            };

            this.SetupClient(queueClientProvider, responseHandlerMapping);

            this.SampleMenuActions = new Dictionary<string, Tuple<string, Action>>
            {
                { "1", new Tuple<string, Action>("Retrieve a Company", this.RetrieveCompany) },
                { "2", new Tuple<string, Action>("Create a Company", this.CreateCompany) },
                { "3", new Tuple<string, Action>("Update a Company", this.UpdateCompany) },
                { "4", new Tuple<string, Action>("Delete a Company", this.DeleteCompany) },
                { "5", new Tuple<string, Action>("Activate a Company", this.ActivateCompany) },
                { "6", new Tuple<string, Action>("Retrieve multiple Companies", this.RetrieveCompanies) },
            };
        }

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

        /// <summary>
        /// Handles the RetrieveCompanyResponse that is received from the response queue. Displays the company.
        /// </summary>
        /// <param name="response">The RetrieveCompanyResponse received after sending a RetrieveCompanyRequest.</param>
        private void ProcessRetrieveCompanyResponse(SdkResponse response)
        {
            var retrieveCompanyResponse = (RetrieveCompanyResponse)response;
            Console.WriteLine("Processing RetrieveCompanyResponse.");

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

                var company = retrieveCompanyResponse.Company;
                company.Name = name;
                var request = new CreateOrUpdateCompanyRequest { Company = company };
                this.Client.ProcessRequest(request);
            }
            else
            {
                this.PrintCompany(retrieveCompanyResponse.Company);
            }
        }

        /// <summary>
        /// Prints the content of a company.
        /// </summary>
        /// <param name="company">The company</param>
        private void PrintCompany(Company company)
        {
            foreach (var propertyInfo in company.GetType().GetProperties().ToList())
            {
                var value = propertyInfo.GetValue(company);
                var parentCompany = value as Company;
                if (parentCompany != null)
                {
                    Console.WriteLine(propertyInfo.Name + ":" + parentCompany.Id + " (" + parentCompany.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
                {
                    Console.WriteLine(propertyInfo.Name + ":" + value);
                }
            }
        }

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

            Console.Write("Please type the name for the new company => ");
            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 company belongs to => ");
            Guid belongsToCompanyId;
            if (!Guid.TryParse(Console.ReadLine(), out belongsToCompanyId))
            {
                Console.WriteLine("Incorrect belongs to ID");
                return;
            }

            var company = new Company
            {
                Id = id,
                Name = name,
                BelongsToCompany = new Company { Id = belongsToCompanyId },
                IsMarketing = true
            };

            var request = new CreateOrUpdateCompanyRequest { Company = company };
            this.Client.ProcessRequest(request);
        }

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

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

        /// <summary>
        /// Handles the <see cref="CreateOrUpdateCompanyResponse"/> that is received from the response queue. Displays the company.
        /// </summary>
        /// <param name="response">The <see cref="CreateOrUpdateCompanyResponse"/> received after sending a <see cref="CreateOrUpdateCompanyRequest"/>.</param>
        private void ProcessCreateOrUpdateCompanyResponse(SdkResponse response)
        {
            var createOrUpdateCompanyResponse = (CreateOrUpdateCompanyResponse)response;
            Console.WriteLine("Processing CreateOrUpdateCompanyResponse.");

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

            Console.WriteLine("The create/update Company");
            this.PrintCompany(createOrUpdateCompanyResponse.Company);
            this.updateRequestSent = false;
        }

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

            var request = new DeleteCompanyRequest { CompanyId = id };
            this.Client.ProcessRequest(request);
        }

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

            var request = new ActivateCompanyRequest { CompanyId = id };
            this.Client.ProcessRequest(request);
        }

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

            Console.WriteLine(deleteCompanyResponse.Succeeded ? "Company deleted" : "Failed to delete Company");
        }

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

            Console.WriteLine(activateCompanyResponse.Succeeded ? "Company activated" : "Failed to activate the Company");
        }

        /// <summary>
        /// Demonstrates how to retrieve multiple companies.
        /// </summary>
        private void RetrieveCompanies()
        {
            Console.WriteLine("This request will retrieve multiple Companies.");
            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 RetrieveCompaniesRequest { MaxNumberOfRecordsToGet = 100, OriginOfChange = originOfChange,SkipNumberOfRecords = skipNumberOfRecords, IncludeDeletedCompanies = true};
            this.Client.ProcessRequest(request);
        }

        /// <summary>
        /// Handles the RetrieveCompaniesResponse that is received from the response queue. Displays the companies.
        /// </summary>
        /// <param name="response">The RetrieveCompaniesResponse received after sending a RetrieveCompaniesRequest.</param>
        private void ProcessRetrieveCompaniesResponse(SdkResponse response)
        {
            var retrieveCompaniesResponse = (RetrieveCompaniesResponse)response;
            Console.WriteLine("Processing RetrieveCompaniesResponse.");

            var counter = 1;
            foreach (var company in retrieveCompaniesResponse.Companies)
            {
                Console.WriteLine("\nCompany #{0}", counter++);
                this.PrintCompany(company);
            }
        }

        /// <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.Model
Microsoft.Dynamics.Marketing.SDK.Messages.Company
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