Home › Dynamics 365 Customer Engagement (CRM) › Dynamics 365 Get Current User from C#
Dynamics 365 Customer Engagement (CRM) · Jun 28, 2017

Dynamics 365 Get Current User from C#

In Dynamics 365 when running C# code, you may want to get the current user. We will go through an example if we were to run this from a console app.

First, create a new console app in Visual Studio:

From NuGet, add:

  • Microsoft.CrmSdk.CoreAssemblies
  • Microsoft.CrmSdk.XrmTooling.CoreAssembly

Add using:

using Microsoft.Xrm.Tooling.Connector;
using Microsoft.Xrm.Sdk;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Query;

Add the code. We will first get the user id, then perform a retrieve to get the user’s name:

[sourcecode language=”CSharp”]
try
{
var connectionString = @"AuthType = Office365; Url = https://yourtenant.crm.dynamics.com/;Username=yourusername;Password=yourpassword";
CrmServiceClient conn = new CrmServiceClient(connectionString);

IOrganizationService service;
service = (IOrganizationService)conn.OrganizationWebProxyClient != null ? (IOrganizationService)conn.OrganizationWebProxyClient : (IOrganizationService)conn.OrganizationServiceProxy;

// Get a system user to send the email (From: field)
WhoAmIRequest systemUserRequest = new WhoAmIRequest();
WhoAmIResponse systemUserResponse = (WhoAmIResponse)service.Execute(systemUserRequest);
Guid userId = systemUserResponse.UserId;

// Lookup User
var User = service.Retrieve("systemuser", userId, new ColumnSet("fullname"));
string fullName = User["fullname"].ToString();

Console.WriteLine(userId.ToString());
Console.WriteLine(fullName);
Console.ReadLine();
}
catch (Exception ex)
{
// Implement error handling
}
[/sourcecode]

This will output:

 

Leave a Reply

Your email address will not be published. Required fields are marked *

Carl de Souza
KEEP LEARNING. KEEP BUILDING.

Explore AI, agents & Microsoft technology.

I share practical ideas, tutorials, and videos about AI, AI agents, Microsoft technologies, and the Power Platform.