CRM 2011 – How to get the current user from within a dialog

2007_microsoft_dynamics_crmI needed to get the current user in a dialog but CRM 2011 Dialogs do not provide any easy way to access the currently logged in user’s information. To get this information I found two ways (I don’t know if they are the unique ways.. but run!!):

1. USE ENTITY

The first way was to create a new instance if an entity: I created a new entity, the owner field will contain the currently logged in user.
The steps I followed:

  • Log into CRM and create a new entity, call it new_CurrentDialogUser. You do not have to add any new fields.
  • Open your existing dialog for editing.
  • From the Dialog editor, the first thing to do is create an instance of new_CurrentDialogUser.
    • Create a new stage, positioned at the very beginning of the dialog.
    • Click ‘Add Step’ and select ‘Create Record’.
    • Choose the type to be new_CurrentDialogUser.
    • Click on properties. Notice the owner field is presented. Do not populate this field. Instead, when the ‘Create Record’ step executes, it will default the owner to the currently logged in user.
  • Once the ‘Create Record’ steps executes in your dialog, you have the ability to reference this step from throughout the rest of your dialog, just as if you were referencing the current record that is related to your dialog.
  • In my case, I use an ‘Assign Value’ step to store the owner of the newly created new_ CurrentDialogUser to a local variable, called CurrentUser.
    • Click ‘Add Step’ and choose ‘assign value details.’
    • In the ‘Look For’, select from the local values, the choice ‘Create (Current Dialog User)’.
  • Finally, once my am done using the current user, I perform an ‘UpdateStatus’ step, as a means to
    deactivate the dynamically created new_CurrentDialogUser instance.
    • Add step, select ‘Change Status’
    • Select the ‘Create (Current Dialog user)’.
    • Change the status to ‘Inactive’.

2. USE ACTIVITY WORKFLOW

I created a new workflow activity with Output parameters. This output parameters are all parameters that I needed in my dialog. For example I have the Current User, etc. In following the piece of code:

// <copyright file="ParametersActivity.cs" company="">
// Copyright (c) 2014 All Rights Reserved
// </copyright>
// <author>Alessandro Graps</author>
// <date>6/25/2014 8:34:52 AM</date>
// <summary>Implements the ParametersActivity Workflow Activity.</summary>

using ActivityRecording.Entities;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Query;

namespace Winvs.Next.ActivityRecording.Workflow
{
    using System;
    using System.Activities;
    using System.ServiceModel;
    using Microsoft.Xrm.Sdk;
    using Microsoft.Xrm.Sdk.Workflow;

    public sealed class ParametersActivity : CodeActivity
    {
        [Output("Current User")]
        [ReferenceTarget("systemuser")]
        public OutArgument<EntityReference> CurrentUser { get; set; }

        [Output("Current Time Mapping")]
        [ReferenceTarget(winvs_unitconfiguration.EntityLogicalName)]
        public OutArgument<EntityReference> CurrentTimeMapping { get; set; }

        protected override void Execute(CodeActivityContext context)
        {
            IWorkflowContext workflowContext = context.GetExtension<IWorkflowContext>();

            if (workflowContext == null)
            {
                throw new InvalidPluginExecutionException("Failed to retrieve workflow context.");
            }

            if (workflowContext.Depth > 1)
                return;
            
            CurrentUser.Set(context, new EntityReference("systemuser", workflowContext.InitiatingUserId));


            IOrganizationServiceFactory serviceFactory = context.GetExtension<IOrganizationServiceFactory>();
            IOrganizationService service = serviceFactory.CreateOrganizationService(workflowContext.UserId);

            winvs_unitconfiguration winvsUnitconfiguration = GetConfigurationEntityUnitGroup(service);

            CurrentTimeMapping.Set(context, new EntityReference("winvs_unitconfiguration", winvsUnitconfiguration.Id));

        }

        public winvs_unitconfiguration GetConfigurationEntityUnitGroup(IOrganizationService service)
        {
            string entityName = "winvs_unitconfiguration";

            // Get the metadata for the currently list's entity
            // This metadata is used to create a "Property Descriptor Collection"

            QueryExpression qe = new QueryExpression();
            qe.ColumnSet = new ColumnSet(true);
            qe.EntityName = entityName;

            RetrieveMultipleRequest request = new RetrieveMultipleRequest();
            request.Query = qe;
            RetrieveMultipleResponse response = (RetrieveMultipleResponse)service.Execute(request);


            if (response.EntityCollection.Entities.Count == 0)
                throw new Exception(string.Format("The configuration entity is empty."));

            foreach (Entity unitConfigurationEntity in response.EntityCollection.Entities)
            {
                winvs_unitconfiguration winvsUnitconfiguration = unitConfigurationEntity.ToEntity<winvs_unitconfiguration>();
                return winvsUnitconfiguration;
                break;
            }

            throw new Exception(string.Format("The configuration entity is empty."));
        }

    }
}

This is a fast way to get all information that I don’t have in dialogs.

Lascia un commento

Inserisci i tuoi dati qui sotto o clicca su un'icona per effettuare l'accesso:

Logo WordPress.com

Stai commentando usando il tuo account WordPress.com. Chiudi sessione / Modifica )

Foto Twitter

Stai commentando usando il tuo account Twitter. Chiudi sessione / Modifica )

Foto di Facebook

Stai commentando usando il tuo account Facebook. Chiudi sessione / Modifica )

Google+ photo

Stai commentando usando il tuo account Google+. Chiudi sessione / Modifica )

Connessione a %s...