웹 API 도우미 코드: 구성 클래스

 

게시 날짜: 2017년 1월

적용 대상: Dynamics 365 (online), Dynamics 365 (on-premises), Dynamics CRM 2016, Dynamics CRM Online

구성 클래스 계층 구조를 사용하여 응용 프로그램에서 Dynamics 365 웹 서비스에 액세스하기 위해 필요한 연결 데이터를 지정할 수 있습니다.Configuration 기본 클래스를 사용하여 사용자 입력에서 직접 코드에서 값을 설정하여 이 연결 데이터를 제공할 수 있습니다. 더 일반적으로 파생된 클래스인 FileConfiguration을 사용하여 응용 프로그램 구성 파일에 저장된 설정에 이 정보를 제공할 수 있습니다.

구성 클래스 계층 구조에 대한 소스 코드는 CRM SDK 웹 API 라이브러리 도우미의 파일 Configuration.cs 위치에 있습니다. 구성 클래스 계층 구조는 Dynamics 365 서비스에 보안 연결을 설정하기 위해 Authentication 클래스와 함께 작동하도록 설계되었습니다. 자세한 내용은 Microsoft Dynamics 365 웹 API 도우미 라이브러리(C#) 사용을 참조하십시오.

연결 데이터

Configuration 클래스는 응용 프로그램 구성 파일을 읽고 구문 분석하여 다음 연결 데이터를 가져옵니다.

연결 데이터

배포

설명

서비스 URL

모두

Dynamics 365 서비스에 대한 기본 URL

사용자 이름

모두

Dynamics 365에 등록된 사용자 이름

암호

모두

사용자의 암호

도메인

모두

Active Directory 인증을 위한 Dynamics 365 서비스의 도메인

클라이언트 ID

온라인 및 IFD 전용

Dynamics 365(온라인)용 Azure AD로 또는 인터넷 연결 배포(IFD)를 사용하여 Dynamics 365(온-프레미스)용 Active Directory 테넌트로 응용 프로그램의 클라이언트 ID를 등록하는 경우.

리디렉션 URL

온라인 및 IFD 전용

현재 응용 프로그램에 대한 콜백 URI.

응용 프로그램에 대한 클라이언트 ID와 리디렉션 URL을 얻는 방법에 대한 자세한 내용은 Dynamics 365(온라인) 사용의 경우 연습: Azure Active Directory를 사용하여 Dynamics 365 등록을, 인터넷 연결 배포(IFD)를 사용한 Dynamics 365(온-프레미스) 사용의 경우 연습: Active Directory를 사용하여 Dynamics 365 등록을 참조하십시오.

FileConfiguration 연결 설정

대부분의 Dynamics 365 웹 API 샘플에서는 파생된 클래스 FileConfiguration을 사용하여 응용 프로그램 구성 파일인 App.config에서 연결 데이터를 추출합니다. 이 파일은 다양한 Dynamics 365 서버 배포 모드에 적용되는 여러 응용 프로그램에 대한 설정이 있습니다.connectionString 설정은 서비스 URL 및 사용자 이름을 포함합니다. 또한 온라인 또는 인터넷 연결 배포(IFD)에 ClientIdRedirectUrl 설정이 필요합니다. 대부분의 웹 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 웹 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”);

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 웹 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 웹 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 웹 API(C#) 시작
Visual Studio(C#)에서 Dynamics 365 웹 API 프로젝트 시작
Microsoft Dynamics 365 웹 API 도우미 라이브러리(C#) 사용
웹 API 도우미 코드: 인증 클래스
웹 API 도우미 코드: CrmHttpResponseException 클래스

Microsoft Dynamics 365

© 2017 Microsoft. All rights reserved. 저작권 정보