샘플: XRM 도구 API 빠른 시작

 

게시 날짜: 2017년 1월

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

QuickStart 샘플은 XRM 도구 API를 사용하여 Microsoft Dynamics 365 인스턴스에 연결하고 엔터티에 대해 기본적인 만들기, 업데이트, 검색 및 삭제 작업을 수행하는 방법을 보여 주는 Microsoft .NET Framework 관리형 코드 샘플입니다. XRM 도구에 대한 자세한 내용은 XRM 도구를 사용하여 클라이언트 응용 프로그램 빌드를 참조하십시오.

요구 사항

이 샘플 코드는 Microsoft Dynamics 365(온라인 및 온-프레미스)용입니다. Microsoft Dynamics CRM SDK 패키지를 다운로드합니다. 다운로드 패키지의 다음 위치에서 확인할 수 있습니다.

SDK\SampleCode\CS\XRMTooling

보여 주기

  • 샘플 코드는 인증 및 자격 증명 캐싱 및 재사용에 대한 기본 제공 지원을 사용하여 일반적인 로그인 컨트롤을 제공하는 Dynamics 365용 WPF 응용 프로그램 SDK 템플릿을 사용하여 빌드됩니다. 일반적인 로그인 컨트롤과 Microsoft Visual Studio에서 SDK 템플릿을 사용하는 방법에 대한 자세한 내용은 클라이언트 응용 프로그램에서 XRM 도구의 공통 로그인 컨트롤 사용을 참조하십시오.

  • Dynamics 365에 대한 연결을 설정하는 데 도우미 코드를 사용하지 않습니다.

  • Dynamics 365에 연결한 후 샘플은 거래처 엔터티에 대해 기본적인 만들기, 업데이트, 검색 및 삭제 작업을 수행합니다.

  • 샘플을 처음으로 실행하면 c:\Users\<username>\AppData\Roaming\Microsoft\QuickStartXRMToolingWPFClient 폴더의 구성 파일(Default_QuickStartXRMToolingWPFClient.exe.config)에 사용자 자격 증명을 저장하고, 그 이후부터 런타임에 Dynamics 365에 로그인하려면 저장된 정보를 사용하거나 새 자격 증명을 지정하라는 메시지를 표시합니다.

  • 문제 해결을 지원하기 위해 문제가 발생하면 다음 로그 파일을 생성합니다.

    • Login_ErrorLog.log: 로그인 오류를 보고하기 위해. 이 파일은 \Users\<username>\AppData\Roaming\Microsoft\QuickStartXRMToolingWPFClient에 있습니다.

    • QuickStartXRMToolingWPFClient.log: 작동 오류를 보고하기 위해. 이 파일은 실행 파일과 동일한 위치, 즉 Microsoft Visual Studio 프로젝트의 디버그 폴더에 있습니다.

샘플을 실행하려면

  1. SDK\SampleCode\CS\XRMTooling 폴더를 찾아 엽니다.

  2. Visual Studio에서 QuickStartXRMToolingWPFClient.sln 파일을 엽니다.

  3. F5 키를 눌러 프로그램을 컴파일하고 실행합니다.

예제

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

// This namespace is automatically added for using 
// components in LoginWindow\CrmLogin.xaml (common login control).
using QuickStartXRMToolingWPFClient.LoginWindow;

// Add this namespace for performing 
// various operations in CRM.
using Microsoft.Xrm.Tooling.Connector;

namespace QuickStartXRMToolingWPFClient
{
    /// <summary>
    /// Demonstrates how to do basic entity operations like create, retrieve,
    /// update, and delete using the XRM Tooling APIs and the common login
    /// control.</summary>
    /// <remarks>
    /// At run-time, you will be given the option to delete all the
    /// database records created by this program.</remarks>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            btnDelete.Visibility = Visibility.Hidden;
        }

        #region Class Level Members

        private CrmLogin _ctrl = null;
        private Guid _accountId;

        #endregion Class Level Members

        #region How To Sample Code

        /// <summary>
        /// Connect to Microsoft CRM, and get an instance of CRMServiceClient 
        /// </summary>

        private void LoginButton_Click(object sender, RoutedEventArgs e)
        {
            // Create an instance of the XRM Tooling common login control
            _ctrl = new CrmLogin();

            /// Wire event to the CRM sign-in response. 
            _ctrl.ConnectionToCrmCompleted += ctrl_ConnectionToCrmCompleted;
            UpdateStatus("Initiating connection to CRM...");

            /// Show the XRM Tooling common login control. 
            _ctrl.ShowDialog();

            /// Validate if you are connected to CRM 
            if (_ctrl.CrmConnectionMgr != null && _ctrl.CrmConnectionMgr.CrmSvc != null && _ctrl.CrmConnectionMgr.CrmSvc.IsReady)
            {
                UpdateStatus("Connected to CRM! (Version: " + _ctrl.CrmConnectionMgr.CrmSvc.ConnectedOrgVersion.ToString() + 
                    "; Org: " + _ctrl.CrmConnectionMgr.CrmSvc.ConnectedOrgUniqueName.ToString() + ")");
                UpdateStatus("***************************************");
                UpdateStatus("Click Start to create, retrieve, update, and delete (optional) an account record.");
                btnSignIn.IsEnabled = false;
                btnCRUD.IsEnabled = true;
            }
            // If you are not connected to CRM; display the last error and last CRM excption
            else
            {
                UpdateStatus("The connection to CRM failed or was cancelled by the user.");            
            }            
        }

        private void btnCRUD_Click(object sender, RoutedEventArgs e)
        {
            // Create an account record
            Dictionary<string, CrmDataTypeWrapper> inData = new Dictionary<string, CrmDataTypeWrapper>();
            inData.Add("name", new CrmDataTypeWrapper("Sample Account Name", CrmFieldType.String));
            inData.Add("address1_city", new CrmDataTypeWrapper("Redmond", CrmFieldType.String));
            inData.Add("telephone1", new CrmDataTypeWrapper("555-0160", CrmFieldType.String));
            _accountId = _ctrl.CrmConnectionMgr.CrmSvc.CreateNewRecord("account", inData);

            // Validate if the account is created, and then retrieve it
            if (_accountId != Guid.Empty)
            {
                UpdateStatus("***************************************");
                UpdateStatus(DateTime.Now.ToString() + ": Created an account with the following" + "\n" + "details, and retrieved it:");
                Dictionary<string, object> data = _ctrl.CrmConnectionMgr.CrmSvc.GetEntityDataById("account", _accountId, null);
                foreach (var pair in data)
                {
                    if ((pair.Key == "name") || (pair.Key == "address1_city") || (pair.Key == "telephone1"))
                    {
                        UpdateStatus(pair.Key.ToUpper() + ": " + pair.Value);
                    }
                }
                btnCRUD.IsEnabled = false;
            }
            else
            {
                UpdateStatus("***************************************");
                UpdateStatus("Could not create the account.");
            }


            // Update the account record
            Dictionary<string, CrmDataTypeWrapper> updateData = new Dictionary<string, CrmDataTypeWrapper>();
            updateData.Add("name", new CrmDataTypeWrapper("Updated Sample Account Name", CrmFieldType.String));
            updateData.Add("address1_city", new CrmDataTypeWrapper("Boston", CrmFieldType.String));
            updateData.Add("telephone1", new CrmDataTypeWrapper("555-0161", CrmFieldType.String)); 
            bool updateAccountStatus = _ctrl.CrmConnectionMgr.CrmSvc.UpdateEntity("account","accountid",_accountId,updateData);

            // Validate if the the account record was updated successfully, and then display the updated information
            if (updateAccountStatus == true)
            {
                UpdateStatus("***************************************");
                UpdateStatus(DateTime.Now.ToString() + ": Updated the account details as follows:");
                Dictionary<string, object> data = _ctrl.CrmConnectionMgr.CrmSvc.GetEntityDataById("account", _accountId, null);
                foreach (var pair in data)
                {
                    if ((pair.Key == "name") || (pair.Key == "address1_city") || (pair.Key == "telephone1"))
                    {
                        UpdateStatus(pair.Key.ToUpper() + ": " + pair.Value);
                    }
                }
            }
            else
            {
                UpdateStatus("***************************************");
                UpdateStatus("Could not update the account.");
            }

            // Prompt the user to delete the account record created in the sample
            UpdateStatus("***************************************");
            UpdateStatus("To delete the account record created by the sample, click Delete Record.");
            UpdateStatus("Otherwise, click Exit to close the sample application.");
            btnDelete.Visibility = Visibility.Visible;        
        }

        // Delete the account record created in this sample.
        private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            btnDelete.IsEnabled = false;
            _ctrl.CrmConnectionMgr.CrmSvc.DeleteEntity("account", _accountId);
            UpdateStatus("***************************************");
            UpdateStatus(DateTime.Now.ToString() + ": Deleted the account record.");
            UpdateStatus("Click Exit to close the sample application.");
        }

        // Exit the sample application
        private void btnExit_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// Progressively displays the status messages about the actions
        /// performed during the running of the sample.
        /// <param name="updateText">Indicates the status string that needs to be 
        /// displayed to the user.</param>
        /// </summary>
        public void UpdateStatus(string updateText)
        {
            if (lblStatus.Content.ToString() != String.Empty)
            {
                lblStatus.Content = lblStatus.Content + "\n" + updateText;
            }
            else
            {
                lblStatus.Content = updateText;
            }
        }

        /// <summary>
        /// Raised when the login process is completed.
        /// </summary>
        private void ctrl_ConnectionToCrmCompleted(object sender, EventArgs e)
        {
            if (sender is CrmLogin)
            {
                this.Dispatcher.Invoke(() =>
                {
                    ((CrmLogin)sender).Close();
                });
            }
        }
    }
    #endregion How To Sample Code

}

참고 항목

클라이언트 응용 프로그램에서 XRM 도구의 공통 로그인 컨트롤 사용
XRM 도구를 사용하여 클라이언트 응용 프로그램 빌드
Microsoft Dynamics 365에 대한 개발 학습 자습서 및 리소스

Microsoft Dynamics 365

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