Sample: Create, read, update, and cancel event registration

 

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

Requirements

Note

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

Demonstrates

This sample demonstrates how to create, retrieve, update, and cancel an event registration using Microsoft Dynamics Marketing.

Example

namespace Microsoft.Dynamics.Marketing.SDK.Samples.EventRegistrationSample
{
    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.Event;
    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 eventRegistration 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 eventRegistration.
    /// </remarks>
    public class EventRegistrationSample : 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 EventRegistrationSample(queueClientProvider);
                sample.Run();
            }
            catch (Exception ex)
            {
                EventRegistrationSample.WriteException(ex);
                Console.WriteLine("Press Enter key to exit.");
                Console.ReadLine();
            }
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="EventRegistrationSample"/> class.
        /// </summary>
        /// <param name="queueClientProvider">
        /// The QueueClientProvider that’s set up to connect to the SDK queues configured in Microsoft Dynamics Marketing.
        /// </param>
        public EventRegistrationSample(IQueueClientProvider queueClientProvider)
        {
            this.updateRequestSent = false;
            var responseHandlerMapping = new Dictionary<Type, Client.ResponseHandler>
            {
                { typeof(RetrieveEventRegistrationResponse), this.ProcessRetrieveEventRegistrationResponse },
                { typeof(CreateOrUpdateEventRegistrationResponse), this.ProcessCreateOrUpdateEventRegistrationResponse },
                { typeof(CancelEventRegistrationResponse), this.ProcessCancelEventRegistrationResponse },
                { typeof(SdkErrorResponse), this.ProcessSdkErrorResponse },
                { typeof(RetrieveEventRegistrationsResponse), this.ProcessRetrieveEventRegistrationsResponse },
            };

            this.SetupClient(queueClientProvider, responseHandlerMapping);

            this.SampleMenuActions = new Dictionary<string, Tuple<string, Action>>
            {
                { "1", new Tuple<string, Action>("Retrieve an event registration", this.RetrieveEventRegistration) },
                { "2", new Tuple<string, Action>("Create an event registration", this.CreateEventRegistration) },
                { "3", new Tuple<string, Action>("Update an event registration", this.UpdateEventRegistration) },
                { "4", new Tuple<string, Action>("Cancel an event registration", this.CancelEventRegistration) },
                { "5", new Tuple<string, Action>("Retrieve a collection of event registrations", this.RetrieveEventRegistrations) }
            };
        }

        /// <summary>
        /// Demonstrates RetrieveEventRegistrationRequest and RetrieveEventRegistrationResponse.
        /// </summary>
        private void RetrieveEventRegistration()
        {
            Console.WriteLine("This request retrieves an event registration.");
            Console.Write("Please type the ID (GUID) for the event registration to retrieve => ");
            Guid id;
            if (Guid.TryParse(Console.ReadLine(), out id))
            {
                var request = new RetrieveEventRegistrationRequest { EventRegistrationId = id };
                this.Client.ProcessRequest(request);
            }
            else
            {
                Console.WriteLine("Incorrect ID");
            }
        }

        /// <summary>
        /// Demonstrates RetrieveEventRegistrationsRequest and RetrieveEventRegistrationsResponse.
        /// </summary>
        private void RetrieveEventRegistrations()
        {
            Console.WriteLine("Processing RetrieveEventRegistrationsResponse. \n");

            Guid? contactGuid = null;
            Guid? eventGuid = null;
            Guid? sessionGuid = null;
            Guid? eventItemGuid = null;
            var skipNumberOfRecords = 0;

            Console.Write("Please type the ID (GUID) for event registrations's contact =>\n");
            var userChoice = Console.ReadLine();

            if (!string.IsNullOrEmpty(userChoice))
            {
                if (!GetGuid(userChoice, out contactGuid))
                {
                    Console.WriteLine("Incorrect ID");
                    return;
                }
            }

            Console.Write("Please type the ID (GUID) for event registrations's event =>\n");
            userChoice = Console.ReadLine();

            if (!string.IsNullOrEmpty(userChoice))
            {
                if (!GetGuid(userChoice, out eventGuid))
                {
                    Console.WriteLine("Incorrect ID");
                    return;
                }
            }

            Console.Write("Please type the ID (GUID) for event registrations's session =>\n");
            userChoice = Console.ReadLine();

            if (!string.IsNullOrEmpty(userChoice))
            {
                if (!GetGuid(userChoice, out sessionGuid))
                {
                    Console.WriteLine("Incorrect ID");
                    return;
                }
            }

            Console.Write("Please type the ID (GUID) for event registrations's EventItem =>\n");
            userChoice = Console.ReadLine();

            if (!string.IsNullOrEmpty(userChoice))
            {
                if (!GetGuid(userChoice, out eventItemGuid))
                {
                    Console.WriteLine("Incorrect ID");
                    return;
                }
            }

            Console.Write("Enter offset - or empty for the first set of records =>");
            userChoice = Console.ReadLine();

            if (!string.IsNullOrEmpty(userChoice))
            {
                if (!int.TryParse(userChoice, out skipNumberOfRecords))
                {
                    Console.WriteLine("Incorrect offset");
                    return;
                }
            }

            var request = new RetrieveEventRegistrationsRequest
            {
                ContactID = contactGuid,
                RegistrationSetupID = eventItemGuid,
                EventID = eventGuid,
                SessionID = sessionGuid,
                IncludeCanceled = true,
                MaxNumberOfRecords = 100,
                SkipNumberOfRecords = skipNumberOfRecords
            };

            this.Client.ProcessRequest(request);
        }

        /// <summary>
        /// Handles the RetrieveEventRegistrationResponse that is received from the response queue. Displays the eventRegistration.
        /// </summary>
        /// <param name="response">The RetrieveEventRegistrationResponse received after sending a RetrieveEventRegistrationRequest.</param>
        private void ProcessRetrieveEventRegistrationResponse(SdkResponse response)
        {
            var retrieveEventRegistrationResponse = (RetrieveEventRegistrationResponse)response;
            Console.WriteLine("Processing RetrieveEventRegistrationResponse.");

            if (this.updateRequestSent)
            {
                Console.WriteLine("Old registrant Id for event registration: {0} ", retrieveEventRegistrationResponse.EventRegistration.ForContact.Id);
                Console.Write("Please type the new registrant Id for the event registration => ");
                var forContactId = Console.ReadLine();
                var contactIdValue = new Guid();
                if (string.IsNullOrEmpty(forContactId) || !Guid.TryParse(forContactId, out contactIdValue))
                {
                    Console.WriteLine("Incorrect Value");
                    return;
                }

                var eventRegistration = retrieveEventRegistrationResponse.EventRegistration;
                eventRegistration.ForContact.Id = contactIdValue;
                var request = new CreateOrUpdateEventRegistrationRequest { EventRegistration = eventRegistration };
                this.Client.ProcessRequest(request);
            }
            else
            {
                this.PrintEventRegistration(retrieveEventRegistrationResponse.EventRegistration);
            }
        }

        /// <summary>
        /// Handles the RetrieveEventRegistrationsResponse that is received from the response queue. Displays the collection of eventRegistrations.
        /// </summary>
        /// <param name="response">The RetrieveEventRegistrationsResponse received after sending a RetrieveEventRegistrationsRequest.</param>
        private void ProcessRetrieveEventRegistrationsResponse(SdkResponse response)
        {
            var retrieveEventRegistrationsResponse = (RetrieveEventRegistrationsResponse)response;
            Console.WriteLine("Processing RetrieveEventRegistrationsResponse.\n");

            if (!retrieveEventRegistrationsResponse.Succeeded)
            {
                Console.WriteLine("Failed to retrieve event registrations because: \n");
                Console.WriteLine(retrieveEventRegistrationsResponse.Message);
                return;
            }

            Console.WriteLine("The collection of event registrations: \n");
            if (retrieveEventRegistrationsResponse.EventRegistrations.Any())
            {
                foreach (var registration in retrieveEventRegistrationsResponse.EventRegistrations)
                {
                    Console.WriteLine("");
                    this.PrintEventRegistration(registration);
                }
            }
            else
            {
                Console.WriteLine("The request didn't return any event registration that matches your search criteria!");
                return;
            }
        }

        /// <summary>
        /// Print the content of an event registration.
        /// </summary>
        /// <param name="eventRegistration">The eventRegistration</param>
        private void PrintEventRegistration(EventRegistration eventRegistration)
        {
            foreach (var propertyInfo in eventRegistration.GetType().GetProperties().ToList())
            {
                var value = propertyInfo.GetValue(eventRegistration);
                var objEvent = value as Event;
                if (objEvent != null)
                {
                    Console.WriteLine("{0} : {1} ( {2} )", propertyInfo.Name, objEvent.Id, objEvent.Name);
                    continue;
                }

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

                Console.WriteLine("{0} : {1}", propertyInfo.Name, value);
            }
        }

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

            Console.Write("Please type the ID (GUID) registrant ID for new event registration => ");
            Guid forContactId;
            if (!Guid.TryParse(Console.ReadLine(), out forContactId))
            {
                Console.WriteLine("Incorrect contact ID");
                return;
            }

            Console.Write("Please type the ID (GUID) registered by contact ID for new event registration => ");
            Guid contactId;
            if (!Guid.TryParse(Console.ReadLine(), out contactId))
            {
                Console.WriteLine("Incorrect contact ID");
                return;
            }

            Console.Write("Please type the ID (GUID) for the event for new event registration => ");
            Guid eventId;
            if (!Guid.TryParse(Console.ReadLine(), out eventId))
            {
                Console.WriteLine("Incorrect event ID");
                return;
            }

            var eventRegistration = new EventRegistration
            {
                Id = id,
                Event = new Event { Id = eventId },
                ForContact = new Contact { Id = forContactId },
                ByContact = new Contact { Id = contactId },
                RegistrationDate = DateTime.UtcNow,
                IsFree = false,
            };

            var request = new CreateOrUpdateEventRegistrationRequest { EventRegistration = eventRegistration };
            this.Client.ProcessRequest(request);
        }

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

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

        /// <summary>
        /// Handles the CreateOrUpdateEventRegistrationResponse that is received from the response queue. Displays the event registration.
        /// </summary>
        /// <param name="response">The CreateOrUpdateEventRegistrationResponse received after sending a CreateOrUpdateEventRegistrationRequest.</param>
        private void ProcessCreateOrUpdateEventRegistrationResponse(SdkResponse response)
        {
            var upsertEventRegistrationResponse = (CreateOrUpdateEventRegistrationResponse)response;
            Console.WriteLine("Processing CreateOrUpdateEventRegistrationResponse.");

            if (!upsertEventRegistrationResponse.Succeeded)
            {
                Console.WriteLine("Failed to create/update event registration");
                return;
            }

            Console.WriteLine("The create/update event registration");
            this.PrintEventRegistration(upsertEventRegistrationResponse.EventRegistration);
            this.updateRequestSent = false;
        }

        /// <summary>
        /// Demonstrates how to cancel an event registration.
        /// </summary>
        private void CancelEventRegistration()
        {
            Console.WriteLine("This request cancels an event registration.");
            Console.Write("Please type the ID (GUID) for the event registration => ");
            Guid id;
            if (!Guid.TryParse(Console.ReadLine(), out id))
            {
                Console.WriteLine("Incorrect ID");
                return;
            }

            var request = new CancelEventRegistrationRequest { EventRegistrationId = id };
            this.Client.ProcessRequest(request);
        }

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

            Console.WriteLine(cancelEventRegistrationResponse.Succeeded ? cancelEventRegistrationResponse.Message : "Failed to cancel event registration");
        }

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

        private static bool GetGuid(string guid, out Guid? value)
        {
            Guid parsedGuid;
            value = null;
            var suceess = Guid.TryParse(guid, out parsedGuid);
            if (suceess)
            {
                value = parsedGuid;
            }

            return suceess;
        }
    }
}

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.Event
Microsoft.Dynamics.Marketing.SDK.Model
Developer overview of Microsoft Dynamics Marketing
Manage event registration and attendance
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