Chapter 15. Additional Samples and Utilities

By now you are well versed in how to extend and develop custom business logic with Microsoft Dynamics CRM 4.0. To conclude, we want to share some additional code examples and useful utilities. This chapter will describe some helpful classes and an export customizations utility that you can immediately use with your Microsoft Dynamics CRM development. Lastly, we will delve into some additional sample script ideas, including a full demonstration of using script and two custom entities to implement basic form-based, field-level security.

Remember that you can download all of the source code for your own use. Please see the Introduction for the download URL.

This chapter covers the following topics:

  • Various utility classes

  • Customizations utility

  • Additional script examples

  • Field-level security

Utility Classes

This section provides a few helpful utility classes that you can include in your projects. These classes, included in the following list, provide common actions you will take during the course of your development with Microsoft Dynamics CRM:

  • CrmServiceUtility

  • DynamicEntityUtility

  • MetadataUtility

Example 15-1 demonstrates a class that exposes three static methods:

  • GetCrmService

  • GetMetadataService

  • GetServerUrlFromRegistry

GetCrmService allows you to easily return an instance of the CrmService object using the current user’s default credentials. This service works for both IFD and on-premise deployments. Similarly, the GetMetadataService method returns an instance of the MetadataService object. The GetServerURLFromRegistry method provides a quick way to access the Microsoft Dynamics CRM Web server ServerUrl value from the registry.

Example 15-1. The CrmServiceUtility class

public static class CrmServiceUtility
{
  /// <summary>
  /// Creates an instance of a CrmService.
  /// </summary>
  /// <param name="crmServerUrl">The URL of the CRM server.
  /// Path does not need to be included.</param>
  /// <param name="organizationName">The name of the CRM organization.</param>
  /// <returns>A new CrmService instance.</returns>
  public static CrmService GetCrmService(string crmServerUrl,
   string organizationName)
  {
    CrmAuthenticationToken token = new CrmAuthenticationToken();
    token.OrganizationName = organizationName;

    CrmService service = new CrmService();

    if (!String.IsNullOrEmpty(crmServerUrl))
    {
      UriBuilder builder = new UriBuilder(crmServerUrl);
      builder.Path = "/MSCRMServices/2007/CrmService.asmx";
      service.Url = builder.Uri.ToString();
    }

    service.UseDefaultCredentials = true;
    service.CrmAuthenticationTokenValue = token;

    return service;
  }

  /// <summary>
  /// Creates an instance of a MetadataService.
  /// </summary>
  /// <param name="crmServerUrl">The URL of the CRM server.
  /// Path does not need to be included.</param>
  /// <param name="organizationName">The name of the CRM organization.</param>
  /// <returns>A new MetadataService instance.</returns>
  public static MetadataService GetMetadataService(string crmServerUrl,
    string organizationName)
  {
    CrmAuthenticationToken token = new CrmAuthenticationToken();
    token.OrganizationName = organizationName;

    MetadataService service = new MetadataService();

    if (!String.IsNullOrEmpty(crmServerUrl))
    {
      UriBuilder builder = new UriBuilder(crmServerUrl);
      builder.Path = "/MSCRMServices/2007/MetadataService.asmx";
      service.Url = builder.Uri.ToString();
    }

    service.UseDefaultCredentials = true;
    service.CrmAuthenticationTokenValue = token;

    return service;
  }

  public static string GetServerURLFromRegistry()
  {
    using (RegistryKey mscrmKey =
     Registry.LocalMachine.OpenSubKey(@"SOFTWAREMicrosoftMSCRM"))
    {
      if (mscrmKey != null)
      {
        string serverUrl = (string)mscrmKey.GetValue("ServerUrl");
        if (!String.IsNullOrEmpty(serverUrl))
        {
          return serverUrl;
        }
      }
    }

    return String.Empty;
  }
}

Example 15-2 shows that the DynamicEntityUtility class provides one static method, GetPropertyValue, which uses reflection to return the value from a dynamic entity property.

Example 15-2. The DynamicEntityUtility class

public static class DynamicEntityUtility
{
  public static string GetPropertyValue(object value)
  {
    string returnValue = String.Empty;

    // checking for a name property
    // this way we can show the text value instead of a guid
    // for types of lookup, customer, and owner
    PropertyInfo prop = value.GetType().GetProperty("name");

    if (prop != null)
    {
      value = prop.GetValue(value, null);
    }
    else
    {
      prop = value.GetType().GetProperty("Value");
      if (prop != null)
      {
          value = prop.GetValue(value, null);
      }
    }

    returnValue = value.ToString();

    return returnValue;
  }
}

MetadataUtility Class

The MetadataUtility class provides a couple of helpful utilities for working with Microsoft Dynamics CRM’s metadata. The class provides a way to easily retrieve and, more importantly, cache the metadata. Example 15-3 shows the source code for this class.

Example 15-3. The MetadataUtility class

public static class MetadataUtility
{
  private static Dictionary<string, AttributeMetadata> _attributeCache;
  private static object _attributeCacheLock = null;

  static MetadataUtility()
  {
    _attributeCache = new Dictionary<string, AttributeMetadata>();
    _attributeCacheLock = new object();
  }


  public static AttributeMetadata RetrieveAttributeMetadata(
   MetadataService metadataService, string entityName, string attributeName)
  {
    string key = GetAttributeKey(entityName, attributeName);
    AttributeMetadata attributeMetadata = null;

    if (!_attributeCache.TryGetValue(key, out attributeMetadata))
    {
      lock (_attributeCacheLock)
      {
        if (!_attributeCache.TryGetValue(key, out attributeMetadata))
        {
          RetrieveAttributeRequest attributeRequest =
           new RetrieveAttributeRequest();
          attributeRequest.EntityLogicalName = entityName;
          attributeRequest.LogicalName = attributeName;
          RetrieveAttributeResponse attributeResponse =
           (RetrieveAttributeResponse)metadataService.Execute(attributeRequest);
          attributeMetadata = attributeResponse.AttributeMetadata;
          _attributeCache.Add(key, attributeMetadata);
        }
      }
    }
    return attributeMetadata;
  }

  private static string GetAttributeKey(string entityName, string attributeName)
  {
    return String.Format("{0}.{1}", entityName, attributeName);
  }
}
..................Content has been hidden....................

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