public bool UpdateProduct(AmzProduct p)
        {

            bool result = true;
            logger.InfoFormat("Updating product: {0} - {1}", p.ProductName, p.ProductDescription);

            if (p.ProductName.Length >= 150)
                p.ProductName = p.ProductName.Substring(0, 149);

            if (p.ProductDescription.Length >= 255)
                p.ProductDescription = p.ProductDescription.Substring(0, 254);


            DateTime updateDate = DateTime.UtcNow;
            string updatedBy = HttpContext.Current.Request.LogonUserIdentity.Name; 
            if(string.IsNullOrEmpty(updatedBy))
            {
                logger.Warn("Couldn't figure out HttpContext user identity. Using Environment.UserName instead");
                updatedBy = Environment.UserName;
            }
            using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
            {
                conn.Open();
                try
                {
                    conn.Execute(@"
                                                        update amz.Products
                                                        set ProductName = @ProductName
                                                            , ProductDescription = @ProductDescription
                                                            , ProductLongDescription = @ProductLongDescription
                                                            , UnitPrice = @UnitPrice
                                                            , UnitsInStock = @UnitsInStock
                                                            , UnitsOnOrder = @UnitsOnOrder
                                                            , Discontinued = @Discontinued
                                                            , ImageUploadSuccessful = @ImageUploadSuccessful
                                                            , ModifiedDate = @updateDate
                                                            , ModifiedBy = @updatedBy
                                                            , ImageIdOne = @ImageIdOne
                                                            , ImageIdTwo = @ImageIdTwo
                                                            , ImageIdThree = @ImageIdThree
                                                            , ImageIdFour = @ImageIdFour
                                                            , ImageIdFive = @ImageIdFive
                                                            , SectionID = @SectionID
                                                        where ProductID = @ProductID

                                                    ",
                                                    new {
                                                        p.ProductName
                                                        ,p.ProductDescription
                                                        ,p.ProductLongDescription
                                                        ,p.UnitPrice
                                                        ,p.UnitsInStock
                                                        ,p.UnitsOnOrder
                                                        ,p.Discontinued
                                                        ,p.ImageUploadSuccessful
                                                        ,updateDate
                                                        ,updatedBy
                                                        ,p.ImageIdOne
                                                        ,p.ImageIdTwo
                                                        ,p.ImageIdThree
                                                        ,p.ImageIdFour
                                                        ,p.ImageIdFive
                                                        ,p.ProductID
                                                        ,p.SectionID
                                                    });


                }
                catch (Exception ex)
                {
                    result = false;
                    logger.Error(ex);
                }

            }
            return result;

        }
        public bool DeleteProduct(AmzProduct p)
        {

            bool result = true;
            logger.InfoFormat("Deleting product: {0} - {1}", p.ProductName, p.ProductDescription);
            DateTime updateDate = DateTime.UtcNow;
            string updatedBy = HttpContext.Current.Request.LogonUserIdentity.Name;
            if (string.IsNullOrEmpty(updatedBy))
            {
                logger.Warn("Couldn't figure out HttpContext user identity. Using Environment.UserName instead");
                updatedBy = Environment.UserName;
            }
            using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
            {
                conn.Open();
                try
                {
                    conn.Execute(@"
                                                        delete amz.Products
                                                        where ProductID = @ProductID

                                                    ",
                                                    new
                                                    {
                                                        p.ProductID
                                                    });


                }
                catch (Exception ex)
                {
                    result = false;
                    logger.Error(ex);
                }

            }
            return result;

        }
        public  AmzProduct AddProduct(AmzProduct p)
        {

            logger.InfoFormat("Adding product: {0} - {1}", p.ProductName, p.ProductDescription);
            if (p.ProductName.Length >= 150)
                p.ProductName = p.ProductName.Substring(0, 149);

            if (p.ProductDescription.Length >= 255)
                p.ProductDescription = p.ProductDescription.Substring(0, 254);


            DateTime addDate = DateTime.UtcNow;
            string addedBy = HttpContext.Current.Request.LogonUserIdentity.Name;
            if (string.IsNullOrEmpty(addedBy))
            {
                logger.Warn("Couldn't figure out HttpContext user identity. Using Environment.UserName instead");
                addedBy  = Environment.UserName;
            }

            using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
            {
                conn.Open();
                try
                {
                    var result = conn.Query<int>(@"
                                                        insert into amz.Products
                                                        (ProductName
                                                        , ProductDescription
                                                        , ProductLongDescription
                                                        , UnitPrice
                                                        , UnitsInStock
                                                        , UnitsOnOrder
                                                        , Discontinued
                                                        , ImageUploadSuccessful
                                                        , SmallImageId
                                                        , MediumImageId
                                                        , LargeImageId
                                                        , OriginalImageId
                                                        , ImageIdOne
                                                        , ImageIdTwo
                                                        , ImageIdThree
                                                        , ImageIdFour
                                                        , ImageIdFive
                                                        , AddDate
                                                        , AddedBy
                                                        )
                                                        values(@ProductName
                                                            , @ProductDescription
                                                            , @ProductLongDescription
                                                            , @UnitPrice
                                                            , @UnitsInStock
                                                            , @UnitsOnOrder
                                                            , @Discontinued
                                                            , @ImageUploadSuccessful
                                                            , @SmallImageId
                                                            , @MediumImageId
                                                            , @LargeImageId
                                                            , @OriginalImageId
                                                            , @ImageIdOne
                                                            , @ImageIdTwo
                                                            , @ImageIdThree
                                                            , @ImageIdFour
                                                            , @ImageIdFive
                                                            , getdate()
                                                            , @addedBy
                                                        )
                                                        SELECT SCOPE_IDENTITY()

                        ", new { p.ProductName
                                ,p.ProductDescription
                                ,p.ProductLongDescription
                                ,p.UnitPrice
                                ,p.UnitsInStock
                                ,p.UnitsOnOrder
                                ,p.Discontinued
                                ,p.ImageUploadSuccessful
                                ,p.SmallImageId
                                ,p.MediumImageId
                                ,p.LargeImageId
                                ,p.OriginalImageId
                                ,p.ImageIdOne
                                ,p.ImageIdTwo
                                ,p.ImageIdThree
                                ,p.ImageIdFour
                                ,p.ImageIdFive
                                ,addDate
                                ,addedBy
                                });


                    if(result.Any())
                    {
                        int insertedProductId = (int)result.ElementAtOrDefault(0);
                        return GetProduct(insertedProductId);
                    }


                }
                catch (Exception ex)
                {
                    logger.Error(ex);
                }

            }
            return null;

        }
        public ActionResult UploadProduct(IEnumerable<HttpPostedFileBase> files, string productName, string productDescription, string productLongDescription, decimal unitPrice, int unitInStock)
        {
            string uploadMessage = PRODUCT_UPLOAD_SUCCESSFUL;
            bool fileUploadFailed = false;
            bool fileIsValid = true;
            try
            {
                var request = System.Web.HttpContext.Current.Request;

                FileInfo fi = new FileInfo(files.ElementAtOrDefault(0).FileName);
                if (!fi.Extension.ToLower().Equals(".jpg"))
                {
                    uploadMessage = "Please upload a valid [.jpg] image file";
                }


                
                if (fileIsValid)
                {
                    AmzProduct product = new AmzProduct()
                    {
                        ProductName = productName
                        ,ProductDescription = productDescription
                        ,ProductLongDescription = productLongDescription
                        ,UnitPrice = unitPrice
                        ,UnitsInStock = unitInStock
                    };
                    
                    //string path = System.Web.HttpContext.Current.Server.MapPath("~/UploadedImages");
                    //DirectoryInfo di = new DirectoryInfo(path);
                    //if (!di.Exists)
                    //{
                    //    di.Create();
                    //}

                    string nowTicks = DateTime.Now.Ticks.ToString();
                    string destinationFilePath = System.Web.HttpContext.Current.Server.MapPath("~/Content/products");

                    string originalImageId = string.Format("AMZ_Original_{0}.jpg",nowTicks);
                    string sourceFile = string.Format(@"{0}\{1}", destinationFilePath, originalImageId);

                    files.ElementAtOrDefault(0).SaveAs(sourceFile);
                    logger.InfoFormat("Saved input file as {0}", sourceFile);
                    product.OriginalImageId = originalImageId;


                    Bitmap bmOriginal = new Bitmap(sourceFile);
                    ImageHandler ih = new ImageHandler();

                    

                    product.SmallImageId =  string.Format(@"AMZ_Small_{0}.jpg", nowTicks);
                    ih.Save(bmOriginal, 100, 100, 100, string.Format(@"{0}\{1}",destinationFilePath,product.SmallImageId));
                    logger.InfoFormat("Resized input file and saved as {0}", product.SmallImageId);

                    product.MediumImageId = string.Format(@"AMZ_Medium_{0}.jpg", nowTicks);
                    ih.Save(bmOriginal, 400, 400, 100, string.Format(@"{0}\{1}",destinationFilePath, product.MediumImageId));
                    logger.InfoFormat("Resized input file and saved as {0}", product.MediumImageId);

                    product.LargeImageId = string.Format(@"AMZ_Large_{0}.jpg", nowTicks);
                    ih.Save(bmOriginal, 400, 400, 100, string.Format(@"{0}\{1}",destinationFilePath, product.LargeImageId));
                    logger.InfoFormat("Resized input file and saved as {0}",product.LargeImageId);


                    if(files.ElementAtOrDefault(1) != null )
                    {
                        originalImageId = string.Format("AMZ_Image_1_{0}.jpg", nowTicks);
                        sourceFile = string.Format(@"{0}\{1}", destinationFilePath, originalImageId);
                        product.ImageIdOne = originalImageId;
                        files.ElementAtOrDefault(1).SaveAs(sourceFile);
                        logger.InfoFormat("Saved image one file as {0}", sourceFile);
                    }

                    if (files.ElementAtOrDefault(2) != null)
                    {
                        originalImageId = string.Format("AMZ_Image_2_{0}.jpg", nowTicks);
                        sourceFile = string.Format(@"{0}\{1}", destinationFilePath, originalImageId);
                        product.ImageIdTwo = originalImageId;
                        files.ElementAtOrDefault(2).SaveAs(sourceFile);
                        logger.InfoFormat("Saved image two file as {0}", sourceFile);
                    }

                    if (files.ElementAtOrDefault(3) != null)
                    {
                        originalImageId = string.Format("AMZ_Image_3_{0}.jpg", nowTicks);
                        sourceFile = string.Format(@"{0}\{1}", destinationFilePath, originalImageId);
                        product.ImageIdThree = originalImageId;
                        files.ElementAtOrDefault(3).SaveAs(sourceFile);
                        logger.InfoFormat("Saved image three file as {0}", sourceFile);
                    }

                    if (files.ElementAtOrDefault(4) != null)
                    {
                        originalImageId = string.Format("AMZ_Image_4_{0}.jpg", nowTicks);
                        sourceFile = string.Format(@"{0}\{1}", destinationFilePath, originalImageId);
                        product.ImageIdFour = originalImageId;
                        files.ElementAtOrDefault(4).SaveAs(sourceFile);
                        logger.InfoFormat("Saved image four file as {0}", sourceFile);
                    }

                    if (files.ElementAtOrDefault(5) != null)
                    {
                        originalImageId = string.Format("AMZ_Image_5_{0}.jpg", nowTicks);
                        sourceFile = string.Format(@"{0}\{1}", destinationFilePath, originalImageId);
                        product.ImageIdFive = originalImageId;
                        files.ElementAtOrDefault(5).SaveAs(sourceFile);
                        logger.InfoFormat("Saved image five file as {0}", sourceFile);
                    }





                    product.ImageUploadSuccessful = true;

                    productHandler.AddProduct(product);

                    logger.InfoFormat(PRODUCT_UPLOAD_SUCCESSFUL);

                    //try
                    //{
                    //    FileInfo fiFileToDelete = new FileInfo(sourceFile);
                    //    if (fiFileToDelete.Exists)
                    //        fiFileToDelete.Delete();
                    //    logger.InfoFormat("Removed file {0}", sourceFile);

                    //}
                    //catch (Exception ex1)
                    //{
                    //    logger.Error(ex1);

                    //}
                }

            }
            catch (Exception ex)
            {
                logger.Error(ex);
                uploadMessage = string.Format("Product upload failed: Error: {0}", ex.Message);
                fileUploadFailed = true;
            }


            return RedirectToAction("Index", new RouteValueDictionary(
                                                new { controller = "ProductAdmin", action = "Index", message = uploadMessage, status = fileUploadFailed }));
        }
        public ActionResult Editing_Destroy([DataSourceRequest] DataSourceRequest request, AmzProduct product)
        {
            string destinationFilePath = System.Web.HttpContext.Current.Server.MapPath("~/Content/products");
                    
                try
                {
                    string fileToDelete = string.Format(@"{0}\{1}", destinationFilePath, product.OriginalImageId);
                    FileInfo fi = new FileInfo(fileToDelete);
                    if (fi.Exists)
                    {
                        try
                        {
                            fi.Delete();
                        }
                        catch { }
                    }
                    fileToDelete = string.Format(@"{0}\{1}", destinationFilePath, product.SmallImageId);
                    fi = new FileInfo(fileToDelete);
                    if (fi.Exists)
                    {
                        try {
                            fi.Delete();
                        }
                        catch { }
                    }
                    fileToDelete = string.Format(@"{0}\{1}", destinationFilePath, product.MediumImageId);
                    fi = new FileInfo(fileToDelete);
                    if (fi.Exists)
                    {
                        try {
                            fi.Delete();
                        }
                        catch { }
                    }
                    fileToDelete = string.Format(@"{0}\{1}", destinationFilePath, product.LargeImageId);
                    fi = new FileInfo(fileToDelete);
                    if (fi.Exists)
                    {
                        try {
                            fi.Delete();
                        }
                        catch { }
                    }
                    fileToDelete = string.Format(@"{0}\{1}", destinationFilePath, product.ImageIdOne);
                    fi = new FileInfo(fileToDelete);
                    if (fi.Exists)
                    {
                        try {
                            fi.Delete();
                        }
                        catch { }

                    }
                    fileToDelete = string.Format(@"{0}\{1}", destinationFilePath, product.ImageIdTwo);
                    fi = new FileInfo(fileToDelete);
                    if (fi.Exists)
                    {
                        try {
                            fi.Delete();
                        }
                        catch { }
                    }
                    fileToDelete = string.Format(@"{0}\{1}", destinationFilePath, product.ImageIdThree);
                    fi = new FileInfo(fileToDelete);
                    if (fi.Exists)
                    {
                        try {
                            fi.Delete();
                        }
                        catch { }
                    }
                    fileToDelete = string.Format(@"{0}\{1}", destinationFilePath, product.ImageIdFour);
                    fi = new FileInfo(fileToDelete);
                    if (fi.Exists)
                    {
                        try {
                            fi.Delete();
                        }
                        catch { }
                    }
                    fileToDelete = string.Format(@"{0}\{1}", destinationFilePath, product.ImageIdFive);
                    fi = new FileInfo(fileToDelete);
                    if (fi.Exists)
                    {
                        try {
                            fi.Delete();
                        }
                        catch { }
                    }



                }
                catch (Exception ex)
                {
                    logger.Fatal(ex);
                }


                productHandler.DeleteProduct(product);

            return Json(new[] { product }.ToDataSourceResult(request, ModelState));
        }
        public ActionResult Editing_Update([DataSourceRequest] DataSourceRequest request, AmzProduct product)
        {
            productHandler.UpdateProduct(product);

            return Json(new[] { product }.ToDataSourceResult(request, ModelState));
        }
        public ActionResult Editing_Create([DataSourceRequest] DataSourceRequest request, AmzProduct product)
        {

            var addedProduct = productHandler.AddProduct(product);
            if (addedProduct != null)
            {
                ViewBag.Message = "Record saved";
                ViewBag.ErrorFound = false;

                product.ProductID = addedProduct.ProductID;
            }
            else
            {
                ViewBag.Message = "Failed to save record";
                ViewBag.ErrorFound = true;

            }


            return Json(new[] { product }.ToDataSourceResult(request, ModelState));
        }