Skip to main content

How to get Child Products using Commerce Server 2007 & 2009

using System;
using System.Linq;
using Microsoft.Commerce.Common.MessageBuilders;
using Microsoft.Commerce.Contracts;
using Microsoft.Commerce.Contracts.Messages;
using Microsoft.CommerceServer.Catalog;
using Microsoft.CommerceServer.Runtime;

namespace ASPNet3346
{
    public partial class GetChildProducts : System.Web.UI.Page
    {
        protected void btnCS2007_Click(object sender, EventArgs e)
        {
            ProductCatalog productCatalog = (ProductCatalog)CommerceContext.Current.CatalogSystem.GetCatalog("Adventure Works Catalog", "en-US");
            // Get the root category.
            Category departmentCategory = productCatalog.GetCategory("Boots");
            ProductCollection childProducts = departmentCategory.ChildProducts;
            foreach (Product product in childProducts)
            {
                DisplayHelper.DisplayValue("DisplayName", product.DisplayName, Response);
            }
        }

        protected void btnCS2009_Click(object sender, EventArgs e)
        {

            var catalogQuery = new CommerceQuery("Category");
            catalogQuery.SearchCriteria.Model.Id = "Boots";
            catalogQuery.SearchCriteria.Model.Properties["CatalogId"] = "Adventure Works Catalog";

            //Get Child Categories
            // Add Related Query Operation for child products
            {
                CommerceQueryRelatedItem queryChildProducts =
                    new CommerceQueryRelatedItem("ChildProducts", "Product");
                catalogQuery.RelatedOperations.Add(queryChildProducts);
            }
            CommerceResponse response = CommerceFoundationServiceAgent.Execute(catalogQuery);

            // Handle Responses
            CommerceQueryOperationResponse queryResponse = response.OperationResponses.Single() as CommerceQueryOperationResponse;
            CommerceEntity productCatalog = queryResponse.CommerceEntities.SingleOrDefault();
            var childCategories = productCatalog.GetPropertyValue("ChildProducts") as CommerceRelationshipList;
            if (childCategories != null)
                foreach (var commerceRelationship in childCategories)
                {
                    CommerceEntity childcategory = commerceRelationship.Target;
                    DisplayHelper.DisplayValue("DisplayName", childcategory.Properties["DisplayName"], Response);
                }
        }
    }
}

Attached Source Code : ASPNet3346

How to get Child Categories using Commerce Server 2007 & 2009

using System;
using System.Linq;
using Microsoft.Commerce.Common.MessageBuilders;
using Microsoft.Commerce.Contracts;
using Microsoft.Commerce.Contracts.Messages;
using Microsoft.CommerceServer.Catalog;
using Microsoft.CommerceServer.Runtime;

namespace ASPNet3346
{
    public partial class GetChildCategories : System.Web.UI.Page
    {
        protected void btnCS2007_Click(object sender, EventArgs e)
        {
            ProductCatalog productCatalog = (ProductCatalog)CommerceContext.Current.CatalogSystem.GetCatalog("Adventure Works Catalog", "en-US");
            // Get the root category.
            Category departmentCategory = productCatalog.GetCategory("Departments");
            CatalogItemsDataSet categories = departmentCategory.ChildCategories.DataSet;
            foreach (CatalogItemsDataSet.CatalogItem category in categories.CatalogItems)
            {
                DisplayHelper.DisplayValue("DisplayName", category.DisplayName, Response);
            }

        }

        protected void btnCS2009_Click(object sender, EventArgs e)
        {

            var catalogQuery = new CommerceQuery("Category");
            catalogQuery.SearchCriteria.Model.Id = "Departments";
            catalogQuery.SearchCriteria.Model.Properties["CatalogId"] = "Adventure Works Catalog";

            //Get Child Categories
            // Add Related Query Operation for child products
            {
                CommerceQueryRelatedItem queryChildProducts =
                    new CommerceQueryRelatedItem("ChildCategories", "Category");
                //the relation name can ChildCategories,AncestorCategories,CanonicalCategories,ParentCategories,RelatedCategories , Ref MetadataDefinitions.xml
                catalogQuery.RelatedOperations.Add(queryChildProducts);
            }
            CommerceResponse response = CommerceFoundationServiceAgent.Execute(catalogQuery);

            // Handle Responses
            CommerceQueryOperationResponse queryResponse = response.OperationResponses.Single() as CommerceQueryOperationResponse;
            CommerceEntity productCatalog = queryResponse.CommerceEntities.SingleOrDefault();
            var childCategories = productCatalog.GetPropertyValue("ChildCategories") as CommerceRelationshipList;
            foreach (var commerceRelationship in childCategories)
            {
                CommerceEntity childcategory = commerceRelationship.Target;
                DisplayHelper.DisplayValue("DisplayName", childcategory.Properties["DisplayName"], Response);
            }

        }
    }
}

Attached Source Code : ASPNet3346

How to get product using Commerce Server 2007 & 2009

using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Microsoft.Commerce.Common.MessageBuilders;
using Microsoft.Commerce.Contracts;
using Microsoft.Commerce.Contracts.Messages;
using Microsoft.CommerceServer.Catalog;
using Microsoft.CommerceServer.Runtime;

namespace ASPNet3346
{
    public partial class GetAProduct : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        protected void btnCS2007_Click(object sender, EventArgs e)
        {
            GetCatalog(CommerceContext.Current.CatalogSystem, "Adventure Works Catalog");
        }
        private void GetCatalog(CatalogContext context, string catalogName)
        {
            //Get the catalog with the name specified in catalogName.
            // Return the catalog data in English, as specified by "en-US");
            ProductCatalog productCatalog = (ProductCatalog)context.GetCatalog(catalogName, "en-US");
            Response.Write(productCatalog.Name);
            Response.Write(productCatalog.IdentifyingProductProperty);
        }

        protected void btnCS2009_Click(object sender, EventArgs e)
        {
            var productQuery = new CommerceQuery("Product");

            productQuery.SearchCriteria.Model.Properties["CatalogId"] = "Adventure Works Catalog";
            productQuery.SearchCriteria.Model.Id = "AW200-12";

            productQuery.Model.Properties.Add("Id");
            productQuery.Model.Properties.Add("DisplayName");
            productQuery.Model.Properties.Add("Description");
            productQuery.Model.Properties.Add("ListPrice");

            {
                var queryVariants = new CommerceQueryRelatedItem("Variants", "Variant");

                queryVariants.SearchCriteria.SortProperties = new List();
                queryVariants.SearchCriteria.SortProperties.Add(new CommerceSortProperty("Variant", "ProductColor", SortDirection.Ascending));
                queryVariants.SearchCriteria.FirstItemIndex = 0;
                queryVariants.SearchCriteria.ReturnTotalItemCount = true;

                queryVariants.Model.Properties.Add("Id");
                queryVariants.Model.Properties.Add("VariantCode");
                queryVariants.Model.Properties.Add("ProductColor");

                productQuery.RelatedOperations.Add(queryVariants);
            }

            CommerceResponse response = CommerceFoundationServiceAgent.Execute(productQuery);

            // Handle Responses
            CommerceQueryOperationResponse queryResponse = response.OperationResponses.Single() as CommerceQueryOperationResponse;
            CommerceEntity product = queryResponse.CommerceEntities.SingleOrDefault();
            Response.Write(product.Id);
        }
    }
}

Attached Source Code : ASPNet3346

How to get a Catalog using Commerce Server 2007 & 2009

namespace ASPNet3346
{
    public partial class GetACatalog : System.Web.UI.Page
    {

        protected void btnCS2007_Click(object sender, EventArgs e)
        {

            ProductCatalog productCatalog = (ProductCatalog)CommerceContext.Current.CatalogSystem.GetCatalog("Adventure Works Catalog", "en-US");
            DisplayHelper.DisplayValue("Catalog ID", productCatalog.Name, Response);
            DisplayHelper.DisplayValue("IdentifyingProductProperty", productCatalog.IdentifyingProductProperty, Response);

        }

        protected void btnCS2009_Click(object sender, EventArgs e)
        {
            var catalogQuery = new CommerceQuery("Catalog");

            //TODO Theme Microsoft Multi-Channel Commerce Foundation RequestContext object will BindingContainert he user locale information used to get the catalogs in the appropriate language. If the language in the RequestContext is NotFiniteNumberExceptionc urrently supported, the _Defaultl anguage for thec atalog(s) willb e used.
            //catalogQuery.SearchCriteria.Model.Properties["language"] = "en-US";
            catalogQuery.SearchCriteria.Model.Id = "Adventure Works Catalog";

            CommerceResponse response = CommerceFoundationServiceAgent.Execute(catalogQuery);

            // Handle Responses
            CommerceQueryOperationResponse queryResponse = response.OperationResponses.Single() as CommerceQueryOperationResponse;
            CommerceEntity productCatalog = queryResponse.CommerceEntities.SingleOrDefault();

            DisplayHelper.DisplayValue("Catalog ID", productCatalog.Id, Response);
            DisplayHelper.DisplayValue("IdentifyingProductProperty", productCatalog.Properties["IdentifyingProductProperty"], Response);

        }

    }
}

Attached Source Code : ASPNet3346

The search criteria Model must contain exactly one property that maps to a Commerce Server profile property defined as a primary, join, or unique key.

Last week I extended Profile System and added One more unique key for the User Object.
I had done this many times in past and was an easy and simple job but not this time ( because of my silly mistake ).

I had created database field, added Data Member, property in profile definition & finally updated Metadatadefinition file to map to the new field.

image

image

When I queried user object with MCCF by the Key SSN, I got following error.

An exception of type ‘Microsoft.Commerce.Providers.Exceptions.InvalidOperationRequestException’ occurred and was caught.
————————————————————————————————————————
12/21/2010 03:28:37
Type : Microsoft.Commerce.Providers.Exceptions.InvalidOperationRequestException, Microsoft.Commerce.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
Message : The operation could not be performed because the search criteria Model is not valid. The search criteria Model must contain exactly one property that maps to a Commerce Server profile property defined as a primary, join, or unique key.
Source : Microsoft.Commerce.Providers
Help link :
Data : System.Collections.ListDictionaryInternal
TargetSite : Void ValidateSearchCriteria(Microsoft.Commerce.Contracts.Messages.CommerceModelSearch)
Stack Trace : at Microsoft.Commerce.Providers.Components.ProfileOperationSequenceComponent.ValidateSearchCriteria(CommerceModelSearch searchCriteria)
at Microsoft.Commerce.Providers.Components.ProfileOperationSequenceComponent.GetMatches(CommerceModelSearch searchCriteria, Nullable`1& totalItemCount, Boolean throwIfNotFound)
at Microsoft.Commerce.Providers.Components.ProfileOperationSequenceComponent.GetMatches(CommerceModelSearch searchCriteria, Nullable`1& totalItemCount)
at Microsoft.Commerce.Providers.Components.ProfileLoaderBase.ExecuteQuery(CommerceQueryOperation queryOperation, OperationCacheDictionary operationCache, CommerceQueryOperationResponse response)
at Microsoft.Commerce.Providers.Components.OperationSequenceComponent.Execute(CommerceOperation operation, OperationCacheDictionary operationCache, CommerceOperationResponse response)
at Microsoft.Commerce.Providers.Components.ProfileOperationSequenceComponent.Execute(CommerceOperation operation, OperationCacheDictionary operationCache, CommerceOperationResponse response)
at Microsoft.Commerce.Broker.OperationSequence.ExecuteComponentTree(List`1 executionTreeList, CommerceOperation operation, OperationCacheDictionary operationCache, CommerceOperationResponse response)
at Microsoft.Commerce.Broker.OperationSequence.Execute(CommerceOperation operation)
at Microsoft.Commerce.Broker.MessageHandler.ProcessMessage(String messageHandlerName, CommerceOperation operation)
at Microsoft.Commerce.Broker.OperationService.InternalProcessRequest(CommerceRequest request)
at Microsoft.Commerce.Broker.OperationService.ProcessRequest(CommerceRequest request)
Additional Info:

MachineName : VPC-MYMachine-BASE
TimeStamp : 12/21/2010 9:28:37 AM
FullName : Microsoft.Commerce.Common, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
AppDomainName : /LM/W3SVC/483061927/ROOT-1-129373971773508707
ThreadIdentity :
WindowsIdentity : VPC-MYMachine-BASE\Administrator

I recheck that all the bindings are correct and the property is defined as Unique Key. Every thing seems to be OK but still I was facing error. 🙁

On a closer look I found that I had made a mistake with the group name in the MetadataDefinition file.
The name of the CS Property is case sensitive and my MetadataDefinition file was not in Sync with the Case in Commerce Server Manager.

image

image

Change To

image

I faced the same error On my initial trial of extending profile system when CS 2009 CTP was release ( around 2 year back ) and I had made the same mistake of case. Thus I decided to document the issue and the solution.

Possible solutions for ‘Failed to set value for profile property ’email_address’.’ and Object or data matching the name, range, or selection criteria was not found within the scope of this operation.

Last week I ran in to two issues, “Failed to set value for profile property ’email_address’ and “Object or data matching the name, range, or selection criteria was not found within the scope of this operation”

Following are the two exceptions.

An exception has occured.

ExceptionType: 'CommerceProfileSystemException'
ExceptionMessage: 'Failed to set value for profile property 'email_address'.'
StackTrace: ' at Microsoft.CommerceServer.Runtime.Profiles.ProfileProperty.set_Value(Object value)
at Microsoft.CommerceServer.Runtime.Profiles.UpmMembershipProvider.CreateUser(String username, String password, String email, String passwordQuestion, String passwordAnswer, Boolean isApproved, Object providerUserKey, MembershipCreateStatus& status)
at Microsoft.Commerce.UI.WebParts.CommercePropertyBaseWebPart.CreateUser()
at Microsoft.Commerce.UI.WebParts.CommercePropertyBaseWebPart.OnBubbleEvent(Object source, EventArgs args)'
Source: 'Microsoft.CommerceServer.Runtime'
TargetSite: 'Void set_Value(System.Object)'
Inner exception:
ExceptionType: 'COMException'
ExceptionMessage: 'Exception from HRESULT: 0xC1004043'
StackTrace: ' at ADODB.Field.set_Value(Object pvar)
at Microsoft.CommerceServer.Runtime.Profiles.ProfileProperty.set_Value(Object value)'
Source: 'ADODB'
TargetSite: 'Void set_Value(System.Object)'

And

Object or data matching the name, range, or selection criteria was not found within the scope of this operation.
Stack Trace:
[COMException (0x80040e19): Object or data matching the name, range, or selection criteria was not found within the scope of this operation.]
Microsoft.CommerceServer.Interop.Profiles.IProfileObject2.GetInfo() +0
Microsoft.CommerceServer.Runtime.Profiles.Profile.Refresh() +166
[CommerceProfileSystemException: Failed to refresh profile state from underlying stores.]
Microsoft.CommerceServer.Runtime.Profiles.Profile.Refresh() +454
Microsoft.CommerceServer.Runtime.Profiles.UpmMembershipUser.ValidateUser(String password) +55
System.Web.UI.WebControls.Login.AuthenticateUsingMembershipProvider(AuthenticateEventArgs e) +75
   System.Web.UI.WebControls.Login.AttemptLogin() +152
System.Web.UI.WebControls.Login.OnBubbleEvent(Object source, EventArgs e) +124
System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +70
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +29
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2981

Following are the checkpoint which helped me to resolve the issue.

The connection string was having invalid provider.

clip_image002

Also check following possibility.

Check Ravi’s Blog for details

  • The reason is the guid passed already exists in the user object.

Check de-Hao’s Blog

  • check for all the custom attribute for the user object tables ( SQL and Commerce server Properties)
  • check and associate the properties to data source under commerce server manager
  • check you donn’t have case mistake in MetadataDefinitions.xml.