다음을 통해 공유


샘플: 샌드박스가 적용된 플러그 인에서 웹 액세스

 

게시 날짜: 2016년 11월

적용 대상: Dynamics CRM 2015

요구 사항

이 샘플 코드는 Microsoft Dynamics CRM 2015 및 Microsoft Dynamics CRM Online 2015 업데이트용입니다.Microsoft Dynamics CRM SDK 패키지를 다운로드합니다. 다운로드 패키지의 다음 위치에서 확인할 수 있습니다.

SDK\SampleCode\CS\Plugins\WebClientPlugin.cs

Microsoft Dynamics 365 서버의 샌드박스에서 실행할 컴파일된 플러그 인을 등록합니다.

보여 주기

웹(네트워크) 액세스가 있는 플러그 인을 코딩하고 샌드박스에 등록하는 방법을 보여 줍니다.

예제


using System;
using System.Globalization;
using System.IO;
using System.Text;
using System.Net;

// Microsoft Dynamics CRM namespace(s)
using Microsoft.Xrm.Sdk;

namespace Microsoft.Crm.Sdk.Samples
{
    /// <summary>
    /// A sandboxed plug-in that can access network (Web) resources.
    /// </summary>
    /// <remarks>Register this plug-in in the sandbox. You can provide an unsecure string
    /// during registration that specifies the Web address (URI) to access from the plug-in.
    /// </remarks>
    public sealed class WebClientPlugin : IPlugin
    {
        private string webAddress;

        /// <summary>
        /// The plug-in constructor.
        /// </summary>
        /// <param name="config">The Web address to access. An empty or null string
        /// defaults to accessing www.bing.com. The Web address can use the HTTP or
        /// HTTPS protocol.</param>
        public WebClientPlugin(string config)
        {
            if (String.IsNullOrEmpty(config))
            {
                webAddress = "https://www.bing.com";
            }
            else
            {
                webAddress = config;
            }
        }

        /// <summary>
        /// Main execute method that is required by the IPlugin interface. Uses the WebClient 
        /// .NET class to access the target Web address.
        /// </summary>
        /// <param name="serviceProvider">The service provider from which you can obtain the
        /// tracing service, plug-in execution context, organization service, and more.</param>
        public void Execute(IServiceProvider serviceProvider)
        {
            //Extract the tracing service for use in plug-in debugging.
            ITracingService tracingService = 
                (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            try
            {
                tracingService.Trace("Downloading the target URI: " + webAddress);

                try
                {
                    // Download the target URI using a Web client. Any .NET class that uses the
                    // HTTP or HTTPS protocols and a DNS lookup should work.
                    using (WebClient client = new WebClient())
                    {
                        byte[] responseBytes = client.DownloadData(webAddress);
                        string response = Encoding.UTF8.GetString(responseBytes);
                        tracingService.Trace(response);

                        // For demonstration purposes, throw an exception so that the response
                        // is shown in the trace dialog of the Microsoft Dynamics CRM user interface.
                        throw new InvalidPluginExecutionException("WebClientPlugin completed successfully.");
                    }
                }

                catch (WebException exception)
                {
                    string str = string.Empty;
                    if (exception.Response != null)
                    {
                        using (StreamReader reader = 
                            new StreamReader(exception.Response.GetResponseStream()))
                        {
                            str = reader.ReadToEnd();
                        }
                        exception.Response.Close();
                    }
                    if (exception.Status == WebExceptionStatus.Timeout)
                    {
                        throw new InvalidPluginExecutionException(
                            "The timeout elapsed while attempting to issue the request.", exception);
                    }
                    throw new InvalidPluginExecutionException(String.Format(CultureInfo.InvariantCulture,
                        "A Web exception occurred while attempting to issue the request. {0}: {1}", 
                        exception.Message, str), exception);
                }
            }
            catch (Exception e)
            {
                tracingService.Trace("Exception: {0}", e.ToString());
                throw;
            }
        }
    }
}

참고 항목

IPlugin
ITracingService
플러그 인 개발
플러그 인 작성
플러그 인 격리, 트러스트 및 통계

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