共用方式為


Web API Helper 程式碼︰組態類別

 

發行︰ 2017年1月

適用於: Dynamics 365 (online)、Dynamics 365 (on-premises)、Dynamics CRM 2016、Dynamics CRM Online

使用組態類別階層指定必要的連線資料,用於從您的應用程式存取 Dynamics 365 Web 服務。 您可以套用此連線資料,直接在您的程式碼中使用設定值,可能來自使用者輸入,使用 Configuration 基底類別。 通常提供此資訊在應用程式設定檔中儲存的設定中,使用衍生類別 FileConfiguration

組態類別階層的原始程式碼位於 Configuration.cs 檔案中,在 CRM SDK Web API Helper 程式庫中。 組態類別階層的設計是搭配 Authentication 類別使用,讓您建立與 Dynamics 365 服務的安全連線。 如需詳細資訊,請參閱使用 Microsoft Dynamics 365 Web API Helper 程式庫 (C#)

連線資料

Configuration 類別會讀取和剖析應用程式設定檔,以取得下列連線資料。

連線資料

部署

描述

服務 URL

全部

Dynamics 365 服務的基底 URL

使用者名稱

全部

Dynamics 365 中註冊的使用者名稱

密碼

全部

該使用者的密碼

網域

全部

Dynamics 365 服務的網域,用於 Active Directory 驗證

用戶端識別碼

線上和僅 IFD

在 Azure AD 中針對 Dynamics 365 (線上) 或 Dynamics 365 (內部部署) 的 Active Directory 用戶註冊的應用程式的用戶端識別碼,使用 網際網路對向部署 (IFD)。

重新導向 URL

線上和僅 IFD

目前應用程式的回呼 URI。

如需取得應用程式的用戶端識別碼和重新導向 URL 的詳細資訊,請參閱逐步解說:向 Azure Active Directory 註冊 Dynamics 365 應用程式,用來搭配 Dynamics 365 (線上),以及逐步解說:向 Active Directory 註冊 Dynamics 365 應用程式,用來搭配 Dynamics 365 (內部部署),使用 網際網路對向部署 (IFD)。

FileConfiguration 連線設定

大多數 Dynamics 365 Web API 範例使用衍生類別 FileConfiguration 從應用程式設定檔 App.config 中取得連線資料。 此檔案有數個應用程式設定,套用至不同的 Dynamics 365 伺服器部署模式。connectionString 設定包含服務 URL 和使用者名稱。 此外,ClientIdRedirectUrl 設定為線上或網際網路對向部署 (IFD) 所需。 下列各行取自預設 App.config 檔案,隨大部分 Web API 範例提供,其中包含做為預留位置值的此連線資料。 您必須將這些預留位置取代為目前使用者、您的 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 Helper 程式庫-Configuration 類別圖表

Configuration 類別

屬性:

所有屬性直接對應至前一節中詳述的對應連線資料。


方法

預設建構函式會將所有屬性保留未初始化 (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”);

如果 null 或空的連接字串名稱傳遞至 FileConfiguration 類別建構函式,則會使用設定檔最上方的第一個連接字串。

此外,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 Helper 程式庫 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 Helper 程式庫 (C#)
Web API Helper 程式碼:驗證類別
Web API Helper 程式碼:CrmHttpResponseException 類別

Microsoft Dynamics 365

© 2017 Microsoft. 著作權所有,並保留一切權利。 著作權