Ejemplo: crear, leer, actualizar y eliminar los resultados de marketing

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

Requisitos

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

Demostraciones

Este ejemplo muestra cómo crear, recuperar, actualizar y eliminar un resultado de marketing con Dynamics Marketing.

Ejemplo


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

        /// <summary>
        /// Initializes a new instance of the <see cref="MarketingResultSample"/> class.
        /// </summary>
        /// <param name="queueClientProvider">
        /// The QueueClientProvider that’s set up to connect to the SDK queues configured in Microsoft Dynamics Marketing.
        /// </param>
        public MarketingResultSample(IQueueClientProvider queueClientProvider)
        {
            this.updateRequestSent = false;
            var responseHandlerMapping = new Dictionary<Type, Client.ResponseHandler>
            {
                { typeof(RetrieveMarketingResultResponse), this.ProcessRetrieveMarketingResultResponse },
                { typeof(RetrieveMarketingResultsResponse), this.ProcessRetrieveMarketingResultsResponse },
                { typeof(CreateOrUpdateMarketingResultResponse), this.ProcessCreateOrUpdateMarketingResultResponse },
                { typeof(DeleteMarketingResultResponse), this.ProcessDeleteMarketingResultResponse },
                { typeof(RetrieveMarketingResultTypesResponse), this.ProcessRetrieveMarketingResultTypesResponse },
                { typeof(SdkErrorResponse), this.ProcessSdkErrorResponse }
            };

            this.SetupClient(queueClientProvider, responseHandlerMapping);

            this.SampleMenuActions = new Dictionary<string, Tuple<string, Action>>
            {
                { "1", new Tuple<string, Action>("Retrieve a Marketing Result", this.RetrieveMarketingResult) },
                { "2", new Tuple<string, Action>("Create a Marketing Result", this.CreateMarketingResult) },
                { "3", new Tuple<string, Action>("Update a Marketing Result", this.UpdateMarketingResult) },
                { "4", new Tuple<string, Action>("Delete a Marketing Result", this.DeleteMarketingResult) },
                { "5", new Tuple<string, Action>("Retrieve a list of marketing result types", this.RetrieveMarketingResultTypes) },
                { "6", new Tuple<string, Action>("Retrieve multiple marketing results", this.RetrieveMarketingResults) },
            };
        }

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

        /// <summary>
        /// Handles the RetrieveMarketingResultResponse that is received from the response queue. Displays the results.
        /// </summary>
        /// <param name="response">The RetrieveMarketingResultResponse received after sending a RetrieveMarketingResultRequest.</param>
        private void ProcessRetrieveMarketingResultResponse(SdkResponse response)
        {
            var retrieveResultResponse = (RetrieveMarketingResultResponse)response;
            Console.WriteLine("Processing RetrieveMarketingResultResponse.");

            if (this.updateRequestSent)
            {
                Console.WriteLine("Old actual for result: " + retrieveResultResponse.MarketingResult.ActualValue);
                Console.Write("Please type the new actual for the result => ");
                var actual = Console.ReadLine();
                double actualValue;
                if (!Double.TryParse(actual, out actualValue))
                {
                    Console.WriteLine("Incorrect Actual Value");
                    return;
                }

                Console.WriteLine("Old forecast for result: " + retrieveResultResponse.MarketingResult.ActualValue);
                Console.Write("Please type the new forecast for the result => ");
                var forecast = Console.ReadLine();
                double forecastValue;
                if (!Double.TryParse(forecast, out forecastValue))
                {
                    Console.WriteLine("Incorrect Forecast Value");
                    return;
                }

                var result = retrieveResultResponse.MarketingResult;
                result.ActualValue = actualValue;
                result.ForecastValue = forecastValue;
                var request = new CreateOrUpdateMarketingResultRequest { MarketingResult = result };
                this.Client.ProcessRequest(request);
            }
            else
            {
                this.PrintMarketingResult(retrieveResultResponse.MarketingResult);
            }
        }

        /// <summary>
        /// Print the content of a marketing result.
        /// </summary>
        /// <param name="result">The result to display.</param>
        private void PrintMarketingResult(MarketingResult result)
        {
            var belongsToCompanyId = result.BelongsToCompany == null ? string.Empty : result.BelongsToCompany.Id.ToString();
            var contactId = result.Contact == null ? string.Empty : result.Contact.Id.ToString();
            var emailId = result.EmailMessage == null ? string.Empty : result.EmailMessage.Id.ToString();
            var jobId = result.Job == null ? string.Empty : result.Job.Id.ToString();
            var eventId = result.Event == null ? string.Empty : result.Event.Id.ToString();
            var campaignId = result.Campaign == null ? string.Empty : result.Campaign.Id.ToString();
            var programId = result.Program == null ? string.Empty : result.Program.Id.ToString();
            var resultTypeId = result.Type == null ? string.Empty : result.Type.Id.ToString();
            var originOfChanges = result.OriginOfChanges == null ? string.Empty : string.Join(";", result.OriginOfChanges.Distinct());

            Console.WriteLine(
                @"
                ID: {0}
                Version: {1}
                Contact: {2}
                Belongs To Company ID: {3}
                Email Message: {4}
                Job: {5}
                Event: {6}
                Program: {7}
                Campaign: {8}
                Comment: {9}
                Type: {10}
                Actual Value: {11}
                ForeCast Value: {12}
                Date: {13}
                OriginOfChanges: {14}",
                result.Id,
                result.Version.ToString(CultureInfo.CurrentCulture),
                contactId,
                belongsToCompanyId,
                emailId,
                jobId,
                eventId,
                programId,
                campaignId,
                result.Comment,
                resultTypeId,
                result.ActualValue.ToString(CultureInfo.CurrentCulture),
                result.ForecastValue.ToString(CultureInfo.CurrentCulture),
                result.Date.ToString(CultureInfo.CurrentCulture),
                originOfChanges);
        }

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

            Console.Write("Please type the ID (GUID) for the company that the new result belongs to => ");
            Guid belongsToCompanyId;
            if (!Guid.TryParse(Console.ReadLine(), out belongsToCompanyId))
            {
                Console.WriteLine("Incorrect belongs to ID");
                return;
            }

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

            var result = new MarketingResult
            {
                Id = id,
                BelongsToCompany = new Company { Id = belongsToCompanyId },
                Type = new MarketingResultType { Id = resultTypeId },
                Date = DateTime.UtcNow
            };

            var request = new CreateOrUpdateMarketingResultRequest { MarketingResult = result };
            this.Client.ProcessRequest(request);
        }

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

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

        /// <summary>
        /// Handles the <see cref="CreateOrUpdateMarketingResultResponse"/> that is received from the response queue. Displays the marketing result.
        /// </summary>
        /// <param name="response">The <see cref="CreateOrUpdateMarketingResultResponse"/> received after sending a <see cref="CreateOrUpdateMarketingResultRequest"/>.</param>
        private void ProcessCreateOrUpdateMarketingResultResponse(SdkResponse response)
        {
            var createOrUpdateResultResponse = (CreateOrUpdateMarketingResultResponse)response;
            Console.WriteLine("Processing CreateOrUpdateResultResponse.");

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

            Console.WriteLine("The create/update result");
            this.PrintMarketingResult(createOrUpdateResultResponse.MarketingResult);
            this.updateRequestSent = false;
        }

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

            var request = new DeleteMarketingResultRequest { MarketingResultId = id };
            this.Client.ProcessRequest(request);
        }

        /// <summary>
        /// Handles the DeleteMarketingResultResponse that is received from the response queue.
        /// </summary>
        /// <param name="response">The DeleteResultMarketingResponse received after sending a DeleteMarketingResultRequest.</param>
        private void ProcessDeleteMarketingResultResponse(SdkResponse response)
        {
            var deleteResultResponse = (DeleteMarketingResultResponse)response;
            Console.WriteLine("Processing DeleteMarketingResultResponse.");

            Console.WriteLine(deleteResultResponse.Succeeded ? "Result deleted" : "Failed to delete result");
        }

        /// <summary>
        /// Demonstrates how to retrieve marketing result types.
        /// </summary>
        private void RetrieveMarketingResultTypes()
        {
            Console.WriteLine("This request retrieves a list of result types.");
            var request = new RetrieveMarketingResultTypesRequest();
            this.Client.ProcessRequest(request);
        }

        /// <summary>
        /// Handles the RetrieveMarketingResultTypesResponse that is received from the response queue.
        /// </summary>
        /// <param name="response">The RetrieveMarketingResultTypesResponse received after sending a RetrieveMarketingResultTypesRequest.</param>
        private void ProcessRetrieveMarketingResultTypesResponse(SdkResponse response)
        {
            var retrieveResultTypesResponse = (RetrieveMarketingResultTypesResponse)response;
            Console.WriteLine("Processing RetrieveResultTypesResponse.");

            if (retrieveResultTypesResponse.Succeeded)
            {
                Console.WriteLine("List of result types");
                Console.WriteLine("ID\t\t\t\t\tName");
                foreach (var status in retrieveResultTypesResponse.MarketingResultTypes)
                {
                    Console.WriteLine(status.Id + "\t" + status.Name);
                }
            }
            else
            {
                Console.WriteLine("Failed to retrieve result types");
            }
        }

        /// <summary>
        /// Demonstrates how to retrieve multiple marketing results.
        /// </summary>
        private void RetrieveMarketingResults()
        {
            Console.WriteLine("This request will retrieve multiple results.");
            Console.Write("Filter on Origin of changes =>");
            var originOfChange = Console.ReadLine();

            var request = new RetrieveMarketingResultsRequest { MaxNumberOfRecordsToGet = 100, OriginOfChange = originOfChange };
            this.Client.ProcessRequest(request);
        }

        /// <summary>
        /// Handles the RetrieveMarketingResultsResponse that is received from the response queue. Displays the marketing results.
        /// </summary>
        /// <param name="response">The RetrieveMarketingResultsResponse received after sending a RetrieveMarketingResultsRequest.</param>
        private void ProcessRetrieveMarketingResultsResponse(SdkResponse response)
        {
            var retrieveResultsResponse = (RetrieveMarketingResultsResponse)response;
            Console.WriteLine("Processing RetrieveResultsResponse.");

            var counter = 1;
            foreach (var result in retrieveResultsResponse.MarketingResults)
            {
                Console.WriteLine("\nResult #{0}", counter++);
                this.PrintMarketingResult(result);
            }
        }

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