Export (0) Print
Expand All

Create a Picklist with Labels in Multiple Languages

banner art

[Applies to: Microsoft Dynamics CRM 4.0]

This sample shows how to add multiple language labels to a picklist item.

This sample code can be found in the following files in the SDK download:

Server\HowTo\CS\Metadata\HowToMetadata.cs
Server\HowTo\VB\Metadata\HowToMetadata.vb

For more information about the helper methods in the Microsoft.Crm.Sdk.Utility.CrmServiceUtility namespace, see Utility Sample Code.

Example

[C#]
using System;
using System.Xml;
using System.Collections;
using Microsoft.Crm.Sdk.Utility;
using System.Web.Services.Protocols;

namespace Microsoft.Crm.Sdk.HowTo
{
    using CrmSdk;
    using MetadataServiceSdk;
   /// <summary>
   /// This sample shows how to add multiple language labels to a picklist item.
   /// A sample XML string table is used for storing all localized text.
   /// </summary>
   public class MultiLanguagePicklist
   {
        static void Main(string[] args)
        {
            bool success = false;

            try
            {
                // TODO: Change the service URL, organization and supported language code to match
                // your Microsoft Dynamics CRM server installation.
                success = MultiLanguagePicklist.Run("http://localhost:5555", "AdventureWorksCycle", "1031");
            }
            catch (SoapException ex)
            {
                Console.WriteLine("The application terminated with an error.");
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.Detail.InnerText);
            }
            catch (System.Exception ex)
            {
                Console.WriteLine("The application terminated with an error.");
                Console.WriteLine(ex.Message);

                // Display the details of the inner exception.
                if (ex.InnerException != null)
                {
                    Console.WriteLine(ex.InnerException.Message);

                    SoapException se = ex.InnerException as SoapException;
                    if (se != null)
                        Console.WriteLine(se.Detail.InnerText);
                }
            }
            finally
            {
                Console.WriteLine("Completed successfully? {0}", success);
                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
      
      public static bool Run(string crmServerUrl, string orgName, string supportedLangCode)
      {
         bool success = true;

         try
         {
            // Store multi-language picklist option values
            // NOTE: The XML below is a solution for storing localized string text that 
            //       is specific to this sample.  The {LCID_TOKEN} in the XML is designed 
            //       to allow for an unknown supported language code to be passed in.  Typically,
            //       all supported languages are known and the use of a token is not necessary.
            string localizedStringTableXml =
            @"<picklistOptions> 
               <picklistOption>
                  <locData langCode='1033' labelText='created'></locData>
                  <locData langCode='{LCID_TOKEN}' labelText='translatedText'></locData>
               </picklistOption>
               <picklistOption>
                  <locData langCode='1033' labelText='updated'></locData>
                  <locData langCode='{LCID_TOKEN}' labelText='translatedText'></locData>
               </picklistOption>
               <picklistOption>
                  <locData langCode='1033' labelText='deleted'></locData>
                  <locData langCode='{LCID_TOKEN}' labelText='translatedText'></locData>
               </picklistOption>
               <displayName>
                  <locData langCode='1033' labelText='Sample Picklist'></locData>
                  <locData langCode='{LCID_TOKEN}' labelText='translatedText'></locData>
               </displayName>
               <description>
                  <locData langCode='1033' labelText='Picklist Attribute'></locData>
                  <locData langCode='{LCID_TOKEN}' labelText='translatedText'></locData>
               </description>
            </picklistOptions>";

            // Replace language code token with actual supported language code value
            string stringTableXml = localizedStringTableXml.Replace("{LCID_TOKEN}", supportedLangCode);
            
            // Build XML objects for processing localization text
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(stringTableXml);
            XmlNodeList picklistOptionNodes = xmlDoc.SelectNodes("//picklistOption");
            XmlNode displayNameNode = xmlDoc.SelectSingleNode("//displayName");
            XmlNode descriptionNode = xmlDoc.SelectSingleNode("//description");

            // Set up the CRM Services.
            MetadataService metadataService = Microsoft.Crm.Sdk.Utility.CrmServiceUtility.GetMetadataService(crmServerUrl, orgName);
            metadataService.PreAuthenticate = true;

            // This service is required for publishing changes to Microsoft CRM metadata
            CrmService service = Microsoft.Crm.Sdk.Utility.CrmServiceUtility.GetCrmService(crmServerUrl, orgName);
            service.PreAuthenticate = true;

                // Create a picklist attribute   
            PicklistAttributeMetadata pickListAttribute = new PicklistAttributeMetadata();

            // Set picklist base properties
            pickListAttribute.SchemaName = "new_multi_picklist";
            pickListAttribute.DisplayName = CreateMultiLanguageLabel(displayNameNode.ChildNodes);
            pickListAttribute.RequiredLevel = new CrmAttributeRequiredLevel();
            pickListAttribute.RequiredLevel.Value = AttributeRequiredLevel.None;
            pickListAttribute.EntityLogicalName = EntityName.contact.ToString();
            pickListAttribute.LogicalName = "new_action";
            pickListAttribute.Description = CreateMultiLanguageLabel(descriptionNode.ChildNodes);
            pickListAttribute.AttributeType = new MetadataServiceSdk.CrmAttributeType();
            pickListAttribute.AttributeType.Value = AttributeType.Picklist;

            // Set picklist extended properties
            pickListAttribute.Options = CreateOptions(picklistOptionNodes);

            // Create the request
            CreateAttributeRequest createAttribute = new CreateAttributeRequest();
            createAttribute.EntityName = EntityName.contact.ToString();
            createAttribute.Attribute = pickListAttribute;
            
            // Execute the request
            CreateAttributeResponse attributeResponse = (CreateAttributeResponse)metadataService.Execute(createAttribute);

            // Publish the new customizations
            // NOTE:  The custom attribute cannot be used until it has been published.
            PublishAllXmlRequest publishAllRequest = new PublishAllXmlRequest();
            PublishAllXmlResponse publishAllResponse = (PublishAllXmlResponse)service.Execute(publishAllRequest);

            #region check success

            // Retrieve each attribute to verify it was created correctly
            RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest();
            attributeRequest.EntityLogicalName = EntityName.contact.ToString();
            attributeRequest.RetrieveAsIfPublished = true;
            attributeRequest.LogicalName = "new_multi_picklist";

            RetrieveAttributeResponse retrieveResponse = (RetrieveAttributeResponse)metadataService.Execute(attributeRequest);
            PicklistAttributeMetadata picklistAttributeMetadata = (PicklistAttributeMetadata)retrieveResponse.AttributeMetadata;
            // Select the first option and check each of its loclabes
            bool testLabelFound = false; 
            foreach (Option picklistOption in picklistAttributeMetadata.Options)
            {
               foreach (MetadataServiceSdk.LocLabel aLocLabel in picklistOption.Label.LocLabels)
               {
                  if (aLocLabel.Label == "created")
                  {
                     testLabelFound = true;
                  }
               }
            }
            
            if (!testLabelFound)
            {
               success = false;
            }
            
            #endregion

            #region Remove Data Required for this Sample

            // Create the request
            DeleteAttributeRequest deleteAttribute = new DeleteAttributeRequest();
            deleteAttribute.LogicalName = "new_multi_picklist";
            deleteAttribute.EntityLogicalName = EntityName.contact.ToString();

            // Execute the request
            DeleteAttributeResponse deleteResponse = (DeleteAttributeResponse)metadataService.Execute(deleteAttribute);

            #endregion
         }
            catch
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }

         return success;
      }

      /// <summary>
      /// Create an array of Options (the base class for picklist)
      /// </summary>
      /// <param name="picklistOptionNodes">All picklist option text and language codes</param>
      /// <returns>Array of Options</returns>
      private static Option[] CreateOptions(XmlNodeList picklistOptionNodes)
      {
         // Build a list of all picklist options
         ArrayList crmPicklistOptions = new ArrayList();
         
         // NOTE: In Microsoft CRM 4.0, all new picklist values begin at 200,000 to maintain
         // backwards compatibility with Microsoft CRM 3.0
         int picklistValue = 200000;
         
         foreach (XmlNode picklistOptionNode in picklistOptionNodes)
         {
            Option crmPicklistOption = new Option();
            crmPicklistOption.Value = new MetadataServiceSdk.CrmNumber();
            crmPicklistOption.Value.Value = picklistValue;
            crmPicklistOption.Label = CreateMultiLanguageLabel(picklistOptionNode.ChildNodes); 
            crmPicklistOptions.Add(crmPicklistOption);
            
            picklistValue++;
         }

         return (Option[])crmPicklistOptions.ToArray(typeof(Option));
      }
      
      /// <summary>
      /// Create a multi-language Crm label
      /// </summary>
      /// <param name="locDataNodes">Localized data for each label required</param>
      /// <returns></returns>
      private static MetadataServiceSdk.CrmLabel CreateMultiLanguageLabel(XmlNodeList locDataNodes)
      {
         ArrayList allLocLabels = new ArrayList();

         // Create a new LocLabel for every language.         
         foreach (XmlNode locDataNode in locDataNodes)
         {
            MetadataServiceSdk.CrmNumber langCode = new MetadataServiceSdk.CrmNumber();
            MetadataServiceSdk.LocLabel locLabel = new MetadataServiceSdk.LocLabel();

            // Get the language code and label text for this LocLabel.
            XmlAttributeCollection languageData = locDataNode.Attributes;
            langCode.Value = Convert.ToInt32(languageData["langCode"].Value);

            // Create the LocLabel.
            locLabel.LanguageCode = langCode;
            locLabel.Label = languageData["labelText"].Value;
            allLocLabels.Add(locLabel);
         }

         // Create the CrmLabel with all supported language text.
         MetadataServiceSdk.CrmLabel crmLabel = new MetadataServiceSdk.CrmLabel();
         crmLabel.LocLabels = (MetadataServiceSdk.LocLabel[])allLocLabels.ToArray(typeof(MetadataServiceSdk.LocLabel));

         return crmLabel;
      }
   }
}
[Visual Basic .NET]
Imports System
Imports System.Xml
Imports System.Collections
Imports Microsoft.Crm.Sdk.Utility
Imports System.Web.Services.Protocols
Imports Microsoft.VisualBasic

Imports CrmSdk
Imports MetadataServiceSdk
Namespace Microsoft.Crm.Sdk.HowTo
    ''' <summary>
    ''' This sample shows how to add multiple language labels to a picklist item.
    ''' A sample XML string table is used for storing all localized text.
    ''' </summary>
    Public Class MultiLanguagePicklist
        Shared Sub Main(ByVal args() As String)
            Dim success As Boolean = False

            Try
                ' TODO: Change the service URL, organization and supported language code to match
                ' your Microsoft Dynamics CRM server installation.
                success = MultiLanguagePicklist.Run("http://localhost:5555", "AdventureWorksCycle", "1031")
            Catch ex As SoapException
                Console.WriteLine("The application terminated with an error.")
                Console.WriteLine(ex.Message)
                Console.WriteLine(ex.Detail.InnerText)
            Catch ex As System.Exception
                Console.WriteLine("The application terminated with an error.")
                Console.WriteLine(ex.Message)

                ' Display the details of the inner exception.
                If ex.InnerException IsNot Nothing Then
                    Console.WriteLine(ex.InnerException.Message)

                    Dim se As SoapException = TryCast(ex.InnerException, SoapException)
                    If se IsNot Nothing Then
                        Console.WriteLine(se.Detail.InnerText)
                    End If
                End If
            Finally
                Console.WriteLine("Completed successfully? {0}", success)
                Console.WriteLine("Press <Enter> to exit.")
                Console.ReadLine()
            End Try
        End Sub

        Public Shared Function Run(ByVal crmServerUrl As String, ByVal orgName As String, ByVal supportedLangCode As String) As Boolean
            Dim success As Boolean = True

            Try
                ' Store multi-language picklist option values
                ' NOTE: The XML below is a solution for storing localized string text that 
                '       is specific to this sample.  The {LCID_TOKEN} in the XML is designed 
                '       to allow for an unknown supported language code to be passed in.  Typically,
                '       all supported languages are known and the use of a token is not necessary.
                Dim localizedStringTableXml As String = "<picklistOptions> " & ControlChars.CrLf & "               <picklistOption>" & ControlChars.CrLf & "                  <locData langCode='1033' labelText='created'></locData>" & ControlChars.CrLf & "                  <locData langCode='{LCID_TOKEN}' labelText='translatedText'></locData>" & ControlChars.CrLf & "               </picklistOption>" & ControlChars.CrLf & "               <picklistOption>" & ControlChars.CrLf & "                  <locData langCode='1033' labelText='updated'></locData>" & ControlChars.CrLf & "                  <locData langCode='{LCID_TOKEN}' labelText='translatedText'></locData>" & ControlChars.CrLf & "               </picklistOption>" & ControlChars.CrLf & "               <picklistOption>" & ControlChars.CrLf & "                  <locData langCode='1033' labelText='deleted'></locData>" & ControlChars.CrLf & "                  <locData langCode='{LCID_TOKEN}' labelText='translatedText'></locData>" & ControlChars.CrLf & "               </picklistOption>" & ControlChars.CrLf & "               <displayName>" & ControlChars.CrLf & "                  <locData langCode='1033' labelText='Sample Picklist'></locData>" & ControlChars.CrLf & "                  <locData langCode='{LCID_TOKEN}' labelText='translatedText'></locData>" & ControlChars.CrLf & "               </displayName>" & ControlChars.CrLf & "               <description>" & ControlChars.CrLf & "                  <locData langCode='1033' labelText='Picklist Attribute'></locData>" & ControlChars.CrLf & "                  <locData langCode='{LCID_TOKEN}' labelText='translatedText'></locData>" & ControlChars.CrLf & "               </description>" & ControlChars.CrLf & "            </picklistOptions>"

                ' Replace language code token with actual supported language code value
                Dim stringTableXml As String = localizedStringTableXml.Replace("{LCID_TOKEN}", supportedLangCode)

                ' Build XML objects for processing localization text
                Dim xmlDoc As New XmlDocument()
                xmlDoc.LoadXml(stringTableXml)
                Dim picklistOptionNodes As XmlNodeList = xmlDoc.SelectNodes("//picklistOption")
                Dim displayNameNode As XmlNode = xmlDoc.SelectSingleNode("//displayName")
                Dim descriptionNode As XmlNode = xmlDoc.SelectSingleNode("//description")

                ' Set up the CRM Services.
                Dim metadataService As MetadataService = Microsoft.Crm.Sdk.Utility.CrmServiceUtility.GetMetadataService(crmServerUrl, orgName)
                metadataService.PreAuthenticate = True

                ' This service is required for publishing changes to Microsoft CRM metadata
                Dim service As CrmService = Microsoft.Crm.Sdk.Utility.CrmServiceUtility.GetCrmService(crmServerUrl, orgName)
                service.PreAuthenticate = True

                ' Create a picklist attribute   
                Dim pickListAttribute As New PicklistAttributeMetadata()

                ' Set picklist base properties
                pickListAttribute.SchemaName = "new_multi_picklist"
                pickListAttribute.DisplayName = CreateMultiLanguageLabel(displayNameNode.ChildNodes)
                pickListAttribute.RequiredLevel = New CrmAttributeRequiredLevel()
                pickListAttribute.RequiredLevel.Value = AttributeRequiredLevel.None
                pickListAttribute.EntityLogicalName = EntityName.contact.ToString()
                pickListAttribute.LogicalName = "new_action"
                pickListAttribute.Description = CreateMultiLanguageLabel(descriptionNode.ChildNodes)
                pickListAttribute.AttributeType = New MetadataServiceSdk.CrmAttributeType()
                pickListAttribute.AttributeType.Value = AttributeType.Picklist

                ' Set picklist extended properties
                pickListAttribute.Options = CreateOptions(picklistOptionNodes)

                ' Create the request
                Dim createAttribute As New CreateAttributeRequest()
                createAttribute.EntityName = EntityName.contact.ToString()
                createAttribute.Attribute = pickListAttribute

                ' Execute the request
                Dim attributeResponse As CreateAttributeResponse = CType(metadataService.Execute(createAttribute), CreateAttributeResponse)

                ' Publish the new customizations
                ' NOTE:  The custom attribute cannot be used until it has been published.
                Dim publishAllRequest As New PublishAllXmlRequest()
                Dim publishAllResponse As PublishAllXmlResponse = CType(service.Execute(publishAllRequest), PublishAllXmlResponse)

                '            #Region "check success"

                ' Retrieve each attribute to verify it was created correctly
                Dim attributeRequest As New RetrieveAttributeRequest()
                attributeRequest.EntityLogicalName = EntityName.contact.ToString()
                attributeRequest.RetrieveAsIfPublished = True
                attributeRequest.LogicalName = "new_multi_picklist"

                Dim retrieveResponse As RetrieveAttributeResponse = CType(metadataService.Execute(attributeRequest), RetrieveAttributeResponse)
                Dim picklistAttributeMetadata As PicklistAttributeMetadata = CType(retrieveResponse.AttributeMetadata, PicklistAttributeMetadata)
                ' Select the first option and check each of its loclabes
                Dim testLabelFound As Boolean = False
                For Each picklistOption As [Option] In picklistAttributeMetadata.Options
                    For Each aLocLabel As MetadataServiceSdk.LocLabel In picklistOption.Label.LocLabels
                        If aLocLabel.Label = "created" Then
                            testLabelFound = True
                        End If
                    Next aLocLabel
                Next picklistOption

                If (Not testLabelFound) Then
                    success = False
                End If

                '            #End Region

                '            #Region "Remove Data Required for this Sample"

                ' Create the request
                Dim deleteAttribute As New DeleteAttributeRequest()
                deleteAttribute.LogicalName = "new_multi_picklist"
                deleteAttribute.EntityLogicalName = EntityName.contact.ToString()

                ' Execute the request
                Dim deleteResponse As DeleteAttributeResponse = CType(metadataService.Execute(deleteAttribute), DeleteAttributeResponse)

                '            #End Region
            Catch
                ' You can handle an exception here or pass it back to the calling method.
                Throw
            End Try

            Return success
        End Function

        ''' <summary>
        ''' Create an array of Options (the base class for picklist)
        ''' </summary>
        ''' <param name="picklistOptionNodes">All picklist option text and language codes</param>
        ''' <returns>Array of Options</returns>
        Private Shared Function CreateOptions(ByVal picklistOptionNodes As XmlNodeList) As [Option]()
            ' Build a list of all picklist options
            Dim crmPicklistOptions As New ArrayList()

            ' NOTE: In Microsoft CRM 4.0, all new picklist values begin at 200,000 to maintain
            ' backwards compatibility with Microsoft CRM 3.0
            Dim picklistValue As Integer = 200000

            For Each picklistOptionNode As XmlNode In picklistOptionNodes
                Dim crmPicklistOption As New [Option]()
                crmPicklistOption.Value = New MetadataServiceSdk.CrmNumber()
                crmPicklistOption.Value.Value = picklistValue
                crmPicklistOption.Label = CreateMultiLanguageLabel(picklistOptionNode.ChildNodes)
                crmPicklistOptions.Add(crmPicklistOption)

                picklistValue += 1
            Next picklistOptionNode

            Return CType(crmPicklistOptions.ToArray(GetType(MetadataServiceSdk.Option)), MetadataServiceSdk.Option())
        End Function

        ''' <summary>
        ''' Create a multi-language Crm label
        ''' </summary>
        ''' <param name="locDataNodes">Localized data for each label required</param>
        ''' <returns></returns>
        Private Shared Function CreateMultiLanguageLabel(ByVal locDataNodes As XmlNodeList) As MetadataServiceSdk.CrmLabel
            Dim allLocLabels As New ArrayList()

            ' Create a new LocLabel for every language.         
            For Each locDataNode As XmlNode In locDataNodes
                Dim langCode As New MetadataServiceSdk.CrmNumber()
                Dim locLabel As New MetadataServiceSdk.LocLabel()

                ' Get the language code and label text for this LocLabel.
                Dim languageData As XmlAttributeCollection = locDataNode.Attributes
                langCode.Value = Convert.ToInt32(languageData("langCode").Value)

                ' Create the LocLabel.
                locLabel.LanguageCode = langCode
                locLabel.Label = languageData("labelText").Value
                allLocLabels.Add(locLabel)
            Next locDataNode

            ' Create the CrmLabel with all supported language text.
            Dim crmLabel As New MetadataServiceSdk.CrmLabel()
            crmLabel.LocLabels = CType(allLocLabels.ToArray(GetType(MetadataServiceSdk.LocLabel)), MetadataServiceSdk.LocLabel())

            Return crmLabel
        End Function
    End Class
End Namespace

© 2010 Microsoft Corporation. All rights reserved.


Show:
© 2014 Microsoft