Skip to content

Instantly share code, notes, and snippets.

Created December 17, 2018 18:17
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save websterian/33c3e18c9b15789b7b9c7fcc9ee522c0 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Web.Http.OData;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using Sitecore.Commerce.Core;
using Sitecore.Services.Examples.Catalog.Commands;
using Sitecore.Services.Examples.Catalog.Pipelines.Arguments;
namespace Sitecore.Services.Examples.Catalog.Controllers
public class ApiController : CommerceController
protected internal const string CreateUpdateSellableItemStr = "createUpdateSellableItem";
protected internal const string ProductsStr = "products";
public ApiController(IServiceProvider serviceProvider, CommerceEnvironment globalEnvironment)
: base(serviceProvider, globalEnvironment)
public async Task<IActionResult> CreateUpdateSellableItem([FromBody] ODataActionParameters value)
if (!ModelState.IsValid)
return new BadRequestObjectResult(ModelState);
if (!value.ContainsKey(CreateUpdateSellableItemStr))
return new BadRequestObjectResult(value);
//Handling scenarios where the input is already converted into JArray (postman) or passed through as string
JArray products;
if (value[CreateUpdateSellableItemStr] is JArray == false)
var payload = JObject.Parse(value[CreateUpdateSellableItemStr].ToString());
products = (JArray) payload[ProductsStr];
products = value[CreateUpdateSellableItemStr] as JArray;
var sellableItemArguments = new List<CreateUpdateSellableItemArgument>();
foreach (var product in products)
var sellableItemArgument = new CreateUpdateSellableItemArgument();
var productid = product["productid"].ToString();
sellableItemArgument.ProductId = productid;
var description = product["description"].ToString();
sellableItemArgument.Description = description;
var name = product["name"].ToString();
sellableItemArgument.Name = name;
var displayName = product["displayname"].ToString();
sellableItemArgument.DisplayName = displayName;
var listprice = product["listprice"].ToString();
var isDecimal = decimal.TryParse(listprice, out var n);
if (isDecimal)
sellableItemArgument.ListPrice = Convert.ToDecimal(listprice);
var variants = (JArray) product["variants"];
foreach (var variant in variants)
var variantArg = new CreateUpdateSellableItemVariantArgument(sellableItemArgument.ProductId, variant["variantid"].ToString());
var variantListPrice = variant["listprice"].ToString();
if (decimal.TryParse(variantListPrice, out var outPrice))
variantArg.ListPrice = Convert.ToDecimal(variantListPrice);
var result = await Command<CreateUpdateSellableItemCommand>().Process(CurrentContext, sellableItemArguments);
return new ObjectResult(result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment