Step by Step: Connecting to Dynamics 365 using a C# Console App

 
 

If you’re new to Microsoft Dynamics 365 development you may be wondering how to connect to it via a .Net C# console application or would like to set up a Visual Studio project to get started with the Dynamics 365 SDK.

In this post I’ll take you through setting up the Visual Studio project, adding the Dynamics 365 SDK references, connecting to Dynamics 365 and running a basic query to validate.

 

Setting up a new Visual Studio 2017 Project with Dynamics 365 SDK References

  1. Open Visual Studio 2017 and select File | New | Project
  2. Click on Visual C# and select Console App (.Net Framework)
  3. Enter a project name within the Name field and click Ok

The next step is to add the Dynamics 365 SDK references to the project and this is quite easy now it’s managed via NuGet.

 
  1. Select Tools | NuGet Package Manager | Manage NuGet Packages for Solution
  2. This screen defaults to showing the installed packages, click Browse
  3. In the Search textbox type: Dynamics 365 XRMTooling and select Microsoft.CrmSdk.XrmTooling.CoreAssembly

  1. Select the Project in the right-hand side window and click Install

  1. If prompted by a “Preview Changes” dialog box, click Ok
  2. Click I Accept when prompted by the License Acceptance dialog
  3. We need to add one more package,  search for Microsoft.CrmSdk.CoreAssemblies under the browse tab and follow the same process to add it to the project too.

Alternatively, this same process can be done from the Nuget command line by:

  • Navigate to Tools | Nuget Package Manager | Package Manager Console
  • Within the package manager console copy and paste the following command:
 
1
2
Install-Package Microsoft.CrmSdk.XrmTooling.CoreAssembly -Version 9.0.2.4
Install-Package Microsoft.CrmSdk.CoreAssemblies -Version 9.0.2.4

Note that as of this post, the latest version is 9.0.2.4, to get the latest version check here.

The process above has added all the SDK DLL’s we need within the project References, so there’s no messing around to manually add them.

Now that’s done, we are ready to start coding!

 

Cutting the Code

  1. Add the following namespaces to the top of Program.cs:
 
1
2
3
4
5
6
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Crm.Sdk.Messages;
using System.Net;
using System.ServiceModel.Description;
using Microsoft.Xrm.Tooling.Connector;

  1. Next comes the connection code and the aim is to create an IOrganizationService object which connects to Dynamics365 via a client connection and provides pragmatic access to Dynamics 365. Copy and paste the following code into the Main method:
 
1
2
3
4
5
6
7
IOrganizationService oServiceProxy;
 
//Create the Dynamics 365 Connection:
CrmServiceClient oMSCRMConn = new Microsoft.Xrm.Tooling.Connector.CrmServiceClient("AuthType=Office365;Username=<USERNAME>;Password=<PASSWORD>;URL=<URL>;");
 
//Create the IOrganizationService:
oServiceProxy = (IOrganizationService)oMSCRMConn.OrganizationWebProxyClient != null ? (IOrganizationService)oMSCRMConn.OrganizationWebProxyClient : (IOrganizationService)oMSCRMConn.OrganizationServiceProxy;

Within the CrmServiceClient string replace the following variables in your code:

  • <USERNAME> = the Dynamics username e.g. someone@DYN365Demo.onmicrosoft.com
  • <PASSWORD> = the user password
  • <URL> = the Dynamics 365 instance URL. This is this is the same URL that would be used to access it from a web browser (minus  the page “/main.aspx#####”) e.g.:

https://DYN365Demo.crm6.dynamics.com

  1. Add the following code underneath to check the connection by attempting to retrieve the current user ID:
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
if (oServiceProxy != null)
{
    //Get the current user ID:
    Guid userid = ((WhoAmIResponse)oServiceProxy.Execute(new WhoAmIRequest())).UserId;
 
    if (userid != Guid.Empty)
    {
        Console.WriteLine("Connection Successful!");
    }
}
else
{
    Console.WriteLine("Connection failed...");
}

And you’re done. Click the Start button to run the program and if the connection details are correct you should see “Connection Successful!”:

To keep the example above simple I’ve left out proper error handling, but for the sake of completeness I’ve included the full code below with a try / catch and some additional outputs to the console to show where it’s at:

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Crm.Sdk.Messages;
using System.Net;
using System.ServiceModel.Description;
using Microsoft.Xrm.Tooling.Connector;
 
 
namespace Dynamics_365_Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            IOrganizationService oServiceProxy;
            try
            {
                Console.WriteLine("Setting up Dynamics 365 connection");
 
                //Create the Dynamics 365 Connection:
                CrmServiceClient oMSCRMConn = new Microsoft.Xrm.Tooling.Connector.CrmServiceClient("AuthType=Office365;Username=<USERNAME>;Password=<PASSWORD>;URL=<URL>;");
 
                //Create the IOrganizationService:
                oServiceProxy = (IOrganizationService)oMSCRMConn.OrganizationWebProxyClient != null ?
                        (IOrganizationService)oMSCRMConn.OrganizationWebProxyClient :
                        (IOrganizationService)oMSCRMConn.OrganizationServiceProxy;
 
                Console.WriteLine("Validating Connection");
 
                if (oServiceProxy != null)
                {
                    //Get the current user ID:
                    Guid userid = ((WhoAmIResponse)oServiceProxy.Execute(new WhoAmIRequest())).UserId;
 
                    if (userid != Guid.Empty)
                    {
                        Console.WriteLine("Connection Successful!");
                    }
                }
                else
                {
                    Console.WriteLine("Connection failed...");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error - " + ex.ToString());
            }
 
            Console.ReadKey();
        }
    }
}

Feel free to leave any questions in the comments section below.

Step by Step: Connecting to Dynamics 365 using a C# Console App的更多相关文章

  1. Dynamics 365 Online-使用Azure Logic App 与 Dynamics 365 集成

    什么是Logic App? Azure Logic App 是微软发布的集成平台的产品,有助于生成,计划和自动完成工作流形式的流程,适合跨企业或组织集成,数据,系统和服务.与此同时,Logic App ...

  2. Step by step Dynamics CRM 2011升级到Dynamics CRM 2013

    原创地址:http://www.cnblogs.com/jfzhu/p/4018153.html 转载请注明出处 (一)检查Customizations 从2011升级到2013有一些legacy f ...

  3. Step by Step 创建一个新的Dynamics CRM Organization

    原创地址:http://www.cnblogs.com/jfzhu/p/4012833.html 转载请注明出处 前面演示过如何安装Dynamics CRM 2013,参见<Step by st ...

  4. Step by step Dynamics CRM 2013安装

    原创地址:http://www.cnblogs.com/jfzhu/p/4008391.html 转载请注明出处   SQL Server可以与CRM装在同一台计算机上,也可安装在不同的计算机上.演示 ...

  5. Step by Step 开发dynamics CRM

    这里是作为开发贴的总结. 现在plugin和workflow系列已经终结. 希望这些教程能给想入坑的小伙伴一些帮忙. CRM中文教材不多, 我会不断努力为大家提供更优质的教程. Plugin 开发系列 ...

  6. Monthly update for Dynamics 365 for Operation

    日期 标题, 类别 版本 描述 2017/8/22 Dyn 365 Fin and Ops, Ent ed July 2017 Plat Update 10 Category: Download   ...

  7. Dynamics 365中自定义工作流活动获取的上下文分析及注意事项

    关注本人微信和易信公众号: 微软动态CRM专家罗勇 ,回复244或者20170306可方便获取本文,同时可以在第一间得到我发布的最新的博文信息,follow me!我的网站是 www.luoyong. ...

  8. Dynamics 365 Online-Microsoft Flow

    自December 2016 update for Dynamics 365 (online)之后的Online版本,Dynamics 365有了个新Feature:Microsoft Flow Co ...

  9. Dynamics 365—脚本

    Xrm.Page.getAttribute() 转控件:controls.get(0) 取赋值:getValue(),setValue() 是否改动:getIsDirty() 表单载入时的值:getI ...

  10. Dynamics 365 Online-Virtual Entities

    转载来源https://blogs.technet.microsoft.com/lystavlen/2017/09/08/virtual-entities/,使用当前Dynamics 365环境,亲测 ...

随机推荐

  1. 记一次mysql5.7保存Emoji表情

    1.错误:SQLException; SQL state [HY000]; error code [1366]; Incorrect string value: '\xF0\x9F\x90\x96 \ ...

  2. C语言-链表流星雨(EsayX)

    刷B站看到的,做个玩玩.IDE:Visual Studio 2022.依赖EsayX图形库 1-效果 2-程序 /* 链表流星雨单文件版本 依赖EsayX图形库 */ #include <std ...

  3. maridb数据库表及字段增删改

    mariadb数据类型 mariadb数据类型分为数字.日期.时间以及字符串值. 适用类型原则:够用就行,尽量使用范围小的,而不用大的 常用数据类型: 1.整数 int,bit   #例如 年纪 适用 ...

  4. 在Ubuntu19.04系统中安装Emacs遇到的问题

    安装显示部分依赖软件包现在无法安装 发现emacs26无法安装 后来查阅资料,发现在Ubuntu18版本及以上就不需要更新了 即不需要以下操作: sudo apt update 同时安装也需要将ema ...

  5. map函数中调用多个async await请求出现的promise问题解决

    以上这个打印会返回[promise,promise,promise]那么是什么原因造成的呢?我们先来一个方法解决: 但是以上这种解决方式并没有真正解决问题,还是会返回一个[promise,promis ...

  6. Mac怎么安装Andriod模拟器

    Mac上怎么安装 Andriod 系统模拟器?有的朋友可能需要在自己用的 Mac 电脑上安装Andriod 系统模拟器,用于开发或测试一些安卓软件.介绍下怎么在 Mac 上用 Parallels De ...

  7. 点击div实现选中效果

    先上一份效果图.原来的checked多选框还是存在的,我只不过隐藏了,让他的整个div的范围都是可以点击的,右上角三个点是可以删除当前元素,左下角的播放按钮可以点击播放语音,主要是利用z-index把 ...

  8. kvm虚拟机创建和管理(2)

  9. iOS用runtime给一个类动态添加方法 ---class_addMethod

    先介绍下class_addMethod这个fangfa   /**   * Adds a new method to a class with a given name and implementat ...

  10. NGINX+Lua模块编译安装

    NGINX+Lua 环境配置 目录 NGINX+Lua 环境配置 一.环境装备 二.解压安装相应的软件 测试Lua环境 上面都是经过安装的一些坑之后安装完成的,下面是安装过程中出现的坑 一.环境装备 ...