Sample Code
public class GetStockLevels : IHttpHandler
{
private class StockRecord
{
public String ID { get; set; }
public String Description { get; set; }
public Int64 FreeStock { get; set; }
}
public class ProductVariantOption
{
public Int64 StockLevel { get; set; }
public DateTime StockCheckDate { get; set; }
}
public class Product
{
public Int64 StockLevel { get; set; }
public DateTime StockCheckDate { get; set; }
}
public void ProcessRequest(HttpContext context)
{
Boolean blnErrorOccured = false;
Int32 intSuccessfullyUpdated = 0;
Int32 intFailedToUpdate = 0;
List<String> lstNotFoundProducts = new List<String>();
String strApiKey = String.Empty;
String strJSONResponse = String.Empty;
String strEndpointURL = String.Empty;
if (WebConfigurationManager.AppSettings["Newton.Enabled"] == "Yes")
{
strEndpointURL = WebConfigurationManager.AppSettings["Newton.GetStock.URL"];
strApiKey = WebConfigurationManager.AppSettings["Newton.API.Key"];
}
else
{
strEndpointURL = "https://secure.mrm.co.uk/StockQueryapiHTTP.ashx";
if (WebConfigurationManager.AppSettings["UniverseMode"] == "LIVE")
{
strApiKey = WebConfigurationManager.AppSettings["LIVEFulfilmentApiKey"];
}
else
{
strApiKey = WebConfigurationManager.AppSettings["TESTFulfilmentApiKey"];
}
}
//get stock records
using (WebClient client = new WebClient())
{
try
{
byte[] response = client.UploadValues(strEndpointURL, new NameValueCollection()
{
{ "ApiKey", strApiKey },
{ "Criteria", "A" },
{ "Value", "" }
});
strJSONResponse = Encoding.UTF8.GetString(response, 0, response.Length);
}
catch (Exception ex)
{
strJSONResponse = ex.Message;
blnErrorOccured = true;
}
}
if (strJSONResponse.Contains("{\"Error"))
{
blnErrorOccured = true;
}
if (String.IsNullOrWhiteSpace(strJSONResponse))
{
strJSONResponse = "Unable to process, blank response.";
blnErrorOccured = true;
}
if (!blnErrorOccured)
{
//update local stock records
using (DatabaseContext _db = new Database.Models.DatabaseContext())
{
List<StockRecord> lstStockRecords = JsonConvert.DeserializeObject<List<StockRecord>>(strJSONResponse);
foreach (StockRecord _stockRecord in lstStockRecords)
{
Boolean blnUpdatedProduct = false;
//lookup item in product variants options table
ProductVariantOption _productVariant = _db.ProductVariantOptions.FirstOrDefault(w => w.FulfilmentCatalogueCode == _stockRecord.ID && w.Deleted == false && w.ProductVariant.Product.Deleted == false);
if (_productVariant != null)
{
_productVariant.StockLevel = _stockRecord.FreeStock;
_productVariant.StockCheckDate = DateTime.UtcNow;
blnUpdatedProduct = true;
intSuccessfullyUpdated += 1;
}
//lookup item in products table
Product _product = _db.Products.FirstOrDefault(w => w.FulfilmentCatalogueCode == _stockRecord.ID && w.Deleted == false);
if (_product != null)
{
_product.StockLevel = _stockRecord.FreeStock;
_product.StockCheckDate = DateTime.UtcNow;
blnUpdatedProduct = true;
intSuccessfullyUpdated += 1;
}
if (blnUpdatedProduct)
{
_db.SaveChanges();
}
else
{
//unable to find product in DB with this catalogue code.
intFailedToUpdate += 1;
lstNotFoundProducts.Add(String.Format("{0} - {1}", _stockRecord.ID, _stockRecord.Description));
}
}
}
}
if (blnErrorOccured)
{
context.Response.ContentType = "text/plain";
context.Response.Write(String.Format("An error occured: {0}", strJSONResponse));
//send notification email
String strSubject = String.Format("Error occured when updating stock records from fulfilment system - {0}", WebConfigurationManager.AppSettings["SiteName"]);
String strMessage = File.ReadAllText(context.Server.MapPath("~/EmailTemplates/") + WebConfigurationManager.AppSettings["FailedToUpdateStockRecordsFromFulfilmentEmail"]);
//replace keywords
strMessage = strMessage.Replace("[ErrorMessage]", strJSONResponse);
strMessage = strMessage.Replace("[SiteName]", WebConfigurationManager.AppSettings["SiteName"]);
strMessage = strMessage.Replace("[SiteURL]", WebConfigurationManager.AppSettings["SiteURL"]);
SendEmail.Send(WebConfigurationManager.AppSettings["EmailFromAddress"], WebConfigurationManager.AppSettings["FulfillmentIntegrationErrorEmailAddress"], strSubject, strMessage);
SystemLog.Add("E05", strSubject, WebConfigurationManager.AppSettings["FulfillmentIntegrationErrorEmailAddress"], (int)SiteSection.Emails);
}
else {
context.Response.ContentType = "text/plain";
context.Response.Write(String.Format("Successfully updated: {0} stock records from the fulfilment system. ", intSuccessfullyUpdated));
if (intFailedToUpdate > 0)
{
context.Response.Write(String.Format("{0} catalogue code(s) was not found in the webshop SQL database when attempting to update it, they are the following: {1}", intFailedToUpdate, String.Join(",", lstNotFoundProducts)));
}
if (intSuccessfullyUpdated == 0 && intFailedToUpdate == 0) {
context.Response.Write("No stockcodes to process.");
}
}
}
}
}