using System; using System.Collections.Generic; using Microsoft.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace bnhtrade.Core.Data.Database.AmazonShipment { public class ReadShipmentPrimaryKey : Connection { private bool enableCache = false; private Dictionary shipmentPKByAmazonShipmentIdDic; private Dictionary amazonShipmentIdByShipmentPKDic; public ReadShipmentPrimaryKey() { } public bool CacheEnabled { get { return enableCache; } set { if (value && enableCache == false) { shipmentPKByAmazonShipmentIdDic = new Dictionary(); amazonShipmentIdByShipmentPKDic = new Dictionary(); } else { shipmentPKByAmazonShipmentIdDic = null; amazonShipmentIdByShipmentPKDic = null; } } } private void ClearCache() { if (CacheEnabled) { shipmentPKByAmazonShipmentIdDic.Clear(); amazonShipmentIdByShipmentPKDic.Clear(); } } private void DeleteCachedShipmentPK(int shipmentPrimaryKey) { if (CacheEnabled) { if (amazonShipmentIdByShipmentPKDic.ContainsKey(shipmentPrimaryKey)) { string amazonShipmentId = amazonShipmentIdByShipmentPKDic[shipmentPrimaryKey]; shipmentPKByAmazonShipmentIdDic.Remove(amazonShipmentId); amazonShipmentIdByShipmentPKDic.Remove(shipmentPrimaryKey); } } } /// /// Retrives table primary key 'AmazonShipmentID' for tblAmazonShipment /// /// Amazon's inbound FBA shipment Id. /// Forces a database query when cache is enabled. /// Primary key or -1 if match isn't found. public int ByAmazonShipmentId(string amazonShipmentId, bool forceDBQuery = false) { if (amazonShipmentId.Length < 5) { throw new Exception("Incorrect Amazon shipment if supplied '" + amazonShipmentId + "'"); } // first, query class dictionary before sql call if (CacheEnabled && forceDBQuery == false && shipmentPKByAmazonShipmentIdDic.ContainsKey(amazonShipmentId)) { return shipmentPKByAmazonShipmentIdDic[amazonShipmentId]; } int shipmentPK = -1; using (SqlConnection conn = new SqlConnection(SqlConnectionString)) { conn.Open(); using (SqlCommand cmd = new SqlCommand(@" SELECT AmazonShipmentID FROM tblAmazonShipment WHERE (((tblAmazonShipment.ShipmentId)=@amazonShipmentId)); ", conn)) { cmd.Parameters.AddWithValue("@amazonShipmentId", amazonShipmentId); object obj = cmd.ExecuteScalar(); if (obj == null || obj == DBNull.Value) { return shipmentPK; } else { shipmentPK = (int)obj; } } } UpdateCache(shipmentPK, amazonShipmentId); return shipmentPK; } private void UpdateCache(int shipmentPK, string amazonShipmentId) { if (CacheEnabled) { DeleteCachedShipmentPK(shipmentPK); shipmentPKByAmazonShipmentIdDic.Add(amazonShipmentId, shipmentPK); amazonShipmentIdByShipmentPKDic.Add(shipmentPK, amazonShipmentId); } } } }