Del via


Web-API-hjælpekode: konfiguration af klasser

 

Udgivet: januar 2017

Gælder for: Dynamics 365 (online), Dynamics 365 (on-premises), Dynamics CRM 2016, Dynamics CRM Online

Brug klassehierarki for konfigurationen til at angive de krævede forbindelsesdata for at få adgang til Dynamics 365-webtjenester fra dit program. Du kan også angive disse forbindelsesdata ved at angive værdier direkte i koden, muligvis fra brugerinput ved hjælp af Configuration-basisklassen. Som de fleste kan du også angive disse oplysninger i de indstillinger, der gemmes i programmets konfigurationsfil ved hjælp af den afledte klasse FileConfiguration.

Kildekoden for klassehierarkiet for konfigurationen er placeret i filen Configuration.cs i CRM SDK Web API-hjælperbiblioteket. Klassehierarkiet for konfigurationen er designet til at arbejde sammen med Authentication-klassen, så du kan oprette en sikker forbindelse til Dynamics 365-tjenesten. Du kan finde flere oplysninger under Brug af Microsoft Dynamics 365 Web API Helper-bibliotek (C#).

Forbindelsesdata

Configuration-klassen læser og analyserer programkonfigurationsfilen for at få følgende forbindelsesdata.

Forbindelsesdata

Installationer

Beskrivelse

URL-adresse til tjeneste

Alle

URL-rodadressen til Dynamics 365-tjenesten

Brugernavn

Alle

Det brugernavn, der er registreret i Dynamics 365

Adgangskode

Alle

Adgangskoden for den pågældende bruger

Domæne

Alle

Domænet for Dynamics 365-tjenesten til Active Directory-godkendelse

Klient-id

Kun online og IFD

Klient-ID'et for programmet, som det er registreret i Azure AD for Dynamics 365 (online) eller din Active Directory-lejer for Dynamics 365 (i det lokale miljø) med Installation med adgang via internet.

Omdiriger URL-adresse

Kun online og IFD

Et URI for tilbagekald for det aktuelle program.

Du kan finde flere oplysninger om hentning af et klient-id og en URL-adresse til omdirigering til et program under Gennemgang: Registrere en Dynamics 365-app med Azure Active Directory til brug med Dynamics 365 (online) og Gennemgang: Registrere en Dynamics 365-app med Active Directory til brug med Dynamics 365 (i det lokale miljø) ved hjælp af Installation med adgang via internet.

Indstillinger for FileConfiguration-forbindelse

De fleste af eksemplerne for Dynamics 365 Web API bruger den afledte klasse, FileConfiguration, til at udtrække forbindelsesdataene fra programkonfigurationsfilen App.config. Denne fil har flere programindstillinger, der gælder for de forskellige installationstilstande for Dynamics 365 Server. Indstillingen for connectionString indeholder tjenestens URL-adresse og brugernavnet. Indstillingerne for ClientId og RedirectUrl er også påkrævede ved onlineinstallation eller installation med adgang via internettet (IFD). Følgende linjer er et uddrag fra standardfilen App.config, som findes i de fleste Web API-eksempler, og indeholder disse forbindelsesdata som pladsholderværdier. Du skal erstatte disse pladsholdere med værdier, der er specifikke for den aktuelle bruger, Dynamics 365-serveren og klientprogrammet.

<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>

Det samlede indhold af standardkonfigurationsfilen findes i Liste over standardkonfigurationsfiler.

Klassehierarki og medlemmer

Følgende tabel viser de offentlige medlemmer af klassehierarkiet for konfigurationen.

Konfigurationsklassediagram til Dynamics 365 Web API Helper-bibliotek

Konfigurationsklasse

Egenskaber:

Alle egenskaber knyttes direkte til de tilsvarende forbindelsesdata, der er beskrevet i forrige afsnit.


Metoder:

Standardkonstruktøren lader alle egenskaber være ikke-initialiserede (null).

FileConfiguration-klasse

Egenskaber:

Name er navnet på posten for forbindelsesstrengens indstilling.

PathToConfig er den komplette eller relative sti til programmets konfigurationsfil.


Metoder:

Standardkonstruktøren lader alle egenskaber være ikke-initialiserede (null).

Ikke-standardkonstruktøren tager en enkelt strengparameter, der angiver den navngivne forbindelsesstreng. En tom streng eller en null-strengværdi resulterer i den første forbindelsesstrengpost, der bruges.

Metoden Load åbner, læser og analyserer den angivne konfigurationsfil. Den bruges af ikke-standardkonstruktøren.

Brug

Klasserne FileConfiguration og Authentication er designet til at blive brugt sammen til at læse forbindelsesoplysningerne i App.config og derefter oprette en sikker forbindelse til Dynamics 365-destinationstjenesten. Det kan implementeres med følgende sætninger.

FileConfiguration config = new FileConfiguration(null);
Authentication auth = new Authentication(config);
httpClient = new HttpClient(auth.ClientHandler, true);

Ikke-standardkonstruktøren i Configuration-klassen tillader brug af en navngiven forbindelsesstreng, for eksempel:

Configuration config = new FileConfiguration(“TestServer”);

Hvis en null-værdi eller et tomt forbindelsesstrengnavn overføres til FileConfiguration-klassekonstruktøren, bruges den første forbindelsesstreng fra toppen af konfigurationsfilen.

Desuden understøtter SDK-eksempler en kommandoparameter for kørsel, som repræsenterer navnet på den ønskede forbindelsesstreng, der skal overføres til konstruktøren. Denne indstilling er implementeret af følgende kode:

if (cmdargs.Length > 0)
{
    config = new FileConfiguration(cmdargs[0]);
}
else
{
    config = new FileConfiguration(null);
}

Søgerækkefølge for konfiguration

Uanset om du anvender standardindstillingen eller en brugerdefineret programkonfigurationsfil, kan den valgfrie AlternateConfig-programindstilling leveres i filen for at angive en alternativ konfigurationsfil. Hvis denne fil findes, bruges dens forbindelsesindstillinger i stedet.

<add key="AlternateConfig" value="C:\Temp\crmsample.exe.config"/>

Et almindeligt formål med denne indstilling er at levere en global konfigurationsfil, som kan deles mellem flere programmer, i stedet for at redigere hvert programs App.config-fil. Dette er især nyttigt ved deling af konfigurations- og registreringsoplysninger mellem flere programmer, der bevæger sig igennem udviklings- og testfaser. Derefter skal du kun angive entydige konfigurations- og registreringsoplysninger for hvert program i forbindelse med produktion.

Liste over standardkonfigurationsfiler

Filen App.config, der leveres med de fleste Dynamics 365 Web API-eksempler, indeholder pladsholderværdier for forbindelsen, der skal redigeres af udvikleren eller webstedsadministratoren.

<?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>

Klasseliste

Den mest aktuelle kilde for denne klasse findes i CRM SDK Web API-hjælperbibliotekets NuGet-pakke.

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
    }
}

Se også

Introduktion til Microsoft Dynamics 365 Web API (C#)
Starte et Dynamics 365 Web API-projekt i Visual Studio (C#)
Brug af Microsoft Dynamics 365 Web API Helper-bibliotek (C#)
Web API Helper-kode: godkendelsesklasse
Web API Helper-kode: CrmHttpResponseException-klasse

Microsoft Dynamics 365

© 2017 Microsoft. Alle rettigheder forbeholdes. Ophavsret