How to Make Calls to Metadata in Commerce Server

This sample shows how to make calls to metadata. It includes a metadata explorer that allows you to drill down into the attributes of a given entity.

Note This sample code is provided to illustrate a concept and should not be used in applications or Web sites, as it may not illustrate the safest coding practices. Microsoft assumes no liability for incidental or consequential damages should the sample code be used for purposes other than as intended.

Prerequisites

You can access the sample code by extracting the .zip archive in the samples folder you selected when you installed the Commerce Server 2009 R2 SDK Samples. In order to use these samples it is assumed that you have installed the following:

  • Microsoft Visual Studio 2008 SP1

  • Microsoft Internet Information Services (IIS)

  • Microsoft Commerce Server 2009

  • Microsoft Commerce Server 2009 SDK Samples

Unpackage and Configure the PUP

You must first unpackage and configure the included Commerce Server site via the PUP file SolutionStorefrontWithSampleData.pup.

The samples depend upon the data within this package.

To create the Commerce Server site

  1. In Windows Explorer, navigate to the <dir>\Pup Packages.

  2. Double-click the SolutionStorefrontWithSampleData.pup file.

  3. In the Unpack screen, select Quick Unpack, and then click Next.

  4. In the Quick Unpack screen, ensure that the SQL Server computer name is correct, enter the SQL Server login name and password or select Windows Authentication as the authentication method, and then click Next.

  5. In the Profiling System screen, accept the defaults, and then click Next.

  6. In the second Profiling System screen, accept the defaults, and then click OK.

  7. In the Commerce Server Site Packager dialog box, click OK.

  8. In the Unpacking is complete! screen, click Finish.

The Commerce Server site is unpacked to the Solution Storefront in IIS.

Building the Solution

You will have to build the Metadata.sln before proceeding.

To build the solution within Visual Studio

  1. In Windows Explorer, go to <dir>\Extensibility Kits\Samples\.

  2. Unzip the FoundationSamples.zip to a new directory.

  3. Browse to the Metadata folder.

  4. Double-click the Metadata.sln file. This opens the solution in Visual Studio.

  5. Under Solution Explorer, right-click Solution <solution name>, and from the context menu select Build Solution.

Creating a Web Application

Use the following steps to add the sample application to your Commerce Server site in Internet Information Services (IIS). When you do so, you will choose an IIS application pool to assign to the Catalog Web application. To make sure that the application works correctly, the application pool you select must comply with the following:

  • The application pool must have all the necessary security privileges to access your Commerce Server site and its associated databases.

To add the application to the Commerce Server site in IIS 7.0

  1. In Internet Information Services (IIS) Manager, in the navigation tree, click Sites, right-click Default Web Site, and then click Add Application.

  2. In the Alias box, type a name for your sample.

  3. Click the Select button next to the Application pool box, select the application pool to use, and then click OK.

    Note

    The application pool must have all the necessary security privileges to access your Commerce Server site and its associated databases.

  4. In the PhysicalPath box, type the full path of the application. This is the path to which you browsed to the FoundationSamples\Metadata folder.

    For example, when you extract the FoundationSamples.zip to the same folder, the application path is as follows: %commerce_server_root%Extensibility Kits\Samples\FoundationSamples\Metadata.

  5. Click OK.

  6. In Internet Explorer, go to the following URL to access the Web application:

    https://localhost/<your_sample_vdir>/Default.aspx,

    where <your_sample_vdir> is the value used in step 4.

Example

The following code snippet illustrates how to build a query to retrieve the mapping and property definition metadata for an entity.

    using System;
    using System.Collections.Generic;
    using Microsoft.Commerce;
    using Microsoft.Commerce.Definitions;

    public enum CommerceServerArea
    {
        Catalog = 0,
        Profiles = 1,
        Orders = 2,
        Marketing = 3,
    }

    /// <summary>
    /// Context class for OperationService calls.
    /// </summary>
    public sealed class CommerceContext
    {
        private static CommerceContext _commerceContext = new CommerceContext();

        private OperationServiceAgent _operationServiveAgent = new OperationServiceAgent();

        /// <summary>
        /// Creates a new CommerceContext instance.
        /// </summary>
        public CommerceContext()
        {
            var metadata = this.GetMetadata("modelname", CommerceServerArea.Catalog);
            var entityMappings = metadata.EntityMappings;
            var entityMetadata = metadata.EntityMetadata;
            var propertyDefinitions = metadata.PropertyDefinitions;
        }

        /// <summary>
        /// Gets the current CommerceContext instance.
        /// </summary>
        public static CommerceContext Current
        {
            get
            {
                return CommerceContext._commerceContext;
            }
        }

        /// <summary>
        /// gets the OperationServiceAgent.
        /// </summary>
        public OperationServiceAgent OperationServiceAgent
        {
            get { return _operationServiveAgent; }
        }

        /// <summary>
        /// Gets the current request context.
        /// </summary>
        /// <returns>The current request context.</returns>
        public CommerceRequestContext GetCurrentRequestContext()
        {
            CommerceRequestContext requestContext = new CommerceRequestContext()
            {
                Channel = "SampleChannel",
                UserLocale = "en-US",
                UserUILocale = "en-US",
                RequestId = Guid.NewGuid().ToString() // Needs to be replaced by the request id
            };

            return requestContext;
        }

        /// <summary>
        /// Gets the metadata for an entity.
        /// </summary>
        /// <param name="modelName">The name of the entity.</param>
        /// <param name="area">The area mapping for the entity metadata.</param>
        /// <returns>The metadata for the specified entity.</returns>
        public CommerceEntityDefinition GetMetadata(string modelName, CommerceServerArea? area)
        {
            // Construct the related RelationshipDefinitions query
            CommerceQueryRelatedItem<PropertyDefinition> relationshipTypePropertyQuery = new CommerceQueryRelatedItem<PropertyDefinition>(
               RelationshipTypeDefinition.RelationshipName.PropertyDefinitions);
            relationshipTypePropertyQuery.RelatedOperations.Add(new CommerceQueryRelatedItem<ConstraintBase>(
                PropertyDefinition.RelationshipName.Constraints));
            relationshipTypePropertyQuery.RelatedOperations.Add(new CommerceQueryRelatedItem<EnumerationEntry>(
                EnumeratedPropertyDefinition.RelationshipName.EnumeratedValues));

            CommerceQueryRelatedItem<RelationshipTypeDefinition> relationshipTypeQuery = new CommerceQueryRelatedItem<RelationshipTypeDefinition>(
                RelationshipDefinition.RelationshipName.RelationshipType);
            relationshipTypeQuery.RelatedOperations.Add(relationshipTypePropertyQuery);

            CommerceQueryRelatedItem<RelationshipDefinition> relationshipDefinitionsQuery = new CommerceQueryRelatedItem<RelationshipDefinition>(
                CommerceEntityDefinition.RelationshipName.RelationshipDefinitions);
            relationshipDefinitionsQuery.RelatedOperations.Add(relationshipTypeQuery);

            // Construct the related PropertyDefinitions query
            CommerceQueryRelatedItem<PropertyDefinition> propertyDefinitionsQuery = new CommerceQueryRelatedItem<PropertyDefinition>(
                CommerceEntityDefinition.RelationshipName.PropertyDefinitions);
            propertyDefinitionsQuery.RelatedOperations.Add(new CommerceQueryRelatedItem<ConstraintBase>(
                PropertyDefinition.RelationshipName.Constraints));
            propertyDefinitionsQuery.RelatedOperations.Add(new CommerceQueryRelatedItem<EnumerationEntry>(
                EnumeratedPropertyDefinition.RelationshipName.EnumeratedValues));

            // Construct the related EntityMetadata query
            CommerceQueryRelatedItem<PropertyDefinition> entityMetadataQuery = new CommerceQueryRelatedItem<PropertyDefinition>(
                CommerceEntityDefinition.RelationshipName.EntityMetadata);
            entityMetadataQuery.RelatedOperations.Add(new CommerceQueryRelatedItem<ConstraintBase>(
                PropertyDefinition.RelationshipName.Constraints));
            entityMetadataQuery.RelatedOperations.Add(new CommerceQueryRelatedItem<EnumerationEntry>(
                EnumeratedPropertyDefinition.RelationshipName.EnumeratedValues));

            // Construct the related EntityMappings query
            CommerceQueryRelatedItem<EntityMapping> entityMappingsQuery = new CommerceQueryRelatedItem<EntityMapping>(
                CommerceEntityDefinition.RelationshipName.EntityMappings);
            entityMappingsQuery.RelatedOperations.Add(new CommerceQueryRelatedItem<DefinitionMapping>(
                EntityMapping.RelationshipName.DefinitionMappings));
            if (area.HasValue)
            {
                entityMappingsQuery.SearchCriteria.Model.CommerceServerArea = area;
            }

            // Construct the CommerceEntityDefinition query.
            var metadataQuery = new CommerceQuery<CommerceEntityDefinition, CommerceModelSearch<CommerceEntity>>();

            metadataQuery.SearchCriteria.Model.ModelName = modelName;

            metadataQuery.RelatedOperations.Add(entityMappingsQuery);
            metadataQuery.RelatedOperations.Add(propertyDefinitionsQuery);
            metadataQuery.RelatedOperations.Add(relationshipDefinitionsQuery);
            metadataQuery.RelatedOperations.Add(entityMetadataQuery);

            // Execute the query
            CommerceResponse response = this.OperationServiceAgent.ProcessRequest(
                this.GetCurrentRequestContext(),
                metadataQuery.ToRequest());

            CommerceQueryOperationResponse queryResponse = (CommerceQueryOperationResponse)response.OperationResponses[0];
            if (queryResponse.Count > 0)
            {
                return (CommerceEntityDefinition)queryResponse.CommerceEntities[0];
            }

            return null;
        }

        /// <summary>
        /// Gets the names of all entites registered in metadata.
        /// </summary>
        /// <returns>The names of all entities registered in metadata.</returns>
        public List<string> GetEntityNames()
        {
            var metadataQuery = new CommerceQuery<CommerceEntityDefinition, CommerceModelSearch<CommerceEntity>>();

            CommerceResponse response = this.OperationServiceAgent.ProcessRequest(
                this.GetCurrentRequestContext(),
                metadataQuery.ToRequest());

            List<string> entityNames = new List<string>();

            CommerceQueryOperationResponse queryResponse = (CommerceQueryOperationResponse)response.OperationResponses[0];
            if (queryResponse.Count > 0)
            {
                foreach (CommerceEntityDefinition entity in queryResponse.CommerceEntities)
                {
                    entityNames.Add(entity.Name);
                }
            }

            return entityNames;
        }
    }