Web API 帮助程序代码:配置类

 

发布日期: 2017年1月

适用于: Dynamics 365 (online),Dynamics 365 (on-premises),Dynamics CRM 2016,Dynamics CRM Online

使用配置类层次结构指定从应用程序访问 Dynamics 365 Web 服务所需连接数据。 可以通过直接在代码中设置值,通过用户输入或使用 Configuration 基类提供此连接数据。 更典型的是,可通过使用派生类 FileConfiguration,在应用程序配置文件中存储的设置内提供此信息。

配置类层次结构的源代码位于 CRM SDK Web API 帮助程序库 中的文件 Configuration.cs 内。 此配置类层次结构设计为与 Authentication 类配合工作,供您建立与 Dynamics 365 服务之间的安全连接。 有关详细信息,请参阅使用 Microsoft Dynamics 365 Web API 帮助程序库 (C# 库)

连接数据

Configuration 类读取并分析应用程序配置文件以获取以下连接数据。

连接数据

部署

说明

服务 URL

所有

Dynamics 365 服务的基 URL

用户名

所有

Dynamics 365 中注册的用户名

密码

所有

该用户的密码

所有

用于执行 Active Directory 身份验证的 Dynamics 365 服务的域

客户端 ID

仅限联机和 IFD

应用程序的客户端 ID,因为它使用 面向 Internet 的部署 (IFD) 注册 Dynamics 365(在线) 或 Dynamics 365(本地) 的 Active Directory 租户的 Azure AD。

重定向 URL

仅限联机和 IFD

当前应用程序的回调 URI。

有关如何获取应用程序的客户端 ID 和重定向 URL 的详细信息,请参阅演练:使用 Azure Active Directory 注册 Dynamics 365 应用程序 了解与 Dynamics 365(在线) 结合使用,以及演练:使用 Active Directory 注册 Dynamics 365 应用程序 了解使用 面向 Internet 的部署 (IFD) 与 Dynamics 365(本地) 结合使用。

FileConfiguration 连接设置

大多数 Dynamics 365 Web API 示例使用派生类 FileConfiguration 从应用程序配置文件 App.config 提取连接数据。 该文件有多个适用于不同 Dynamics 365 Server 部署模式的应用程序设置。connectionString 设置中包含服务 URL 和用户名。 此外,在线或面向 Internet 的部署 (IFD) 需要 ClientIdRedirectUrl 设置。 以下行,除大多数 Web API 示例随附的默认 App.config 文件中的行之外,都包含此连接数据充当占位符值。 必须将这些占位符替换为当前用户、您的 Dynamics 365 服务器和客户端应用程序特定的值。

<connectionStrings>  
  <add name="default"  connectionString="Url=http://myserver/myorg/; Username=name; Password=password; Domain=domain" />
</connectionStrings>  

<appSettings>
  <add key="ClientId" value="e5cf0024-a66a-4f16-85ce-99ba97a24bb2" />
  <add key="RedirectUrl" value="https://localhost/SdkSample" />
</appSettings>

默认配置文件列表 中提供了默认配置文件的完整内容。

类层次结构和成员

下表显示配置类层次结构的公共成员。

Dynamics 365 Web API 帮助程序库 - 配置类关系图

配置类

属性:

所有属性直接映射到上一节中详细介绍的相应连接数据。


方法

默认构造函数将所有属性保持为未初始化 (null)。

FileConfiguration 类

属性:

Name 是连接字符串设置条目的名称。

PathToConfig 是应用程序配置文件的完整路径或相对路径。


方法

默认构造函数将所有属性保持为未初始化 (null)。

非默认构造函数采用用于指定命名连接字符串的单字符串参数。 空字符串或 null 字符串值导致使用第一个连接字符串条目。

Load 方法打开、读取和分析指定的配置文件。 供非默认构造函数使用。

使用情况

FileConfigurationAuthentication 类设计为一前一后使用来读取 App.config 中的连接信息,然后建立与目标 Dynamics 365 服务服务之间的安全连接。 这可以通过以下语句实施。

FileConfiguration config = new FileConfiguration(null);
Authentication auth = new Authentication(config);
httpClient = new HttpClient(auth.ClientHandler, true);

Configuration 类中的非默认构造函数支持使用命名连接字符串,如:

Configuration config = new FileConfiguration(“TestServer”);

如果向 FileConfiguration 类构造函数传递 null 或空连接字符串名称,将使用配置文件顶部的第一个连接字符串。

此外,此 SDK 示例支持运行时命令参数,该参数表示所需连接字符串的名称,将传递到构造函数。 此选项由以下代码实施:

if (cmdargs.Length > 0)
{
    config = new FileConfiguration(cmdargs[0]);
}
else
{
    config = new FileConfiguration(null);
}

配置搜索顺序

无论使用默认还是自定义应用程序配置文件,都可以在该文件中提供可选的 AlternateConfig 应用程序设置来指定备用配置文件。 如果存在该文件,将改用其连接设置。

<add key="AlternateConfig" value="C:\Temp\crmsample.exe.config"/>

此设置的一个常见用途是提供在多个应用程序之间共享的一个全局配置文件,而不是编辑各应用程序的 App.config 文件。 这对贯穿开发和测试阶段的多个应用程序之间共享配置和注册信息尤其有用。 所以,请仅出于生产用途,才为各应用程序提供唯一配置和注册信息。

默认配置文件列表

大多数 Dynamics 365 Web API 示例随附的 App.config 文件中包含开发人员或站点管理员必须编辑的占位符连接值。

<?xml version="1.0" encoding="utf-8"?>
<configuration>

  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
  </startup>

  <connectionStrings>
    <clear />

    <!-- When providing a password, make sure to set the app.config file's security so that only you can read it. -->
    <add name="default"   connectionString="Url=http://myserver/myorg/; Username=name; Password=password; Domain=domain" />
    <add name="CrmOnline" connectionString="Url=https://mydomain.crm.dynamics.com/; Username=someone@mydomain.onmicrosoft.com; Password=password" />
  </connectionStrings>  

  <appSettings>
    <!--For information on how to register an app and obtain the ClientId and RedirectUrl
        values see https://msdn.microsoft.com/dynamics/crm/mt149065 -->

    <!--Active Directory application registration. -->
    <!--These are dummy values and should be replaced with your actual app registration values.-->
    <add key="ClientId" value="e5cf0024-a66a-4f16-85ce-99ba97a24bb2" />
    <add key="RedirectUrl" value="https://localhost/SdkSample" />

    <!-- Use an alternate configuration file for connection string and setting values. This optional setting
    enables use of an app.config file shared among multiple applications. If the specified file does
    not exist, this setting is ignored.-->
    <add key="AlternateConfig" value="C:\Temp\crmsample.exe.config"/>
  </appSettings>

 </configuration>

类列表

CRM SDK Web API 帮助程序库 NuGet 包中提供此类的最新来源。

using System;
using System.IO;
using System.Security;
using System.Configuration;

namespace Microsoft.Crm.Sdk.Samples.HelperCode
{
    /// <summary>
    /// An application configuration containing user logon, application, and web service information
    /// as required for CRM Web API authentication.
    /// </summary>
    public class Configuration
    {
        #region Properties
        /// <summary>
        /// The root address of the CRM service.
        /// </summary>
        /// <example>https://myorg.crm.dynamics.com</example>
        public string ServiceUrl { get; set; }

        /// <summary>
        /// The redirect address provided when the application was registered in Microsoft Azure
        /// Active Directory or AD FS.
        /// </summary>
        /// <remarks>Required only with a web service configured for OAuth authentication.</remarks>
        /// <seealso cref="https://msdn.microsoft.com/library/dn531010.aspx#bkmk_redirect"/>
        public string RedirectUrl { get; set; }

        /// <summary>
        /// The client ID that was generated when the application was registered in Microsoft Azure
        /// Active Directory or AD FS.
        /// </summary>
        /// <remarks>Required only with a web service configured for OAuth authentication.</remarks>
        public string ClientId { get; set; }

        /// <summary>
        /// The user name of the logged on user or null.
        /// </summary>
        public string Username { get; set; }

        /// <summary>
        ///  The password of the logged on user or null.
        /// </summary>
        public SecureString Password { get; set; }

        /// <summary>
        ///  The domain of the logged on user account or null.
        /// </summary>
        /// <remarks>Required only with a web service configured for Active Directory authentication.</remarks>
        public string Domain { get; set; }

        #endregion Properties

        #region Constructors

        /// <summary>
        /// Constructs a configuration object.
        /// </summary>
        public Configuration() { }

        #endregion Constructors
    }

    /// <summary>
    /// A configuration that is persisted to file storage.
    /// </summary>
    /// <remarks>This implementation defaults to using an app.config file. However, you
    /// can derive a subclass and override the virtual methods to make use of other
    /// file formats.
    /// 
    /// One set of application registration settings and multiple named connection strings are supported.</remarks>
    public class FileConfiguration : Configuration
    {
        #region Properties
        /// <summary>
        /// The full or relative path to the application's configuration file.
        /// </summary>
        /// <remarks>The file name is in the format <appname>.exe.config.</appname></remarks>
        public string PathToConfig { get; set; }

        /// <summary>
        /// The name of the connection.
        /// </summary>
        public string Name { get; set; }

        #endregion Properties

        #region Constructors
        /// <summary>
        /// Constructs a file configuration.
        /// </summary>
        public FileConfiguration()
            : base()
        { }

        /// <summary>
        /// Loads a named connection string and application settings from persistent file storage.
        /// The configuration file must have the same name as the application and be located in the 
        /// run-time folder.
        /// </summary>
        /// <param name="name">The name of the target connection string. An empty or null string value 
        /// results in the first named configuration being used.</param>
        /// <remarks>The app.config file must exist in the run-time folder and have the name
        /// <appname>.exe.config. To specify an app.config file path, use the Load() method.</remarks>
        public FileConfiguration(string name)
            : base()
        {
            var path = System.IO.Path.Combine(Directory.GetCurrentDirectory(), Environment.GetCommandLineArgs()[0]);

            Load(name, String.Concat(path, ".config"));
        }

        #endregion Constructors

        #region Methods
        /// <summary>
        /// Loads server connection information and application settings from persistent file storage.
        /// </summary>
        /// <remarks>A setting named OverrideConfig can optionally be added. If a config file that this setting
        /// refers to exists, that config file is read instead of the config file specified in the path parameter.
        /// This allows for an alternate config file, for example a global config file shared by multiple applications.
        /// </summary>
        /// <param name="connectionName">The name of the connection string in the configuration file to use. 
        /// Each CRM organization can have its own connection string. A value of null or String.Empty results
        /// in the first (top most) connection string being used.</param>
        /// <param name="path">The full or relative pathname of the configuration file.</param>
        public virtual void Load(string connectionName, string path)
        {
            // Check passed parameters.
            if (string.IsNullOrEmpty(path) || !System.IO.File.Exists(path))
                throw new ArgumentException("The specified app.config file path is invalid.", this.ToString());
            else
                PathToConfig = path;

            try
            {
                // Read the app.config file and obtain the app settings.
                System.Configuration.Configuration config = null;
                ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();
                configFileMap.ExeConfigFilename = PathToConfig;
                config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);

                var appSettings = config.AppSettings.Settings;

                // If an alternate config file exists, load that configuration instead. Note the test
                // for redirectTo.Equals(path) to avoid an infinite loop.
                if (appSettings["AlternateConfig"] != null)
                {
                    var redirectTo = appSettings["AlternateConfig"].Value;
                    if (redirectTo != null && !redirectTo.Equals(path) && System.IO.File.Exists(redirectTo))
                    {
                        Load(connectionName, redirectTo);
                        return;
                    }
                }

                // Get the connection string.
                ConnectionStringSettings connection;
                if (string.IsNullOrEmpty(connectionName))
                {
                    // No connection string name specified, so use the first one in the file.
                    connection = config.ConnectionStrings.ConnectionStrings[0];
                    Name = connection.Name;
                }
                else
                {
                    connection = config.ConnectionStrings.ConnectionStrings[connectionName];
                    Name = connectionName;
                }

                // Get the connection string parameter values.
                if (connection != null)
                {
                    var parameters = connection.ConnectionString.Split(';');
                    foreach (string parameter in parameters)
                    {
                        var trimmedParameter = parameter.Trim();
                        if (trimmedParameter.StartsWith("Url="))
                            ServiceUrl = parameter.Replace("Url=", String.Empty).TrimStart(' ');

                        if (trimmedParameter.StartsWith("Username="))
                            Username = parameters[1].Replace("Username=", String.Empty).TrimStart(' ');

                        if (trimmedParameter.StartsWith("Password="))
                        {
                            var password = parameters[2].Replace("Password=", String.Empty).TrimStart(' ');

                            Password = new SecureString();
                            foreach (char c in password) Password.AppendChar(c);
                        }
                        if (trimmedParameter.StartsWith("Domain="))
                            Domain = parameter.Replace("Domain=", String.Empty).TrimStart(' ');
                    }
                }
                else
                    throw new Exception("The specified connection string could not be found.");

                // Get the Azure Active Directory application registration settings.
                RedirectUrl = appSettings["RedirectUrl"]?.Value;
                ClientId = appSettings["ClientId"]?.Value;
            }
            catch (InvalidOperationException e)
            {
                throw new Exception("Required setting in app.config does not exist or is of the wrong type.", e);
            }
        }

        /// <summary>
        /// Save the current configuration to persistent file storage.
        /// </summary>
        /// <remarks>Any existing configuration is overwritten.</remarks>
        public virtual void Save()
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// Add a named connection string to persistent file storage.
        /// </summary>
        /// <remarks>A named connection string from the current configuration is added to an existing
        /// configuration file./remarks>
        public virtual void AddConnection()
        {
            throw new NotImplementedException();
        }

        #endregion Methods
    }
}

另请参阅

Microsoft Dynamics 365 Web API (C#) 入门
在 Visual Studio (C#) 中启动 Dynamics 365 Web API 项目
使用 Microsoft Dynamics 365 Web API 帮助程序库 (C# 库)
Web API 帮助程序代码:Authentication 类
Web API 帮助程序代码:CrmHttpResponseException 类

Microsoft Dynamics 365

© 2017 Microsoft。 保留所有权利。 版权