共用方式為


範例:在 XRM 工具 API 的快速開始

 

發行︰ 2017年1月

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

QuickStart 範例是一種 Microsoft .NET Framework 受管理的程式碼範例,它能透過使用 XRM 工具 API 展現連結至 Microsoft Dynamics 365 執行個體的方式,並執行基本的建立、更新以及在實體中刪除作業的方式。 如需 XRM 工具的詳細資訊,請參閱 使用 XRM 工具,建立 Windows 用戶端應用程式

需求

這個範例程式碼適用於 Microsoft Dynamics 365 (線上和內部部署)。 下載 Microsoft Dynamics CRM SDK 套件。 可以在下列位置的下載套件中找到:

SDK\SampleCode\CS\XRMTooling

示範

  • 此程式碼範例是用 Dynamics 365 的 WPF 應用程式 SDK 範本 (其中提供一種含有內建支援認證和憑證快取與重新使用的常見登入控制項)。 如需一般登入控制項以及如何在 Microsoft Visual Studio 中使用 SDK 範本的詳細資訊,請參閱 在您的用戶端應用程式中使用 XRM 工具一般登入控制項

  • Helper 程式碼不會用來建立與 Dynamics 365的連線。

  • 在連線至 Dynamics 365之後,範例會執行建立,更新,擷取,並刪除客戶實體的作業。

  • 在設定檔 (Default_QuickStartXRMToolingWPFClient.exe.config) 儲存使用者認證,儲存路徑為 c:\Users\<username>\AppData\Roaming\Microsoft\QuickStartXRMToolingWPFClient 資料夾,當範例第一次執行時,且在之後會提示使用者在執行階段使用已儲存或指定新的認證來登入 Dynamics 365。

  • 產生以下記錄檔,如果發生任何問題,將可協助疑難排解:

    • Login_ErrorLog.log:回報登入錯誤。 此檔案位於 C:\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 工具,建立 Windows 用戶端應用程式
了解 Microsoft Dynamics 365 開發的教學課程和資源

Microsoft Dynamics 365

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