Chapter 8. Developing with the Metadata Service

As you learned earlier in this book, Microsoft Dynamics CRM includes a MetadataService Web service that allows you to programmatically read and modify the system schema. The MetadataService Web service exposes the same functionality that system customizers can access through the Web-based customization tools. The Microsoft Dynamics CRM metadata repository is effectively a stand-alone, middle-tier application. It stores and manages the metadata for the CRM application itself.

By working with the MetadataService, you can perform the following types of actions:

  • Retrieve the metadata for a specific entity, either system or custom.

  • Retrieve the attributes for an entity.

  • Retrieve the metadata for a specific attribute, such as the possible state names or picklist values for an attribute.

  • Create a custom entity.

  • Add or update an attribute for an entity, either system or custom.

  • Create or delete a relationship between two entities.

  • Retrieve all the metadata to create a metadata cache in a client application.

  • Determine whether metadata has changed since it was previously retrieved.

  • Retrieve all the entities and determine which ones are custom entities.

  • Add or remove an option from a picklist attribute.

  • Write an install and uninstall program for your custom solution.

  • Add and remove schemas for the purposes of deploying a solution. (Chapter 9, covers this scenario in specific detail.)

The prior version of Microsoft Dynamics CRM (version 3.0) also included a MetadataService Web service, but that version of the API allowed you only to read metadata; you could not modify the metadata. The ability to modify the schema through the MetadataService endpoint was added in Microsoft Dynamics CRM 4.0. (You might hear people refer to the Microsoft Dynamics CRM 3.0 MetadataService Web service as the 2006 endpoint.)

As listed above, the editable metadata service opens up all sorts of new and interesting programming options. For example, one tool that makes heavy use of the MetadataService is the Microsoft Dynamics CRM Data Migration Manager (DMM). As a stand-alone application, the DMM uses the metadata APIs to conduct its schema manipulation (used to extend the schema during data import). Figure 8-1 shows the Data Migration Manager and how to create a custom entity in its user interface. As a developer, you can use the metadata to develop your own unique Microsoft Dynamics CRM solutions.

Data Migration Manager performing remote customization

Figure 8-1. Data Migration Manager performing remote customization

In this chapter, we’ll cover the following topics:

  • Connecting to the MetadataService

  • Retrieving metadata

  • Remote customization

  • Caching metadata

  • Handling errors

Connecting to the MetadataService

The first step to work with the MetadataService is to connect to the API. Chapter 3, includes a detailed look at the various approaches related to connecting to the Microsoft Dynamics CRM APIs, but we will quickly review some of the key concepts here.

Referencing the MetadataService

The MetadataService supports all three deployment models: on-premise, Internet-facing deployment (IFD), and Windows Live ID (for Microsoft Dynamics CRM Online). You have the same options when accessing the MetadataService Web service as with the CrmService. To refresh the information provided earlier, you can include a reference to the service by one of the following approaches:

  • Access the Web reference URL directly in Visual Studio 2008.

  • Download the WSDL definition to the file system and add the Web reference locally.

  • Reference the Microsoft.Crm.Sdk and Microsoft.Crm.SdkTypeProxy assemblies.

Because the MetadataService schema does not change, you should consider using the proxy assemblies to access the MetadataService functionality.

Be sure that you have the following namespaces included in your code:

  • Microsoft.Crm.Sdk

  • Microsoft.Crm.Sdk.Metadata

  • Microsoft.Crm.SdkTypeProxy.Metadata

After you have the metadata service referenced in your code and are able to compile it, you still need to provide a valid endpoint for run-time use. We will now discuss the options available to configure the MetadataService endpoint.

Locating the Endpoints

You can locate the MetadataService’s endpoint (metadataservice.asmx) using several different techniques, and each option offers its own benefits and constraints, as discussed in Chapter 3. You should use caution before assuming that you know a Web service endpoint based on the URL of the user interface. Because the Enterprise edition of Microsoft Dynamics CRM supports role-based server deployments, it is possible that the server (or servers) hosting the API is different from the server hosting the Web user interface. Always use the appropriate mechanisms, detailed in the following section, to locate this URL. The main options to locate the MetadataService endpoints are:

  • Use a setting within your application to specify the endpoint.

  • Use the Microsoft Dynamics CRM DiscoveryService Web service to locate the MetadataService URL.

  • Access IMetadataService through a plug-in.

  • Connect to the offline MetadataService URL.

Application Settings

Commonly, you will want to write applications that allow the MetadataService endpoint to be specified in a configuration file or registry entry. This allows the most control over the endpoint location and still permits it to be specified at deployment. If your application is located on the Microsoft Dynamics CRM 4.0 server, it can access a registry key maintained by Microsoft Dynamics CRM 4.0 itself. The following code demonstrates the simplest way to access the service endpoint.

public static MetadataService GetMetadataService(string organizationName)
  {
    CrmAuthenticationToken token = new CrmAuthenticationToken();
    token.OrganizationName = organizationName;

    MetadataService service = new MetadataService();
    // Replace <crmserver> with your own value
    service.Url = "http://<crmserver>/MSCRMServices/2007/MetadataService.asmx";
    service.UseDefaultCredentials = true;
    service.CrmAuthenticationTokenValue = token;

    return service;
  }

For the sake of brevity, we will use the GetMetadataService method throughout the sample code in the remainder of this chapter.

Discovery Service

