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

 

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

Requirements

Note

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

Demonstrates

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

Example

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

        /// <summary>
        /// Initializes a new instance of the <see cref="EventAttendanceSample"/> class.
        /// </summary>
        /// <param name="queueClientProvider">
        /// The QueueClientProvider that’s set up to connect to the SDK queues configured in Microsoft Dynamics Marketing.
        /// </param>
        public EventAttendanceSample(IQueueClientProvider queueClientProvider)
        {
            this.updateRequestSent = false;
            var responseHandlerMapping = new Dictionary<Type, Client.ResponseHandler>
            {
                { typeof(RetrieveEventAttendanceResponse), this.ProcessRetrieveEventAttendanceResponse },
                { typeof(CreateOrUpdateEventAttendanceResponse), this.ProcessCreateOrUpdateEventAttendanceResponse },
                { typeof(CancelEventAttendanceResponse), this.ProcessCancelEventAttendanceResponse },
                { typeof(RetrieveEventAttendanceStatusesResponse), this.ProcessRetrieveEventAttendanceStatusesResponse },
                { typeof(RetrieveEventAttendancesResponse), this.ProcessRetrieveEventAttendancesResponse },
                { typeof(SdkErrorResponse), this.ProcessSdkErrorResponse }
            };

            this.SetupClient(queueClientProvider, responseHandlerMapping);

            this.SampleMenuActions = new Dictionary<string, Tuple<string, Action>>
            {
                { "1", new Tuple<string, Action>("Retrieve an event attendance", this.RetrieveEventAttendance) },
                { "2", new Tuple<string, Action>("Create an event attendance", this.CreateEventAttendance) },
                { "3", new Tuple<string, Action>("Update an event attendance", this.UpdateEventAttendance) },
                { "4", new Tuple<string, Action>("Cancel an event attendance", this.CancelEventAttendance) },
                { "5", new Tuple<string, Action>("Retrieve a list of event attendance statuses", this.RetrieveEventAttendanceStatuses) },
                { "6", new Tuple<string, Action>("Retrieve a list of event attendances", this.RetrieveEventAttendances) }
            };
        }

        /// <summary>
        /// Demonstrates RetrieveEventAttendancesRequest and RetrieveEventAttendancesResponse.
        /// </summary>
        private void RetrieveEventAttendances()
        {
            Console.WriteLine("This request retrieves a list of event attendances.");

            Guid? contactGuid = null;
            Guid? eventGuid = null;
            Guid? sessionGuid = null;
            Guid? eventItemGuid = null;
            int skipNumberOfRecords;

            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 =>");
            var offset = Console.ReadLine();
            int.TryParse(offset, out skipNumberOfRecords);
            var request = new RetrieveEventAttendancesRequest
            {
                MaxNumberOfRecords = 100,
                SkipNumberOfRecords = skipNumberOfRecords,
                ContactId = contactGuid,
                EventId = eventGuid,
                SessionId = sessionGuid,
                RegistrationSetupId = eventItemGuid
            };
            Client.ProcessRequest(request);
        }

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

        /// <summary>
        /// Handles the RetrieveEventAttendanceResponse that is received from the response queue. Displays the eventAttendance
        /// </summary>
        /// <param name="response">The RetrieveEventAttendanceResponse received after sending a RetrieveEventAttendanceRequest.</param>
        private void ProcessRetrieveEventAttendanceResponse(SdkResponse response)
        {
            var retrieveEventAttendanceResponse = (RetrieveEventAttendanceResponse)response;
            Console.WriteLine("Processing RetrieveEventAttendanceResponse.");

            if (this.updateRequestSent)
            {
                if (retrieveEventAttendanceResponse.Succeeded)
                {
                    Console.WriteLine("Old count for event attendance: {0}",
                        retrieveEventAttendanceResponse.EventAttendance.Count);
                    Console.Write("Please type the new count for the event attendance => ");
                    var count = Console.ReadLine();
                    double countvalue = 0.0;
                    if (string.IsNullOrEmpty(count) || !double.TryParse(count, out countvalue))
                    {
                        Console.WriteLine("Incorrect Value (Please enter a number.)");
                        return;
                    }

                    var eventAttendance = retrieveEventAttendanceResponse.EventAttendance;
                    eventAttendance.Count = countvalue;
                    var request = new CreateOrUpdateEventAttendanceRequest {EventAttendance = eventAttendance};
                    this.Client.ProcessRequest(request);
                }
                else
                {
                    Console.WriteLine("Request processing failed: " + retrieveEventAttendanceResponse.Message);
                }
            }
            else
            {
                this.PrintEventAttendance(retrieveEventAttendanceResponse.EventAttendance);
            }
        }

        /// <summary>
        /// Handles the RetrieveEventAttendancesResponse that is received from the response queue. Displays the eventAttendances
        /// </summary>
        /// <param name="response">The RetrieveEventAttendancesResponse received after sending a RetrieveEventAttendancesRequest.</param>
        private void ProcessRetrieveEventAttendancesResponse(SdkResponse response)
        {
            var retrieveEventAttendancesResponse = (RetrieveEventAttendancesResponse)response;
            Console.WriteLine("Processing RetrieveEventAttendancesResponse.");

            if (retrieveEventAttendancesResponse.Succeeded)
            {
                retrieveEventAttendancesResponse.EventAttendances.ToList().ForEach(PrintEventAttendance);
            }
            else
            {
                Console.WriteLine("Request processing failed: " + retrieveEventAttendancesResponse.Message);
            }
        }

        /// <summary>
        /// Print the content of an eventAttendance
        /// </summary>
        /// <param name="eventAttendance">The eventAttendance</param>
        private void PrintEventAttendance(EventAttendance eventAttendance)
        {
            foreach (var propertyInfo in eventAttendance.GetType().GetProperties().ToList())
            {
                var value = propertyInfo.GetValue(eventAttendance);
                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;
                }

                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("{0} Id: {1}", customField.Key, category.Id);
                            Console.WriteLine("{0} Name: {1}", customField.Key, category.Name);
                        }
                        else
                        {
                            Console.WriteLine("{0} : {1}", customField.Key, customField.Value);
                        }
                    }
                }
                else
                {
                    Console.WriteLine("{0} : {1}", propertyInfo.Name, value);
                }
            }
        }

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

            Console.Write("Please type the ID (GUID) for the contact for new event attendance => ");
            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 attendance => ");
            Guid eventId;
            if (!Guid.TryParse(Console.ReadLine(), out eventId))
            {
                Console.WriteLine("Incorrect event ID");
                return;
            }

            var eventAttendance = new EventAttendance
            {
                Id = id,
                Event = new Event { Id = eventId },
                Contact = new Contact { Id = contactId },
                CreateDate = DateTime.UtcNow
            };

            var request = new CreateOrUpdateEventAttendanceRequest { EventAttendance = eventAttendance };
            this.Client.ProcessRequest(request);
        }

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

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

        /// <summary>
        /// Handles the CreateOrUpdateEventAttendanceResponse that is received from the response queue. Displays the event attendance.
        /// </summary>
        /// <param name="response">The CreateOrUpdateEventAttendanceResponse received after sending a CreateOrUpdateEventAttendanceRequest.</param>
        private void ProcessCreateOrUpdateEventAttendanceResponse(SdkResponse response)
        {
            var upsertEventAttendanceResponse = (CreateOrUpdateEventAttendanceResponse)response;
            Console.WriteLine("Processing CreateOrUpdateEventAttendanceResponse.");

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

            Console.WriteLine("The create/update event attendance");
            this.PrintEventAttendance(upsertEventAttendanceResponse.EventAttendance);
            this.updateRequestSent = false;
        }

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

            var request = new CancelEventAttendanceRequest { EventAttendanceId = id };
            this.Client.ProcessRequest(request);
        }

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

            Console.WriteLine(cancelEventAttendanceResponse.Succeeded ? "Event attendance canceled" : "Failed to cancel event attendance");
        }

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

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

            if (retrieveEventAttendanceStatusesResponse.Succeeded)
            {
                Console.WriteLine("List of event attendance statuses");
                Console.WriteLine("ID\t\t\t\t\tName");
                foreach (var status in retrieveEventAttendanceStatusesResponse.EventAttendanceStatuses)
                {
                    Console.WriteLine("{0}\t{1}", status.Id, status.Name);
                }
            }
            else
            {
                Console.WriteLine("Failed to retrieve event attendance statuses");
            }
        }

        /// <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