Ejemplo: crear, leer, actualizar y cancelar el registro de eventos

Este código de muestra es para Microsoft Dynamics Marketing. El código de muestra se puede encontrar en la siguiente ubicación después de descargar e instalar el SDK de Microsoft Dynamics Marketing:

Samples\CS\EventRegistrationSample

Requisitos

noteNota
Este ejemplo funciona con sus datos de producción activa. Puede crear registros de eventos reales en el entorno de Microsoft Dynamics Marketing.

Demostraciones

Este ejemplo muestra cómo crear, recuperar, actualizar, y cancelar un registro de eventos con Microsoft Dynamics Marketing.

Ejemplo


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 = CreatQueueClientProviderFromArgs(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 }
            };

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

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

  • Si la respuesta no se recibe a tiempo, obtendrá el siguiente mensaje de error:



    "Se ha enviado la solicitud pero no se ha recibido la respuesta Puede que desee esperar unos segundos para intentar recibir la respuesta de nuevo o intentar aumentar el ResponseMessageTimeout en client.cs. “



    Algunas de las razones posibles por las que no se recibió la respuesta:

    • El servidor tardó más de lo esperado en procesar esta respuesta. Intente seleccionar la Opción A para ver la respuesta. Si este problema se produce con frecuencia, piense en cambiar el valor de la constante ResponseMessageTimeout en el archivo client.cs.

    • O bien, su cliente está mirando la cola de respuestas incorrecta, o Microsoft Dynamics Marketing no puede escribir en la cola de respuestas debido a un error de configuración. Para obtener información acerca de cómo configurar las horas correctamente, vea Introducción al SDK

  • Si no recibe una respuesta inmediatamente, intente usar la opción para obtener todas las respuestas para esta sesión. A veces una respuesta puede tardar más tiempo que el período de tiempo de espera predeterminado.

  • Si nunca recibe la respuesta, asegúrese de que su solicitud y espacio de nombres y nombres de colas de respuesta coinciden con los datos que ha proporcionado en Inicio > Configuración > Administrador > Opciones de integración. Más información: Configuración del sitio y configuración de integración.

Vea también


Envíe sus comentarios sobre este tema a Microsoft.
© 2015 Microsoft. Reservados todos los derechos.
Mostrar: