public string Upsert(JMCreateNewItem jmcreatenewitem )
        {
            try
            {

                //If Id already exists. just return.
                //if (!string.IsNullOrEmpty(jmcreatenewitem.ItemId))
                //{
                //    result.InventoryId = Convert.ToInt32(jmcreatenewitem.ItemId);
                //    return JsonConvert.SerializeObject(result);
                //}


                //First Check certain Fields are NOT Blank.
                if(string.IsNullOrEmpty(jmcreatenewitem.ItemBrand) || string.IsNullOrEmpty(jmcreatenewitem.ItemCategory.Trim()) ||  string.IsNullOrEmpty(jmcreatenewitem.ItemName))
                {
                    throw new ResultApiException("1 of 3 Important Fields missing: Brand, Category, Item Name.", ApiStatusCode.ERROR, "", iserror: true);
                }

                //Second Check if Category already exists. If so Just grab the ID. else Create the Category. Is Case InSensitive
                var catquery = string.Format(@"  SELECT Id 
                                                 FROM {0} 
                                                 WHERE Category = @catname ", TableNames.TableCategories);
                var categoryid = DapperWrapper.Query<int>(catquery, new { catname = jmcreatenewitem.ItemCategory }).FirstOrDefault();

                if (categoryid == 0) //Item doesnt exist so Create it.
                {
                    catquery = string.Format(@"  INSERT INTO {0} (Category) 
                                                 VALUES (@catname)", TableNames.TableCategories);
                    categoryid = DapperWrapper.Insert(catquery, new { catname = jmcreatenewitem.ItemCategory });
                }



               /* OLD INSERT: INSERT INTO BHNInventory (ItemName, ItemCategoryId, ItemSubCategory, ItemColor, ItemColorCode, ItemPrice, ItemBrand)
                                 values( @itemname, @itemcategoryid, @itemsubcategory, @itemcolor, @itemcolorcode, @itemprice, @itembrand )*/

                var inventoryMerge = string.Format(@" 
                                        MERGE INTO {0} WITH (HOLDLOCK) AS target
                                        USING ( SELECT @itemname as ItemName, 
                                                       @itemcategoryid as ItemCategoryId, 
                                                       @itemsubcategory as ItemSubCategory, 
                                                       @itemcolor as ItemColor, 
                                                       @itemcolorcode as ItemColorCode, 
                                                       @itemprice as ItemPrice, 
                                                       @itembrand as ItemBrand ) AS source
                                            ON target.Id = @itemid
                                        WHEN MATCHED THEN --UPDATE
                                            UPDATE SET target.ItemName = source.ItemName,
                                                       target.ItemCategoryId = source.ItemCategoryId,
                                                       target.ItemSubCategory = source.ItemSubCategory,
                                                       target.ItemColor = source.ItemColor,
                                                       target.ItemColorCode = source.ItemColorCode,
                                                       target.ItemPrice = source.ItemPrice,
                                                       target.ItemBrand = source.ItemBrand

                                        WHEN NOT MATCHED BY TARGET THEN -- ELSE INSERT
                                            INSERT (ItemName, ItemCategoryId, ItemSubCategory, ItemColor, ItemColorCode, ItemPrice, ItemBrand)
                                            VALUES ( source.ItemName, source.ItemCategoryId, source.ItemSubCategory, source.ItemColor, source.ItemColorCode, source.ItemPrice, source.ItemBrand );
                                         ", TableNames.TableInventory);
                var inventoryid = DapperWrapper.Insert(inventoryMerge, new
                {
                    itemid = jmcreatenewitem.ItemId,
                    itembrand = jmcreatenewitem.ItemBrand,
                    itemname = jmcreatenewitem.ItemName,
                    itemcategoryid = categoryid,
                    itemsubcategory = jmcreatenewitem.ItemSubcategory,
                    itemcolor = jmcreatenewitem.ItemColor,
                    itemcolorcode = jmcreatenewitem.ItemColorCode,
                    itemprice = jmcreatenewitem.ItemPrice
                });

                //If there was an error adding the New Record Cuz of Duplicate Names or so... Delete Image Record too. And Image File.
                if (inventoryid <= 0)
                {
                    //Update was done
                    inventoryid = Convert.ToInt32(jmcreatenewitem.ItemId);
                    //throw new Exception("Error Creating Record : Record might already exist.");
                }


                var result = new ResultIMCreateNewItem();
                result.InventoryId = inventoryid;
                return JsonConvert.SerializeObject(result);

            }//Add ResultApiException
            catch(ResultApiException ex) 
            {
                return JsonConvert.SerializeObject(ex);
            }
            catch (Exception ex)
            {
                var newexception = new ResultApiException(ex.Message, ApiStatusCode.ERROR, ex.Message, iserror: true);
                return JsonConvert.SerializeObject(newexception);
            } 
        }
        private ImageSize ShowcaseSize = new ImageSize(254, 300);  //Used in Store Category and Store View


        //Param Data is passed as FormData Object from the FileUpload "Data" Object.
        public string SingleFileUpload(string inventoryid, string imagepos)
        {
            try
            {
                //Check the Data is here. Color is possible to be Null since some items dont have color.
                if (string.IsNullOrEmpty(inventoryid) || string.IsNullOrEmpty(imagepos))
                {
                    var message = "Error - Item Id or Image Pos Missing.";
                    var statusmessage = "Error - Item Id or Image Pos Missing.";
                    throw new ResultApiException(message, ApiStatusCode.ERROR, statusmessage, iserror: true);
                }


                if (Request.Files == null || Request.Files.Count == 0)
                {
                    var message = "Error: File for Upload Not Found!";
                    var statusmessage = "Please add file again.";
                    throw new ResultApiException(message, ApiStatusCode.ERROR, statusmessage, iserror: true);
                }


                var pathsuffix = inventoryid;
                var pathshowcase = Path.Combine(RootvirtualPathShowcase, pathsuffix);
                var paththumbnail = Path.Combine(RootVirtualPathThumbs, pathsuffix);
                //Create the Directories if they Don't Exist.
                //Create Directory Method checks by itself if the Folder doesn't Exist. 
                Directory.CreateDirectory(pathshowcase);
                Directory.CreateDirectory(paththumbnail);

                var filename = "";
                //Loop through the Files. Which should be one at a time.
                for (int i = 0; i < Request.Files.Count; i++)
                {
                    //TODO: Check file is Purely an Image File.
                    var file = Request.Files[i];

                    //Todo: Return File Object just to be able to UPdate File Name.
                    var ext = Path.GetExtension(file.FileName);
                    //itemid_[POS].png
                    var newfilename = string.Format("{0}_{1}{2}", inventoryid, imagepos, ext);  
                    var savelocationshowcase = Path.Combine(pathshowcase, newfilename);
                    var savelocationthumbnail = Path.Combine(paththumbnail, newfilename);


                    //Create Image Object From File.
                    var imageobj = Image.FromStream(file.InputStream);
                    //Showcase Version
                    var img = GlobalHelper.ScaleImage(imageobj, ShowcaseSize.Height, ShowcaseSize.Width);
                    img.Save(savelocationshowcase);
                    //Thumbnail version.
                    img = GlobalHelper.ScaleImage(imageobj, ThumbnailSize.Height, ThumbnailSize.Width);
                    img.Save(savelocationthumbnail);


                    //Now Create the Image Record Entry.
                    var insertquery = string.Format(@" INSERT INTO {0} (ImageName, InventoryId)
                                         values (@img, @inventoryid)", TableNames.TableImages);
                    var insertedimage = DapperWrapper.Insert(insertquery, new { img = newfilename, inventoryid = inventoryid });
                    //check the image was inserted.
                    if( insertedimage == 0 ){
                        var errmsg = "Error trying to Insert Image: " + newfilename;
                        throw new ResultApiException(errmsg, ApiStatusCode.ERROR, errmsg, iserror: true);
                    }

                    filename = newfilename;
                }

                //Return Json Object with Message of Success.
                var result = new ResultFUFileUploads
                {
                    Filename = filename,
                };
               return JsonConvert.SerializeObject(result);

            } 
            catch(ResultApiException ex)
            {
                return JsonConvert.SerializeObject(ex);
            }
            catch (DirectoryNotFoundException ex)
            {
                var newexcep = new ResultApiException(ex.Message, ApiStatusCode.ERROR, ex.Message, iserror: true);
                return JsonConvert.SerializeObject(newexcep);
            }
            catch (Exception ex)
            {
                var newexcep = new ResultApiException(ex.Message, ApiStatusCode.ERROR, ex.Message, iserror: true);
                return JsonConvert.SerializeObject(newexcep);
            }
        }