You use the CrmMetadataServiceUrl property of the OrganizationDetail object to determine the URL of the MetadataService, as demonstrated in the following code sample:

string orgName = "contoso";
string metadataServiceUrl;

CrmDiscoveryService discoveryService = new CrmDiscoveryService();
discoveryService.Credentials = CredentialCache.DefaultCredentials;
// Replace localhost with the correct URL for your application
discoveryService.Url = "http://localhost/MSCRMServices/2007/AD/CrmDiscoveryService.asmx";

RetrieveOrganizationsRequest retrieveOrgRequest = new RetrieveOrganizationsRequest();
RetrieveOrganizationsResponse retrieveOrgResponse =
    (RetrieveOrganizationsResponse)discoveryService.Execute(retrieveOrgRequest);

foreach (OrganizationDetail orgDetail in retrieveOrgResponse.OrganizationDetails)
{
    if (orgDetail.OrganizationName == orgName)
    {
        metadataServiceUrl = orgDetail.CrmMetadataServiceUrl;
        break;
    }
}

You should consider using the Discovery service option when you are unsure of the actual endpoints of your final deployment or when you are using Microsoft Dynamics CRM Online.

Plug-ins

Just as the ICrmService interface is provided to plug-ins for accessing the CrmService Web service API from within a plug-in, an interface is also exposed for the MetadataService. This interface is called IMetadataService and is generated using the CreateMetadataService method on the IPluginExecutionContext object, as shown in the following code:

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Crm.Sdk;
using Microsoft.Crm.SdkTypeProxy;

namespace MetadataPluginSample
{
    public class MyPlugin : IPlugin
    {
        public void Execute(IPluginExecutionContext context)
        {
             IMetadataService metadataService = context.CreateMetadataService(true);
        }
    }
}

More Info

More Info

Please review Chapter 5, for more information regarding plug-ins and the IPluginExecutionContext object.

Offline

The MetadataService is also available in Microsoft Dynamics CRM for Outlook with Offline Access. Chapter 3 details how to locate and configure the URL endpoint and offline development is covered extensively in Chapter 10.

The offline client’s middle tier does not support customization, and subsequently not all MetadataService messages are available while offline. Only the following messages are available:

  • RetrieveAllEntitiesRequest

  • RetrieveAllEntitiesResponse

  • RetrieveEntityRequest

  • RetrieveEntityResponse

  • RetrieveAttributeRequest

  • RetrieveAttributeResponse

  • RetrieveRelationshipRequest

  • RetrieveRelationshipResponse

  • RetrieveTimestampRequest

  • RetrieveTimestampResponse

Using the MetadataService with the CrmImpersonator Class

Chapter 3 introduced the CrmImpersonator class as a way to seamlessly authenticate with IFD deployments. Take special care when using the MetadataService with the CrmImpersonator class. Because of the way the CrmImpersonator class operates, you should avoid using the discovery service for locating the endpoint. Either manually set the endpoint from a configuration setting or use the registry.

The following sample code shows how to access the MetadataService Web service from the registry when using the impersonation pattern with the metadata service:

//Retrieve Server URL from the Registry
string metadataServiceUrl;
using (RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\Microsoft\MSCRM"))
{
    metadataServiceUrl =
        key.GetValue("ServerUrl").ToString() + "/2007/metadataservice.asmx";
}

//Wrap Code in Using statement
using (new CrmImpersonator())
{
    CrmAuthenticationToken token =
     CrmAuthenticationToken.ExtractCrmAuthenticationToken(Context,"MyOrganizationName");
    token.AuthenticationType = 0;
    token.OrganizationName = "MyOrganizationName";
    MetadataService metadataService = new MetadataService();
    metadataService.CrmAuthenticationTokenValue = token;
    metadataService.Credentials = CredentialCache.DefaultCredentials;
    metadataService.Url = metadataServiceUrl;
}

Endpoint

As we mentioned earlier, the 3.0 version of Microsoft Dynamics CRM included a MetadataService Web service. The URL of this Web service is http://<crmserver>/mscrm-services/2006/metadataservice.asmx. Even though Microsoft Dynamics CRM 4.0 includes a new MetadataService, you can still access the 3.0 service. Some developers refer to this Web service as the 2006 endpoint (because of the 2006 in its URL) and the 4.0 Web service is known as the 2007 endpoint.

The capabilities of the 2006 endpoint service differ significantly from the 2007 endpoint. The 2006 endpoint is only capable of reading the metadata, and you can only connect to the default organization. When writing new code, you should only use the 2007 endpoint. Microsoft included the 2006 endpoint in Microsoft Dynamics CRM 4.0 for backward compatibility for customers upgrading from Microsoft Dynamics CRM 3.0 to 4.0.

Microsoft Dynamics CRM Security

As with core entities, Microsoft Dynamics CRM 4.0 also contains a set of security privileges for many of the common metadata components, such as entities, attributes, and relationships. At a minimum, the user executing the MetadataService call will need to have read privileges for the specific metadata being operated on. Figure 8-2 shows a sample Microsoft Dynamics CRM security role listing the metadata privileges.

Metadata privileges

Figure 8-2. Metadata privileges

Note

Note

Microsoft Dynamics CRM 3.0 did not enforce privileges for MetadataService calls. When upgrading your code to Microsoft Dynamics CRM 4.0, be sure to appropriately update the security roles of your users for any MetadataService interaction.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset