Saturday, September 19, 2020

Fix for the Domain is null and Invalid or missing value for property.


 Recently, I have updated my local instance and while doing the new registration or login got the below error

The Domain is null and is probably not defined in Domain Manager

When I checked my domain configuration under site settings

/sitecore/content/Tenant/Sitecore/Settings/Site Grouping/Site

I found the reference of the domain didn't exist on my local system, I created a new domain through the admin panel here

After fixing that, during the registration, I got a diff error

 {  
  "IsSignupFlow": false,  
  "UserName": null,  
  "Errors": [  
   "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator."  
  ],  
  "HasErrors": true,  
  "HasInfo": false,  
  "HasWarnings": false,  
  "Info": [  
  ],  
  "Success": false,  
  "Url": null,  
  "Warnings": [  
  ],  
  "ContentEncoding": null,  
  "ContentType": null,  
  "Data": null,  
  "JsonRequestBehavior": 1,  
  "MaxJsonLength": null,  
  "RecursionLimit": null  
 }  
I opened my session in a new incognito window and found below errors -

 {  
  "IsSignupFlow": false,  
  "UserName": null,  
  "Errors": [  
   "Invalid or missing value for property \u0027Domain\u0027."  
  ],  
  "HasErrors": true,  
  "HasInfo": false,  
  "HasWarnings": false,  
  "Info": [  
  ],  
  "Success": false,  
  "Url": null,  
  "Warnings": [  
  ],  
  "ContentEncoding": null,  
  "ContentType": null,  
  "Data": null,  
  "JsonRequestBehavior": 1,  
  "MaxJsonLength": null,  
  "RecursionLimit": null  
 }  
I updated the existing domain in site groping,  to see if it's working because, because I haven't added this domain in the commerce configuration .
 {  
  "IsSignupFlow": false,  
  "UserName": null,  
  "Errors": [  
   "Customer \u0027Storefront\\jitusonijk@gmail.com\u0027 already exists."  
  ],  
  "HasErrors": true,  
  "HasInfo": false,  
  "HasWarnings": false,  
  "Info": [  
  ],  
  "Success": false,  
  "Url": null,  
  "Warnings": [  
  ],  
  "ContentEncoding": null,  
  "ContentType": null,  
  "Data": null,  
  "JsonRequestBehavior": 1,  
  "MaxJsonLength": null,  
  "RecursionLimit": null  
 }  
So abve message is because I had the same user already registered, I did a new registration and it worked for me.

The issue/learning was - If you create a new domain configuration please make sure that we need to update the site groping and policies accordingly.

PlugIn.AdventureWorks.CommerceAuthoring-1.0.0.json
PlugIn.Habitat.CommerceAuthoring-1.0.0.json
PlugIn.YourSite.CommerceAuthoring-1.0.0.json

 


Wednesday, September 16, 2020

Sitecore Experience Commerce - Steps to update custom values through - GetEntityView and DoUxAction APIs.

There are a few options to extend the Sitecore commerce entities,  OOTB Sitecore XC provided below entities.

  1.  Sitecore.Commerce.Plugin.Catalog.SellableItem
  2.  Sitecore.Commerce.Plugin.Catalog.Catalog
  3.  Sitecore.Commerce.Plugin.Catalog.Category
  4.  Sitecore.Commerce.Plugin.Promotions.PromotionBook
  5.  Sitecore.Commerce.Plugin.Promotions.Promotion
  6.  Sitecore.Commerce.Plugin.Pricing.PriceBook
  7.  Sitecore.Commerce.Plugin.Pricing.PriceCard
  8.  Sitecore.Commerce.Plugin.Customers.Customer
  9.  Sitecore.Commerce.Plugin.Orders.Order

If you are working in the commerce world, you will see a requirement to extend these entities, the requirement can be an example below.

1,  Add invoice link to the order - Add a new field on order entities to show the invoice link or status from the backend system.

2. Add a new field on customer entities to show the preferred time for the call, Membership type like gold, silver etc.

3. Extend the sellable item (The most common one) to add more fields like custom properties for Color, notes etc.

For updating the order usually, we should use the minion jobs to read the current status and update from the backend system but sometimes you need to update those details from the outer side. Here are a few easy tips.

To update any field values of entities like Order, Customer you can use the GetEntityVIew to get the Entry and 

URL will be like this  

https://commerceauthoring.XX.dev.com/api/GetEntityView()- h

Request input-

{  
  "entityId": "Entity-Customer-f26e9063ba38461bafcf97fe4a115830",  
  "viewName": "EditView",  
  "forAction": "EditView",  
  "itemId": "Composer-82bd424ddb274945912dca6fb71cea4b"  
 }  
We need to pass the Customer or Entity and name of the Composer template-

The response will be an complete entity, We can keep the response in an object and update the value and after that can call the

 https://commerceauthoring.XXX.com.dev.com/api/DoUxAction()

and post the updated view, that will update the value in the entiry.

 {  
  "@odata.context": "https://commerceauthoring.XXX.com.dev.com/Api/$metadata#Sitecore.Commerce.EntityViews.EntityView",  
  "@odata.type": "#Sitecore.Commerce.EntityViews.EntityView",  
  "Name": "EditView",  
  "Policies": [  
  ],  
  "DisplayName": "Edit View",  
  "EntityId": "Entity-SellableItem-demohandtowel1",  
  "EntityVersion": 4,  
  "Action": "EditView",  
  "ItemId": "Composer-82bd424ddb274945912dca6fb71cea4b",  
  "VersionedItemId": "Composer-82bd424ddb274945912dca6fb71cea4b-4",  
  "SelectedChildView": {  
   "Name": "",  
   "Policies": [  
   ]  
  },  
  "DisplayRank": 500,  
  "UiHint": "Flat",  
  "Icon": "chart_column_stacked",  
  "Properties": [  
   {  
    "Name": "Version",  
    "Policies": [  
    ],  
    "DisplayName": "Version",  
    "Value": "1",  
    "IsHidden": true,  
    "OriginalType": "System.Int32",  
    "IsReadOnly": true,  
    "UiType": "",  
    "IsRequired": true  
   },  
   {  
    "Name": "LaunchDate",  
    "Policies": [  
    ],  
    "DisplayName": "Launch Date",  
    "Value": "2020-09-16T14:26:00.5386742+00:00",  
    "IsHidden": false,  
    "OriginalType": "System.DateTimeOffset",  
    "IsReadOnly": false,  
    "UiType": "",  
    "IsRequired": true  
   },  
   {  
    "Name": "DealerName",  
    "Policies": [  
    ],  
    "DisplayName": "Dealer Name",  
    "Value": "",  
    "IsHidden": false,  
    "OriginalType": "System.String",  
    "IsReadOnly": false,  
    "UiType": "",  
    "IsRequired": true  
   }  
  ],  
  "ChildViews": [  
  ]  
 }  
the get GetEntityView will always create a new version in case of edit, so there would be any issue for the concurrency, the same request response can be used to update the entity with the latest values.

Note:- Although this is not a recommended option. 
Ideally, all these changes should go inside the commerce engine.

This information is just an example if there is any need to update data from the external API or need for front end extension.




Sitecore Experience Commerce (Entity Composer) - Key consideration.

Entity Composer is a way to extend the Sitecore entities from the UI Like we can create additional fields and attached those fields to the entities.

If you want to extend any of the Sitecore entities, you would need to add those properties.

For sellable items, there are two options either you can generate those field through the code-first approach, here is a link or you have to define those field in composer template.

I most of the time prefer to use Entity Composer to extend the Sitecore XC entities and it basically depends on the requirement if you don't know the field structure before processing the import, It's recommended to create the filed schema dynamically.

These are the high-level entities.

  1.  Sitecore.Commerce.Plugin.Catalog.SellableItem
  2.  Sitecore.Commerce.Plugin.Catalog.Catalog
  3.  Sitecore.Commerce.Plugin.Catalog.Category
  4.  Sitecore.Commerce.Plugin.Promotions.PromotionBook
  5.  Sitecore.Commerce.Plugin.Promotions.Promotion
  6.  Sitecore.Commerce.Plugin.Pricing.PriceBook
  7.  Sitecore.Commerce.Plugin.Pricing.PriceCard
  8.  Sitecore.Commerce.Plugin.Customers.Customer
  9.  Sitecore.Commerce.Plugin.Orders.Order

Here are the simple steps and best practices.

Go to the Composer template -



1. Naming convention -  I usually prefer the naming Pascal cashing and giving the entity name considering the OOTB naming structure which is 

Sitecore.Commerce.EntityViews.EntityView - OOTB

CompanyName.Custom.Type

CompanyName.Custom,Color

CompanyName.Custom,AditionalProductDetails

Give it the same Display name and just add the proper spacing.

Make sure you choose your name carefully as there is no any option to update the entity name. which is true it's like a primary identifier.

Second point is the view name should be more relevant, As the contact editor will use that field to get the understanding.


Field property - Remove space from the Name and add meaningful display name



Add meaning full tag name  


Assoicate this entity composer with existing entiries.


Now, Here we have associated this custom entity with existing entities, that's it now we can add those values to existing entities.

Order View


Customer VIew -

Price Book


 

Tuesday, September 8, 2020

Sitecore Experience Commerce (Generate a custom order number with policies)

Recently, I got a requirement to generate a custom order number, As the default number is a GUID. I did a similar task in Sitecore Commerce 8.2.1.  here is a link . I used a custom store procedure to generate the order number but would be very straight forward, As the requirement was to generate only random numbers for a fixed digit.

Steps to do that -

1. Create a new plugin -

2.  Give it a name let's say 

Sitecore.Plugin.CustomOrderGenerator

The plugin will look like this -  Now build the plugin


Define the policy here, I need the policy to put a Prefix and make a decision whether to generate a random number or sequential numbers



Add a reference to Sitecore.Commerce.Plugin.Catalog - Because my XC version is 9.3, I have chosen version 5.0.43

Second reference for Commerce.Plugin.Order


Replace OrderPlacedAssignConfirmationIdBlock pipeline block with your custom block



  [PipelineDisplayName("Sitecore.Commerce.Plugin.Sample.CustomOrderGeneratorBlock")]  
   public class CustomOrderGeneratorBlock : PipelineBlock<Order, Order, CommercePipelineExecutionContext>  
   {  
     private readonly FindEntitiesInListCommand _getEntitiesInListCommand;  
     public CustomOrderGeneratorBlock(FindEntitiesInListCommand findEntitiesInListCommand) : base((string)null)  
     {  
       _getEntitiesInListCommand = findEntitiesInListCommand;  
     }  
     public override Task<Order> Run(Order order, CommercePipelineExecutionContext context)  
     {  
       order.OrderConfirmationId = GenerateCustomOrderNumber(order, context, _getEntitiesInListCommand);  
       return Task.FromResult<Order>(order);  
     }  
     private string GenerateCustomOrderNumber(Order order, CommercePipelineExecutionContext context, FindEntitiesInListCommand findEntitiesInListCommand)  
     {  
       var contactComponent = order.GetComponent<ContactComponent>();  
       var orders = (IEnumerable<Order>)findEntitiesInListCommand.Process<Order>(context.CommerceContext, CommerceEntity.ListName<Order>(), 0, int.MaxValue).Result.Items;  
       var orderCount = orders.Count();  
       if (orders.Any())  
       {  
         OrderGeneratorPolicy policy = context.GetPolicy<OrderGeneratorPolicy>();  
         string nextOrderNumber;  
         if (policy.IsRandomNumber)  
         {  
           nextOrderNumber = GenerateNumber(policy.TotalDigitMin, policy.TotalDigitMax);  
         }  
         else  
         {  
           nextOrderNumber = Convert.ToString(orderCount + 1);  
         }  
         return policy.Prefix + nextOrderNumber.ToString();  
       }  
       return Guid.NewGuid().ToString("B");  
     }  
     private string GenerateNumber(int min, int max)  
     {  
       Random r = new Random();  
       int randNum = r.Next(min, max);  
       return randNum.ToString();  
     }  
   }  
When we run the order flow, We can see the result on the order confirmation page.

A few additional notes - Make sure you have registered your policies correctly.

1.  The name should be correct  Plugin.CustomOrderGenerator.PolicySet-1.0.0.json - I think the when we do the bootstrap the application Global.json file consider the ref version ( not sure) but it's better to keep the same naming convention as an example - PlugIn.Payments.Braintree.PolicySet-1.0.0.json

2. Make sure your the definition withing the file is correct and using the correct namespace, As an example below

 {  
  "$type": "Sitecore.Commerce.Core.PolicySet, Sitecore.Commerce.Core",  
  "Id": "Entity-PolicySet-CustomOrderGenerator",  
  "Version": 1,  
  "IsPersisted": false,  
  "Name": "CustomOrderGenerator",  
  "Policies": {  
   "$type": "System.Collections.Generic.List`1[[Sitecore.Commerce.Core.Policy, Sitecore.Commerce.Core]], mscorlib",  
   "$values": [  
    {  
     "$type": "Plugin.CustomOrderGenerator.OrderGeneratorPolicy,Plugin.CustomOrderGenerator",  
     "Environment": "sandbox",  
     "Prefix": "XX",  
     "IsRandomNumber": true,  
     "TotalDigitMin": 9999999,  
     "TotalDigitMax": 1000000  
    }  
   ]  
  }  
 }  


3. Add entity entry in all roles

{ "$type": "Sitecore.Commerce.Core.PolicySetPolicy, Sitecore.Commerce.Core", "PolicySetId": "Entity-PolicySet-BraintreePolicySet" },


That's so much easy, Let me know if have any questions ;) 

Friday, September 4, 2020

Sitecore Experience Commerce ( Fix for AddCartLine: Value cannot be null )

 


Recently, I got below error while adding an item into the cart -

Sitecore XP and XC Version 9.3 

 {"Lines":null,"Email":null,"Subtotal":null,"TaxTotal":null,"Total":null,
"ShippingTotal":null,"TotalAmount":0,"Shipments":null,"Payments":null,"Parties"
:null,"AccountingParty":null,"Discount":null,"PromoCodes":null,  


Investigation steps -
  1. Initially, I thought this could be related to data, so I refreshed the cache, updated the XC template and did the reindex.
  2. I verified data exits in the Solr index.
  3. Found one issue in xConnect related to model - When I browse the xConnect found model is a not correct issue, and that got fix when I updated the right model.
  4. I did the bootstrap and item sync path 
  5. I did add to cart through the postman, and it worked perfectly fine. you need to pass below details
 {  
   "cartId":"Cart01",  
   "itemId": "XXX |AW098 04|5",  
   "quantity": 1  
 }  
The issue still exists after performing all above 5 points. Finally, I have redeployed complete XP and XC website and did all steps again like commerce refresh cache, bootstrap and indexing. That also didn't resolve the issue.


 Fix - FInally, I had to restore all three databases - Master, XCGlobal and XCShared and that help us to see the add to cart functionality again.

but still, what was the issue? - After further investigation, I came to know that during the catalog import process we got below errors -

 Entity-SellableItem-7042259#Entity-SellableItem-demohandtowel1#Entity-SellableItem-demoitem1#Entity-SellableItem-DN136182#Entity-SellableItem-DN136185#Entity-SellableItem-DN136186#Entity-SellableItem-DN136188#Entity-SellableItem-DN136200#Entity-SellableItem-DN136201#Entity-SellableItem-DN136204#Entity-SellableItem-DN136207#Entity-SellableItem-DN136210#Entity-SellableItem-DN139713#Entity-SellableItem-DN139715#Entity-SellableItem-DN139716#Entity-SellableItem-DN142257#Entity-SellableItem-DN151084#Entity-SellableItem-DN142603#Entity-SellableItem-DN142604#Entity-SellableItem-DN142608#Entity-SellableItem-DN142609#Entity-SellableItem-DN151084#Entity-SellableItem-DN151248#Entity-SellableItem-DN151249#Entity-SellableItem-DN151250#Entity-SellableItem-DN151254#Entity-SellableItem-DN162370#Entity-SellableItem-DN162371#Entity-SellableItem-DN162373#Entity-SellableItem-DN162374#Entity-SellableItem-DN162375#Entity-SellableItem-DNEN96#Entity-SellableItem-eb101#Entity-SellableItem-eb102test#Entity-SellableItem-N151248#Entity-SellableItem-TestProduct123'|Environment='Entity-CommerceEnvironment-XXXXX'|Message=  
 'Violation of PRIMARY KEY constraint 'PK_VersioningEntity'.  
  Cannot insert duplicate key in object 'sitecore_commerce_storage.VersioningEntity'.  
  The duplicate key value is (0604f03b-b6a7-a7c4-72d4-23f95337b340).\r\nDuplicate key was ignored.\r\nDuplicate key was ignored.\r\nDuplicate key was ignored.\r\nThe statement has been terminated.'|Number='2627'|Procedure='sitecore_commerce_storage.InsertEntities'|Line='645']",  
       "CommerceTermKey": "SQL:blocks:AddEntities"  

and that's the issue, we ran the import process, and there was an existing reference, 

Finally, I cleaned the environment and reimported it again, and that had resolved the issue entirely.

Thursday, September 3, 2020

Sitecore Experience Commerce (Steps to configure a new currency)

 


Here are simple steps to configure new currency in Sitecore commerce (XC) -

Setup currency in XP -

Go to this path - /sitecore/Commerce/Commerce Control Panel/Shared Settings/Currency Settings/Currency Sets



Create a new currency item and choose the correct configuration, so here we have done the master configuration, Now we need to configure this currency at the store level -

Go to /sitecore/Commerce/Commerce Control Panel/Storefront Settings/Storefronts/YourStoreName/Currencies Display Adjustments/AddNewCurrencyhere



We are done with XP settings now - Let's configured the Sitecore commerce now.

Go to this path -

C:\inetpub\wwwroot\yousite.dev.local\App_Config\Include\Y.Commerce.Engine

Create patch file for below settings

 <defaultShopCurrency>USD</defaultShopCurrency>

Update the BizFx solution and update below configuration-

  "Language": "en",  
  "Currency": "USD",  
Good so here are the final steps - Need to configure the commerce engine environment policies

    {  
     "$type": "Sitecore.Commerce.Core.GlobalCurrencyPolicy, Sitecore.Commerce.Core",  
     "DefaultCurrencySet": "0F65742E-317F-44B0-A4DE-EBF06209E8EA"  
Update the Id for new items created in step first -
 CommerceAuthoring-1.0.0.json  
 CommerceMinions-1.0.0.json  
 CommerceShops-1.0.0.json   
 CommerceAuthoring-1.0.0.json  
 Don't forget to bootstrap as we have changed the configuration here. It's that much easy!

Let me know if you have any questions.

Sitecore Experience Commerce (Postorder components)

Sitecore Experience Commerce (Postorder components)

Recently, I was working on sending the order details to the backend system (SAP), and here is my experience.

Fist, You need to define your pipeline and block, Or if you have any existing feature like Order you can create a new partnership for that - I choose the minion services to pick the Order and send it to the SAP system.

The important part is how to get all the required details and send it to the backend system.

Here are some essential components which we would need to get the information



You may need to add a reference for these components -



       var contactDetails = arg.GetComponent<ContactComponent>();  
       var paymentDetails = arg.GetComponent<FederatedPaymentComponent>();  
       var fulfilmentDetails = arg.GetComponent<FulfillmentComponent>();  
       var listDetails = arg.GetComponent<ListMembershipsComponent>();  
       var listTransientDetails = arg.GetComponent<TransientListMembershipsComponent>();  

For all order line items - We can simply run a for-each loop to get the information.

  foreach (var orderLine in order.Lines)  
           {  
           }  
Fill all the properties in the object, generate the serialized JSON and send it to your backend system.

It's that much simple.

Let me know if need any detail or help on that.

Tuesday, September 1, 2020

Sitecore XC 9.3 - Investigation and fix for Microsoft.OData.Client.DataServiceQueryException



Recently, We have found an issue while deploying the XC changes on a new machine, below are the error details Sitecore XC 9.3
 16164 19:56:24 ERROR Exception <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">     <html xmlns="http://www.w3.org/1999/xhtml">     <head>     <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />     <title> IIS 502.5 Error </title><style type="text/css"></style></head>     <body> <div id = "content">      <div class = "content-container"><h3> HTTP Error 502.5 - Process Failure </h3></div>      <div class = "content-container">      <fieldset> <h4> Common causes of this issue: </h4>       <ul><li> The application process failed to start </li>       <li> The application process started but then stopped </li>       <li> The application process started but failed to listen on the configured port </li></ul></fieldset>      </div>      <div class = "content-container">       <fieldset><h4> Troubleshooting steps: </h4>       <ul><li> Check the system event log for error messages </li>       <li> Enable logging the application process' stdout messages </li>       <li> Attach a debugger to the application process and inspect </li></ul></fieldset>       <fieldset><h4> For more information visit:       <a href="https://go.microsoft.com/fwlink/?linkid=808681"> <cite> https://go.microsoft.com/fwlink/?LinkID=808681 </cite></a></h4>       </fieldset>      </div>    </div></body></html> on Execute:https://commerceauthoring.xxx.com.dev.com/api/GetBulkStockInformation  
 16164 19:56:24 ERROR Application error.  
 Exception: System.Web.HttpUnhandledException  
 Message: An unhandled exception occurred.  
 Source: Sitecore.Mvc  
   at Sitecore.Mvc.Pipelines.MvcEvents.Exception.ShowAspNetErrorMessage.ShowErrorMessage(ExceptionContext exceptionContext, ExceptionArgs args)  
   at Sitecore.Mvc.Pipelines.MvcEvents.Exception.ShowAspNetErrorMessage.Process(ExceptionArgs args)  
   at (Object , Object )  
   at Sitecore.Pipelines.CorePipeline.Run(PipelineArgs args)  
   at Sitecore.Pipelines.DefaultCorePipelineManager.Run(String pipelineName, PipelineArgs args, String pipelineDomain, Boolean failIfNotExists)  
   at Sitecore.Pipelines.DefaultCorePipelineManager.Run(String pipelineName, PipelineArgs args, String pipelineDomain)  
   at Sitecore.Mvc.Pipelines.PipelineService.RunPipeline[TArgs](String pipelineName, TArgs args)  
   at Sitecore.Mvc.Filters.PipelineBasedRequestFilter.OnException(ExceptionContext exceptionContext)  
   at System.Web.Mvc.ControllerActionInvoker.InvokeExceptionFilters(ControllerContext controllerContext, IList`1 filters, Exception exception)  
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass3_1.<BeginInvokeAction>b__5(IAsyncResult asyncResult)  
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult)  
   at System.Web.Mvc.Controller.<>c.<BeginExecuteCore>b__152_1(IAsyncResult asyncResult, ExecuteCoreState innerState)  
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)  
   at System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult)  
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)  
   at System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult)  
   at System.Web.Mvc.MvcHandler.<>c.<BeginProcessRequest>b__20_1(IAsyncResult asyncResult, ProcessRequestState innerState)  
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)  
   at System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)  
   at Sitecore.Mvc.Routing.RouteHttpHandler.EndProcessRequest(IAsyncResult result)  
   at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()  
   at System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step)  
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)  
 Nested Exception  
 Exception: Microsoft.OData.Client.DataServiceQueryException  
 Message: An error occurred while processing this request.  
 Source: Microsoft.OData.Client  
   at Microsoft.OData.Client.DataServiceRequest.Execute[TElement](DataServiceContext context, QueryComponents queryComponents)  
   at Microsoft.OData.Client.DataServiceContext.InnerSynchExecute[TElement](Uri requestUri, String httpMethod, Nullable`1 singleResult, OperationParameter[] operationParameters)  
   at Microsoft.OData.Client.DataServiceActionQuery`1.Execute()  
   at Sitecore.Commerce.ServiceProxy.Proxy.Execute[T](DataServiceActionQuery`1 query)  
   at Sitecore.Commerce.Engine.Connect.Pipelines.Inventory.GetStockInformation.Process(ServicePipelineArgs args)  
   at (Object , Object )  
   at Sitecore.Pipelines.CorePipeline.Run(PipelineArgs args)  
   at Sitecore.Pipelines.DefaultCorePipelineManager.Run(String pipelineName, PipelineArgs args, String pipelineDomain, Boolean failIfNotExists)  
   at Sitecore.Pipelines.DefaultCorePipelineManager.Run(String pipelineName, PipelineArgs args, String pipelineDomain)  
   at Sitecore.Commerce.Pipelines.PipelineService.RunPipeline[TArgs](String pipelineName, TArgs args)  
   at Sitecore.Commerce.Services.ServiceProvider.RunPipeline[TRequest,TResult](String pipelineName, TRequest request)  
   at Sitecore.Commerce.XA.Foundation.Connect.Managers.InventoryManager.GetStockInformation(CommerceStorefront storefront, IEnumerable`1 products, StockDetailsLevel detailsLevel, Boolean includeBundledItemsInventory, StringPropertyCollection propertyBag)  
   at Sitecore.Commerce.XA.Foundation.Connect.Managers.InventoryManager.GetProductsStockStatusFromConnect(CommerceStorefront storefront, ICollection`1 productEntityList, StringPropertyCollection propertyBag)  
   at Sitecore.Commerce.XA.Feature.Catalog.Repositories.PromotedProductsRepository.AdjustProductStockStatus(ICollection`1 productEntityList)  
   at Sitecore.Commerce.XA.Feature.Catalog.Repositories.PromotedProductsRepository.GetPromotedProductsJsonResult(IVisitorContext visitorContext, String productListId, String relationshipFieldId, String currentItemId, String currentCatalogItemId, Nullable`1 pageSize, Nullable`1 pageNumber, StringPropertyCollection propertyBag)  
   at lambda_method(Closure , ControllerBase , Object[] )  
   at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)  
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c.<BeginInvokeSynchronousActionMethod>b__9_0(IAsyncResult asyncResult, ActionInvocation innerInvokeState)  
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult)  
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)  
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__11_0()  
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass11_1.<InvokeActionMethodFilterAsynchronouslyRecursive>b__2()  
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass11_1.<InvokeActionMethodFilterAsynchronouslyRecursive>b__2()  
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult)  
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass3_6.<BeginInvokeAction>b__3()  
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass3_1.<BeginInvokeAction>b__5(IAsyncResult asyncResult)  
 16164 19:56:24 ERROR Exception <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">     <html xmlns="http://www.w3.org/1999/xhtml">     <head>     <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />     <title> IIS 502.5 Error </title><style type="text/css"></style></head>     <body> <div id = "content">      <div class = "content-container"><h3> HTTP Error 502.5 - Process Failure </h3></div>      <div class = "content-container">      <fieldset> <h4> Common causes of this issue: </h4>       <ul><li> The application process failed to start </li>       <li> The application process started but then stopped </li>       <li> The application process started but failed to listen on the configured port </li></ul></fieldset>      </div>      <div class = "content-container">       <fieldset><h4> Troubleshooting steps: </h4>       <ul><li> Check the system event log for error messages </li>       <li> Enable logging the application process' stdout messages </li>       <li> Attach a debugger to the application process and inspect </li></ul></fieldset>       <fieldset><h4> For more information visit:       <a href="https://go.microsoft.com/fwlink/?linkid=808681"> <cite> https://go.microsoft.com/fwlink/?LinkID=808681 </cite></a></h4>       </fieldset>      </div>    </div></body></html> on Execute:https://commerceauthoring.xxxxx.com.dev.com/api/GetBulkStockInformation  
 16164 19:56:24 ERROR Application error.  
 Exception: System.Web.HttpUnhandledException  
 Message: An unhandled exception occurred.  
 Source: Sitecore.Mvc  
   at Sitecore.Mvc.Pipelines.MvcEvents.Exception.ShowAspNetErrorMessage.ShowErrorMessage(ExceptionContext exceptionContext, ExceptionArgs args)  
   at Sitecore.Mvc.Pipelines.MvcEvents.Exception.ShowAspNetErrorMessage.Process(ExceptionArgs args)  
   at (Object , Object )  
   at Sitecore.Pipelines.CorePipeline.Run(PipelineArgs args)  
   at Sitecore.Pipelines.DefaultCorePipelineManager.Run(String pipelineName, PipelineArgs args, String pipelineDomain, Boolean failIfNotExists)  
   at Sitecore.Pipelines.DefaultCorePipelineManager.Run(String pipelineName, PipelineArgs args, String pipelineDomain)  
   at Sitecore.Mvc.Pipelines.PipelineService.RunPipeline[TArgs](String pipelineName, TArgs args)  
   at Sitecore.Mvc.Filters.PipelineBasedRequestFilter.OnException(ExceptionContext exceptionContext)  
   at System.Web.Mvc.ControllerActionInvoker.InvokeExceptionFilters(ControllerContext controllerContext, IList`1 filters, Exception exception)  
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass3_1.<BeginInvokeAction>b__5(IAsyncResult asyncResult)  
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult)  
   at System.Web.Mvc.Controller.<>c.<BeginExecuteCore>b__152_1(IAsyncResult asyncResult, ExecuteCoreState innerState)  
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)  
   at System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult)  
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)  
   at System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult)  
   at System.Web.Mvc.MvcHandler.<>c.<BeginProcessRequest>b__20_1(IAsyncResult asyncResult, ProcessRequestState innerState)  
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)  
   at System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)  
   at Sitecore.Mvc.Routing.RouteHttpHandler.EndProcessRequest(IAsyncResult result)  
   at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()  
   at System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step)  
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)  
 Nested Exception  
 Exception: Microsoft.OData.Client.DataServiceQueryException  
 Message: An error occurred while processing this request.  
 Source: Microsoft.OData.Client  
   at Microsoft.OData.Client.DataServiceRequest.Execute[TElement](DataServiceContext context, QueryComponents queryComponents)  
   at Microsoft.OData.Client.DataServiceContext.InnerSynchExecute[TElement](Uri requestUri, String httpMethod, Nullable`1 singleResult, OperationParameter[] operationParameters)  
   at Microsoft.OData.Client.DataServiceActionQuery`1.Execute()  
   at Sitecore.Commerce.ServiceProxy.Proxy.Execute[T](DataServiceActionQuery`1 query)  
   at Sitecore.Commerce.Engine.Connect.Pipelines.Inventory.GetStockInformation.Process(ServicePipelineArgs args)  
   at (Object , Object )  
   at Sitecore.Pipelines.CorePipeline.Run(PipelineArgs args)  
   at Sitecore.Pipelines.DefaultCorePipelineManager.Run(String pipelineName, PipelineArgs args, String pipelineDomain, Boolean failIfNotExists)  
   at Sitecore.Pipelines.DefaultCorePipelineManager.Run(String pipelineName, PipelineArgs args, String pipelineDomain)  
   at Sitecore.Commerce.Pipelines.PipelineService.RunPipeline[TArgs](String pipelineName, TArgs args)  
   at Sitecore.Commerce.Services.ServiceProvider.RunPipeline[TRequest,TResult](String pipelineName, TRequest request)  
   at Sitecore.Commerce.XA.Foundation.Connect.Managers.InventoryManager.GetStockInformation(CommerceStorefront storefront, IEnumerable`1 products, StockDetailsLevel detailsLevel, Boolean includeBundledItemsInventory, StringPropertyCollection propertyBag)  
   at Sitecore.Commerce.XA.Foundation.Connect.Managers.InventoryManager.GetProductsStockStatusFromConnect(CommerceStorefront storefront, ICollection`1 productEntityList, StringPropertyCollection propertyBag)  
   at Sitecore.Commerce.XA.Feature.Catalog.Repositories.PromotedProductsRepository.AdjustProductStockStatus(ICollection`1 productEntityList)  
   at Sitecore.Commerce.XA.Feature.Catalog.Repositories.PromotedProductsRepository.GetPromotedProductsJsonResult(IVisitorContext visitorContext, String productListId, String relationshipFieldId, String currentItemId, String currentCatalogItemId, Nullable`1 pageSize, Nullable`1 pageNumber, StringPropertyCollection propertyBag)  
   at lambda_method(Closure , ControllerBase , Object[] )  
   at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)  
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c.<BeginInvokeSynchronousActionMethod>b__9_0(IAsyncResult asyncResult, ActionInvocation innerInvokeState)  
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult)  
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)  
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__11_0()  
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass11_1.<InvokeActionMethodFilterAsynchronouslyRecursive>b__2()  
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass11_1.<InvokeActionMethodFilterAsynchronouslyRecursive>b__2()  
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult)  
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass3_6.<BeginInvokeAction>b__3()  
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass3_1.<BeginInvokeAction>b__5(IAsyncResult asyncResult)  
Solution -

I compared the solution dlls with the default setup and found diff in .Net core version - After updating the right version this issue has been resolved -


Basically in project solution, the reference has mentioned with 2.1.* and it was not the correct version.



Simple steps to configure - Sitecore.Commerce.Core.AutoApprovePolicy




If Sitecore XC sellable items are not getting published or it automatically removed (weird scenario) - It could be because you have not published sellable items correctly.

For the catalog import, there are a few options available - but if you want to use the Sitecore XC APIs, It's a good option to enable AutoApprovePolicy and remove once you finish your import.

If you are using the commerce core than you can set up this through the AutoApprovePolicy()

 public class ImportCatalogsCommand : CommerceCommand  
 {  
      public IImportCatalogsPipeline ImportCatalogsPipeline  
      {  
           get;  
      }  
      public ImportCatalogsCommand(IImportCatalogsPipeline importCatalogsPipeline, IServiceScopeFactory serviceScopeFactory)  
           : base(serviceScopeFactory)  
      {  
           Condition.Requires(importCatalogsPipeline, "importCatalogsPipeline").IsNotNull();  
           ImportCatalogsPipeline = importCatalogsPipeline;  
      }  
      public virtual async Task  
 <CommerceCommand> Process(CommerceContext commerceContext, IFormFile importFile, string mode, int batchSize, int errorThreshold, bool publishEntities = true)  
      {  
           using (CommandActivity.Start(commerceContext, this))  
           {  
                CommercePipelineExecutionContextOptions pipelineContextOptions = commerceContext.PipelineContextOptions;  
                ImportCatalogsArgument arg = new ImportCatalogsArgument(importFile, mode)  
                {  
                     BatchSize = batchSize,  
                     ErrorThreshold = errorThreshold  
                };  
                if (publishEntities)  
                {  
                     commerceContext.Environment.SetPolicy(new AutoApprovePolicy());  
                }  
                ImportResult importResult = await ImportCatalogsPipeline.Run(arg, pipelineContextOptions).ConfigureAwait(continueOnCapturedContext: false);  
                if (importResult != null)  
                {  
                     base.Messages.AddRange(importResult.Errors);  
                     base.ResponseCode = importResult.ResultCode;  
                }  
                else  
                {  
                     base.ResponseCode = commerceContext.GetPolicy  
      <KnownResultCodes>().Error;  
                }  
                if (publishEntities)  
                {  
                     commerceContext.Environment.RemovePolicy(typeof(AutoApprovePolicy));  
                }  
                return this;  
           }  
      }  
 }  
You can set up this directly in the policy during the import - If you are using the commerce API 

 { "$type": "Sitecore.Commerce.Core.AutoApprovePolicy, Sitecore.Commerce.Core", }