CRM

How to get the User Id using c# in dynamic crm

In This article we will see How to get the User Id using c# in dynamic crm.

Step By step we will learn How to get the User Id using c# in dynamic crm.

First we will create a console application to connect to the Organization service using the CrmServiceClient class. You will pass your connection information using a connection string passed to the constructor.
One thing always remember use the IOrganizationService.Execute method passing an instance of the WhoAmIRequest class, and we will display the WhoAmIResponse.UserId value.

How to get the User Id using c# in dynamic crm
Prerequisites

Visual Studio (2017 recommended)
Internet connection
Valid user account for a Common Data Service instance
Your username
Your password
Url to the Common Data Service environment you want to connect with

Create Visual Studio Project
1.Create a Console App (.NET Framework) project using .NET Framework 4.6.1.
get-user-id-using-c-dynamic-crm

2.In Solution Explorer, right-click the project you created and select Manage NuGet Packages.

get-user-id-using-c-dynamic-crm

3.Browse this Microsoft.CrmSdk.XrmTooling.CoreAssembly NuGet package and install it.

get-user-id-using-c-dynamic-crm

Open Program.cs Page
In Program.cs page add these namespaces

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

Finally write this code for How to get the User Id using c# in dynamic crm.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Tooling.Connector;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {   //Enter your organization url
            // e.g. https://xyzorg.crm.dynamics.com
            string url = "https://xyzorg.crm.dynamics.com";
            //Enter user name
            // e.g. abc@lkorg.onmicrosoft.com
            string userName = "abc@lkorg.onmicrosoft.com";
            //Enter Password
            // e.g. lku5678@$ 
            string password = "lku5678@$ ";

            string conn = $@"
    Url = {url};
    AuthType = Office365;
    UserName = {userName};
    Password = {password};
    RequireNewInstance = True";

            using (var svc = new CrmServiceClient(conn))
            {

                WhoAmIRequest request = new WhoAmIRequest();

                WhoAmIResponse response = (WhoAmIResponse)svc.Execute(request);

                Console.WriteLine("Your UserId is {0}", response.UserId);

                Console.WriteLine("Press any key to exit.");
                Console.ReadLine();
            }
        }
    }
    }

Press F5 to run the program. The output should look like this:
get-user-id-using-c-dynamic-crm

Leave a Reply

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