public ActionResult Reviewed(int Id, string IndexType, string UserRemark, string IsContinue)
        {
            bool BeforeSave = true;

            try
            {
                BeforeSave = ExcessMaterialDocEvents.beforeHeaderReviewEvent(this, new StockEventArgs(Id), ref context);
            }
            catch (Exception ex)
            {
                string message = _exception.HandleException(ex);
                TempData["CSEXC"] += message;
            }

            if (!BeforeSave)
            {
                TempData["CSEXC"] += "Falied validation before Review.";
            }

            ExcessMaterialHeader pd = new ExcessMaterialHeaderService(_unitOfWork, context).Find(Id);

            if (ModelState.IsValid && BeforeSave)
            {
                pd.ReviewCount = (pd.ReviewCount ?? 0) + 1;
                pd.ReviewBy   += User.Identity.Name + ", ";

                pd.ObjectState = Model.ObjectState.Modified;
                context.ExcessMaterialHeader.Add(pd);

                try
                {
                    ExcessMaterialDocEvents.onHeaderReviewEvent(this, new StockEventArgs(Id), ref context);
                }
                catch (Exception ex)
                {
                    string message = _exception.HandleException(ex);
                    TempData["CSEXC"] += message;
                }

                context.SaveChanges();

                try
                {
                    ExcessMaterialDocEvents.afterHeaderReviewEvent(this, new StockEventArgs(Id), ref context);
                }
                catch (Exception ex)
                {
                    string message = _exception.HandleException(ex);
                    TempData["CSEXC"] += message;
                }

                LogActivity.LogActivityDetail(LogVm.Map(new ActiivtyLogViewModel
                {
                    DocTypeId    = pd.DocTypeId,
                    DocId        = pd.ExcessMaterialHeaderId,
                    ActivityType = (int)ActivityTypeContants.Reviewed,
                    UserRemark   = UserRemark,
                    DocNo        = pd.DocNo,
                    DocDate      = pd.DocDate,
                    DocStatus    = pd.Status,
                }));

                //SendEmail_POReviewd(Id);
                return(RedirectToAction("Index", new { id = pd.DocTypeId, IndexType = IndexType }));
            }

            return(RedirectToAction("Index", new { id = pd.DocTypeId, IndexType = IndexType }).Warning("Error in Reviewing."));
        }
        public ActionResult Submitted(int Id, string IndexType, string UserRemark, string IsContinue, string GenGatePass)
        {
            bool BeforeSave = true;

            try
            {
                BeforeSave = ExcessMaterialDocEvents.beforeHeaderSubmitEvent(this, new StockEventArgs(Id), ref context);
            }
            catch (Exception ex)
            {
                string message = _exception.HandleException(ex);
                TempData["CSEXC"] += message;
                EventException     = true;
            }

            if (!BeforeSave)
            {
                TempData["CSEXC"] += "Falied validation before submit.";
            }

            ExcessMaterialHeader pd = new ExcessMaterialHeaderService(_unitOfWork, context).Find(Id);

            if (ModelState.IsValid && BeforeSave && !EventException)
            {
                if (User.Identity.Name == pd.ModifiedBy || UserRoles.Contains("Admin"))
                {
                    int ActivityType;

                    pd.Status    = (int)StatusConstants.Submitted;
                    ActivityType = (int)ActivityTypeContants.Submitted;

                    ExcessMaterialSettings Settings = new ExcessMaterialSettingsService(_unitOfWork, context).GetExcessMaterialSettingsForDocument(pd.DocTypeId, pd.DivisionId, pd.SiteId);

                    pd.ReviewBy    = null;
                    pd.ObjectState = Model.ObjectState.Modified;

                    context.ExcessMaterialHeader.Add(pd);

                    try
                    {
                        ExcessMaterialDocEvents.onHeaderSubmitEvent(this, new StockEventArgs(Id), ref context);
                    }
                    catch (Exception ex)
                    {
                        string message = _exception.HandleException(ex);
                        TempData["CSEXC"] += message;
                        EventException     = true;
                    }

                    try
                    {
                        if (EventException)
                        {
                            throw new Exception();
                        }

                        context.SaveChanges();
                    }
                    catch (Exception ex)
                    {
                        string message = _exception.HandleException(ex);
                        TempData["CSEXC"] += message;
                        return(RedirectToAction("Index", new { id = pd.DocTypeId }));
                    }


                    try
                    {
                        ExcessMaterialDocEvents.afterHeaderSubmitEvent(this, new StockEventArgs(Id), ref context);
                    }
                    catch (Exception ex)
                    {
                        string message = _exception.HandleException(ex);
                        TempData["CSEXC"] += message;
                    }

                    LogActivity.LogActivityDetail(LogVm.Map(new ActiivtyLogViewModel
                    {
                        DocTypeId    = pd.DocTypeId,
                        DocId        = pd.ExcessMaterialHeaderId,
                        ActivityType = ActivityType,
                        UserRemark   = UserRemark,
                        DocNo        = pd.DocNo,
                        DocDate      = pd.DocDate,
                        DocStatus    = pd.Status,
                    }));


                    return(RedirectToAction("Index", new { id = pd.DocTypeId, IndexType = IndexType }).Success("Record Submitted Successfully"));
                }
                else
                {
                    return(RedirectToAction("Index", new { id = pd.DocTypeId, IndexType = IndexType }).Warning("Record can be submitted by user " + pd.ModifiedBy + " only."));
                }
            }


            return(RedirectToAction("Index", new { id = pd.DocTypeId, IndexType = IndexType }));
        }
        public ActionResult Delete(ReasonViewModel vm)
        {
            bool BeforeSave = true;

            try
            {
                BeforeSave = ExcessMaterialDocEvents.beforeHeaderDeleteEvent(this, new StockEventArgs(vm.id), ref context);
            }
            catch (Exception ex)
            {
                string message = _exception.HandleException(ex);
                TempData["CSEXC"] += message;
                EventException     = true;
            }

            if (!BeforeSave)
            {
                TempData["CSEXC"] += "Failed validation before delete";
            }

            ExcessMaterialHeader ExcessMaterialHeader = (from p in context.ExcessMaterialHeader
                                                         where p.ExcessMaterialHeaderId == vm.id
                                                         select p).FirstOrDefault();

            if (ModelState.IsValid && BeforeSave && !EventException)
            {
                List <LogTypeViewModel> LogList = new List <LogTypeViewModel>();

                try
                {
                    ExcessMaterialDocEvents.onHeaderDeleteEvent(this, new StockEventArgs(vm.id), ref context);
                }
                catch (Exception ex)
                {
                    string message = _exception.HandleException(ex);
                    TempData["CSEXC"] += message;
                    EventException     = true;
                }


                ExcessMaterialHeader ExRec = new ExcessMaterialHeader();
                ExRec = Mapper.Map <ExcessMaterialHeader>(ExcessMaterialHeader);
                ExcessMaterialHeader Rec = new ExcessMaterialHeader();

                LogList.Add(new LogTypeViewModel
                {
                    ExObj = ExRec,
                    Obj   = Rec,
                });

                //Then find all the Purchase Order Header Line associated with the above ProductType.
                //var ExcessMaterialLine = new ExcessMaterialLineService(_unitOfWork).GetExcessMaterialLineforDelete(vm.id);

                var ExcessMaterialLine = (from p in context.ExcessMaterialLine
                                          where p.ExcessMaterialHeaderId == vm.id
                                          select p).ToList();

                //var ProductUids = ExcessMaterialLine.Select(m => m.ProductUidId).ToArray();

                //var ProdUidRecords = (from p in context.ProductUid
                //                      where ProductUids.Contains(p.ProductUIDId)
                //                      select p).ToList();


                //new RequisitionLineStatusService(_unitOfWork).DeleteRequisitionQtyOnIssueMultiple(ExcessMaterialHeader.ExcessMaterialHeaderId, ref context);

                //Mark ObjectState.Delete to all the Purchase Order Lines.
                foreach (var item in ExcessMaterialLine)
                {
                    ExcessMaterialLine ExRecLine = new ExcessMaterialLine();
                    ExRecLine = Mapper.Map <ExcessMaterialLine>(item);
                    ExcessMaterialLine RecLine = new ExcessMaterialLine();

                    LogList.Add(new LogTypeViewModel
                    {
                        ExObj = ExRecLine,
                        Obj   = RecLine,
                    });

                    //if (item.ProductUidId != null && item.ProductUidId > 0)
                    //{
                    //    ProductUidDetail ProductUidDetail = new ProductUidService(_unitOfWork).FGetProductUidLastValues((int)item.ProductUidId, "ExcessMaterial Head-" + ExcessMaterialHeader.ExcessMaterialHeaderId.ToString());

                    //    ProductUid ProductUid = ProdUidRecords.Where(m => m.ProductUIDId == item.ProductUidId).FirstOrDefault();

                    //    ProductUid.LastTransactionDocDate = ProductUidDetail.LastTransactionDocDate;
                    //    ProductUid.LastTransactionDocId = ProductUidDetail.LastTransactionDocId;
                    //    ProductUid.LastTransactionDocNo = ProductUidDetail.LastTransactionDocNo;
                    //    ProductUid.LastTransactionDocTypeId = ProductUidDetail.LastTransactionDocTypeId;
                    //    ProductUid.LastTransactionPersonId = ProductUidDetail.LastTransactionPersonId;
                    //    ProductUid.CurrenctGodownId = ProductUidDetail.CurrenctGodownId;
                    //    ProductUid.CurrenctProcessId = ProductUidDetail.CurrenctProcessId;
                    //    ProductUid.ObjectState = Model.ObjectState.Modified;
                    //    context.ProductUid.Add(ProductUid);

                    //}

                    item.ObjectState = Model.ObjectState.Deleted;
                    context.ExcessMaterialLine.Remove(item);
                }

                ExcessMaterialHeader.ObjectState = Model.ObjectState.Deleted;
                context.ExcessMaterialHeader.Remove(ExcessMaterialHeader);

                //if (GatePassHeaderId.HasValue)
                //{

                //    var GatePassLines = (from p in context.GatePassLine
                //                         where p.GatePassHeaderId == GatePassHeaderId
                //                         select p).ToList();

                //    foreach (var item in GatePassLines)
                //    {
                //        item.ObjectState = Model.ObjectState.Deleted;
                //        context.GatePassLine.Remove(item);
                //    }

                //    GatePassHeader.ObjectState = Model.ObjectState.Deleted;

                //    context.GatePassHeader.Remove(GatePassHeader);

                //}

                XElement Modifications = new ModificationsCheckService().CheckChanges(LogList);

                //Commit the DB
                try
                {
                    if (EventException)
                    {
                        throw new Exception();
                    }
                    context.SaveChanges();
                }

                catch (Exception ex)
                {
                    string message = _exception.HandleException(ex);
                    TempData["CSEXC"] += message;
                    return(PartialView("_Reason", vm));
                }

                try
                {
                    ExcessMaterialDocEvents.afterHeaderDeleteEvent(this, new StockEventArgs(vm.id), ref context);
                }
                catch (Exception ex)
                {
                    string message = _exception.HandleException(ex);
                    TempData["CSEXC"] += message;
                }

                LogActivity.LogActivityDetail(LogVm.Map(new ActiivtyLogViewModel
                {
                    DocTypeId       = ExcessMaterialHeader.DocTypeId,
                    DocId           = ExcessMaterialHeader.ExcessMaterialHeaderId,
                    ActivityType    = (int)ActivityTypeContants.Deleted,
                    UserRemark      = vm.Reason,
                    DocNo           = ExcessMaterialHeader.DocNo,
                    xEModifications = Modifications,
                    DocDate         = ExcessMaterialHeader.DocDate,
                    DocStatus       = ExcessMaterialHeader.Status,
                }));

                return(Json(new { success = true }));
            }
            return(PartialView("_Reason", vm));
        }
        public ActionResult Post(ExcessMaterialHeaderViewModel svm)
        {
            ExcessMaterialHeader s = Mapper.Map <ExcessMaterialHeaderViewModel, ExcessMaterialHeader>(svm);

            System.Web.HttpContext.Current.Session["ExcessMaterialDocDate"] = svm.DocDate;

            #region BeforeSave
            bool BeforeSave = true;
            try
            {
                if (svm.ExcessMaterialHeaderId <= 0)
                {
                    BeforeSave = ExcessMaterialDocEvents.beforeHeaderSaveEvent(this, new StockEventArgs(svm.ExcessMaterialHeaderId, EventModeConstants.Add), ref context);
                }
                else
                {
                    BeforeSave = ExcessMaterialDocEvents.beforeHeaderSaveEvent(this, new StockEventArgs(svm.ExcessMaterialHeaderId, EventModeConstants.Edit), ref context);
                }
            }
            catch (Exception ex)
            {
                string message = _exception.HandleException(ex);
                TempData["CSEXC"] += message;
                EventException     = true;
            }
            if (!BeforeSave)
            {
                TempData["CSEXC"] += "Failed validation before save";
            }
            #endregion

            #region DocTypeTimeLineValidation

            try
            {
                if (svm.ExcessMaterialHeaderId <= 0)
                {
                    TimePlanValidation = DocumentValidation.ValidateDocument(Mapper.Map <DocumentUniqueId>(svm), DocumentTimePlanTypeConstants.Create, User.Identity.Name, out ExceptionMsg, out Continue);
                }
                else
                {
                    TimePlanValidation = DocumentValidation.ValidateDocument(Mapper.Map <DocumentUniqueId>(svm), DocumentTimePlanTypeConstants.Modify, User.Identity.Name, out ExceptionMsg, out Continue);
                }
            }
            catch (Exception ex)
            {
                string message = _exception.HandleException(ex);
                TempData["CSEXC"] += message;
                TimePlanValidation = false;
            }

            if (!TimePlanValidation)
            {
                TempData["CSEXC"] += ExceptionMsg;
            }

            #endregion

            if (ModelState.IsValid && BeforeSave && !EventException && (TimePlanValidation || Continue))
            {
                #region CreateRecord
                if (svm.ExcessMaterialHeaderId <= 0)
                {
                    s.DocNo        = new DocumentTypeService(_unitOfWork).FGetNewDocNo("DocNo", ConfigurationManager.AppSettings["DataBaseSchema"] + ".ExcessMaterialHeaders", s.DocTypeId, s.DocDate, s.DivisionId, s.SiteId);
                    s.CreatedDate  = DateTime.Now;
                    s.ModifiedDate = DateTime.Now;
                    s.CreatedBy    = User.Identity.Name;
                    s.ModifiedBy   = User.Identity.Name;
                    s.Status       = (int)StatusConstants.Drafted;
                    //_ExcessMaterialHeaderService.Create(s);
                    s.ObjectState = Model.ObjectState.Added;
                    context.ExcessMaterialHeader.Add(s);

                    try
                    {
                        ExcessMaterialDocEvents.onHeaderSaveEvent(this, new StockEventArgs(s.ExcessMaterialHeaderId, EventModeConstants.Add), ref context);
                    }
                    catch (Exception ex)
                    {
                        string message = _exception.HandleException(ex);
                        TempData["CSEXC"] += message;
                        EventException     = true;
                    }

                    try
                    {
                        if (EventException)
                        {
                            throw new Exception();
                        }

                        context.SaveChanges();
                        //_unitOfWork.Save();
                    }

                    catch (Exception ex)
                    {
                        string message = _exception.HandleException(ex);
                        TempData["CSEXC"] += message;
                        PrepareViewBag(svm.DocTypeId);
                        ViewBag.Mode = "Add";
                        return(View("Create", svm));
                    }

                    try
                    {
                        ExcessMaterialDocEvents.afterHeaderSaveEvent(this, new StockEventArgs(s.ExcessMaterialHeaderId, EventModeConstants.Add), ref context);
                    }
                    catch (Exception ex)
                    {
                        string message = _exception.HandleException(ex);
                        TempData["CSEXC"] += message;
                    }

                    LogActivity.LogActivityDetail(LogVm.Map(new ActiivtyLogViewModel
                    {
                        DocTypeId    = s.DocTypeId,
                        DocId        = s.ExcessMaterialHeaderId,
                        ActivityType = (int)ActivityTypeContants.Added,
                        DocNo        = s.DocNo,
                        DocDate      = s.DocDate,
                        DocStatus    = s.Status,
                    }));

                    return(RedirectToAction("Modify", "ExcessMaterialHeader", new { Id = s.ExcessMaterialHeaderId }).Success("Data saved successfully"));
                }
                #endregion

                #region EditRecord
                else
                {
                    List <LogTypeViewModel> LogList = new List <LogTypeViewModel>();

                    ExcessMaterialHeader temp = _ExcessMaterialHeaderService.Find(s.ExcessMaterialHeaderId);

                    ExcessMaterialHeader ExRec = new ExcessMaterialHeader();
                    ExRec = Mapper.Map <ExcessMaterialHeader>(temp);

                    int status = temp.Status;

                    if (temp.Status != (int)StatusConstants.Drafted && temp.Status != (int)StatusConstants.Import)
                    {
                        temp.Status = (int)StatusConstants.Modified;
                    }


                    temp.DocDate   = s.DocDate;
                    temp.DocNo     = s.DocNo;
                    temp.PersonId  = s.PersonId;
                    temp.ProcessId = s.ProcessId;
                    temp.GodownId  = s.GodownId;
                    temp.Remark    = s.Remark;

                    temp.ModifiedDate = DateTime.Now;
                    temp.ModifiedBy   = User.Identity.Name;
                    temp.ObjectState  = Model.ObjectState.Modified;
                    context.ExcessMaterialHeader.Add(temp);

                    LogList.Add(new LogTypeViewModel
                    {
                        ExObj = ExRec,
                        Obj   = temp,
                    });

                    XElement Modifications = new ModificationsCheckService().CheckChanges(LogList);

                    try
                    {
                        ExcessMaterialDocEvents.onHeaderSaveEvent(this, new StockEventArgs(temp.ExcessMaterialHeaderId, EventModeConstants.Edit), ref context);
                    }
                    catch (Exception ex)
                    {
                        string message = _exception.HandleException(ex);
                        TempData["CSEXC"] += message;
                        EventException     = true;
                    }

                    try
                    {
                        if (EventException)
                        {
                            throw new Exception();
                        }

                        context.SaveChanges();
                        //_unitOfWork.Save();
                    }

                    catch (Exception ex)
                    {
                        string message = _exception.HandleException(ex);
                        TempData["CSEXC"] += message;
                        PrepareViewBag(svm.DocTypeId);
                        ViewBag.id = svm.DocTypeId;
                        return(View("Create", svm));
                    }

                    try
                    {
                        ExcessMaterialDocEvents.afterHeaderSaveEvent(this, new StockEventArgs(s.ExcessMaterialHeaderId, EventModeConstants.Edit), ref context);
                    }
                    catch (Exception ex)
                    {
                        string message = _exception.HandleException(ex);
                        TempData["CSEXC"] += message;
                    }

                    LogActivity.LogActivityDetail(LogVm.Map(new ActiivtyLogViewModel
                    {
                        DocTypeId       = temp.DocTypeId,
                        DocId           = temp.ExcessMaterialHeaderId,
                        ActivityType    = (int)ActivityTypeContants.Modified,
                        DocNo           = temp.DocNo,
                        xEModifications = Modifications,
                        DocDate         = temp.DocDate,
                        DocStatus       = temp.Status,
                    }));

                    return(RedirectToAction("Index", new { id = svm.DocTypeId }).Success("Data saved successfully"));
                }
                #endregion
            }
            PrepareViewBag(svm.DocTypeId);
            ViewBag.Mode = "Add";
            return(View("Create", svm));
        }
        public ActionResult DeletePost(ExcessMaterialLineViewModel vm)
        {
            bool BeforeSave = true;

            try
            {
                BeforeSave = ExcessMaterialDocEvents.beforeLineDeleteEvent(this, new StockEventArgs(vm.ExcessMaterialHeaderId, vm.ExcessMaterialLineId), ref db);
            }
            catch (Exception ex)
            {
                string message = _exception.HandleException(ex);
                TempData["CSEXC"] += message;
                EventException     = true;
            }

            if (!BeforeSave)
            {
                TempData["CSEXC"] += "Validation failed before delete.";
            }

            if (BeforeSave && !EventException)
            {
                int?ProdUid = 0;
                List <LogTypeViewModel> LogList = new List <LogTypeViewModel>();

                //ExcessMaterialLine ExcessMaterialLine = _ExcessMaterialLineService.Find(vm.ExcessMaterialLineId);
                ExcessMaterialLine ExcessMaterialLine = (from p in db.ExcessMaterialLine
                                                         where p.ExcessMaterialLineId == vm.ExcessMaterialLineId
                                                         select p).FirstOrDefault();
                ExcessMaterialHeader header = new ExcessMaterialHeaderService(_unitOfWork, db).Find(ExcessMaterialLine.ExcessMaterialHeaderId);

                LogList.Add(new LogTypeViewModel
                {
                    ExObj = Mapper.Map <ExcessMaterialLine>(ExcessMaterialLine),
                });

                ProdUid = ExcessMaterialLine.ProductUidId;

                ExcessMaterialLine.ObjectState = Model.ObjectState.Deleted;
                db.ExcessMaterialLine.Remove(ExcessMaterialLine);

                if (header.Status != (int)StatusConstants.Drafted && header.Status != (int)StatusConstants.Import)
                {
                    header.Status       = (int)StatusConstants.Modified;
                    header.ModifiedDate = DateTime.Now;
                    header.ModifiedBy   = User.Identity.Name;
                    header.ObjectState  = Model.ObjectState.Modified;
                    db.ExcessMaterialHeader.Add(header);
                }


                //if (ProdUid != null && ProdUid > 0)
                //{
                //    ProductUidDetail ProductUidDetail = new ProductUidService(_unitOfWork).FGetProductUidLastValues((int)ProdUid, "ExcessMaterial Head-" + vm.ExcessMaterialHeaderId.ToString());

                //    ProductUid ProductUid = new ProductUidService(_unitOfWork).Find((int)ProdUid);

                //    ProductUid.LastTransactionDocDate = ProductUidDetail.LastTransactionDocDate;
                //    ProductUid.LastTransactionDocId = ProductUidDetail.LastTransactionDocId;
                //    ProductUid.LastTransactionDocNo = ProductUidDetail.LastTransactionDocNo;
                //    ProductUid.LastTransactionDocTypeId = ProductUidDetail.LastTransactionDocTypeId;
                //    ProductUid.LastTransactionPersonId = ProductUidDetail.LastTransactionPersonId;
                //    ProductUid.CurrenctGodownId = ProductUidDetail.CurrenctGodownId;
                //    ProductUid.CurrenctProcessId = ProductUidDetail.CurrenctProcessId;
                //    ProductUid.ObjectState = Model.ObjectState.Modified;
                //    db.ProductUid.Add(ProductUid);
                //}


                XElement Modifications = new ModificationsCheckService().CheckChanges(LogList);

                try
                {
                    ExcessMaterialDocEvents.onLineDeleteEvent(this, new StockEventArgs(ExcessMaterialLine.ExcessMaterialHeaderId, ExcessMaterialLine.ExcessMaterialLineId), ref db);
                }
                catch (Exception ex)
                {
                    string message = _exception.HandleException(ex);
                    TempData["CSEXCL"] += message;
                    EventException      = true;
                }

                try
                {
                    if (EventException)
                    {
                        throw new Exception();
                    }
                    db.SaveChanges();
                }

                catch (Exception ex)
                {
                    string message = _exception.HandleException(ex);
                    TempData["CSEXCL"] += message;
                    ViewBag.LineMode    = "Delete";
                    return(PartialView("_Create", vm));
                }

                try
                {
                    ExcessMaterialDocEvents.afterLineDeleteEvent(this, new StockEventArgs(ExcessMaterialLine.ExcessMaterialHeaderId, ExcessMaterialLine.ExcessMaterialLineId), ref db);
                }
                catch (Exception ex)
                {
                    string message = _exception.HandleException(ex);
                    TempData["CSEXC"] += message;
                }

                LogActivity.LogActivityDetail(LogVm.Map(new ActiivtyLogViewModel
                {
                    DocTypeId       = header.DocTypeId,
                    DocId           = header.ExcessMaterialHeaderId,
                    DocLineId       = ExcessMaterialLine.ExcessMaterialLineId,
                    ActivityType    = (int)ActivityTypeContants.Deleted,
                    DocNo           = header.DocNo,
                    xEModifications = Modifications,
                    DocDate         = header.DocDate,
                    DocStatus       = header.Status,
                }));
            }

            return(Json(new { success = true }));
        }
        public ActionResult _CreatePost(ExcessMaterialLineViewModel svm)
        {
            ExcessMaterialHeader temp = new ExcessMaterialHeaderService(_unitOfWork, db).Find(svm.ExcessMaterialHeaderId);
            ExcessMaterialLine   s    = Mapper.Map <ExcessMaterialLineViewModel, ExcessMaterialLine>(svm);

            bool BeforeSave = true;

            try
            {
                if (svm.ExcessMaterialLineId <= 0)
                {
                    BeforeSave = ExcessMaterialDocEvents.beforeLineSaveEvent(this, new StockEventArgs(svm.ExcessMaterialHeaderId, EventModeConstants.Add), ref db);
                }
                else
                {
                    BeforeSave = ExcessMaterialDocEvents.beforeLineSaveEvent(this, new StockEventArgs(svm.ExcessMaterialHeaderId, EventModeConstants.Edit), ref db);
                }
            }
            catch (Exception ex)
            {
                string message = _exception.HandleException(ex);
                TempData["CSEXCL"] += message;
                EventException      = true;
            }

            if (!BeforeSave)
            {
                ModelState.AddModelError("", "Validation failed before save.");
            }

            if (svm.ProductId <= 0)
            {
                ModelState.AddModelError("ProductId", "The Product field is required");
            }

            if (svm.ExcessMaterialLineId <= 0)
            {
                ViewBag.LineMode = "Create";
            }
            else
            {
                ViewBag.LineMode = "Edit";
            }


            if (ModelState.IsValid && BeforeSave && !EventException)
            {
                if (svm.ExcessMaterialLineId <= 0)
                {
                    s.CreatedDate  = DateTime.Now;
                    s.ModifiedDate = DateTime.Now;
                    s.CreatedBy    = User.Identity.Name;
                    s.ModifiedBy   = User.Identity.Name;
                    s.ProductUidId = svm.ProductUidId;
                    s.Sr           = _ExcessMaterialLineService.GetMaxSr(s.ExcessMaterialHeaderId);
                    s.ObjectState  = Model.ObjectState.Added;
                    db.ExcessMaterialLine.Add(s);

                    if (temp.Status != (int)StatusConstants.Drafted && temp.Status != (int)StatusConstants.Import)
                    {
                        temp.Status       = (int)StatusConstants.Modified;
                        temp.ModifiedBy   = User.Identity.Name;
                        temp.ModifiedDate = DateTime.Now;
                        db.ExcessMaterialHeader.Add(temp);
                    }

                    try
                    {
                        ExcessMaterialDocEvents.onLineSaveEvent(this, new StockEventArgs(s.ExcessMaterialHeaderId, s.ExcessMaterialLineId, EventModeConstants.Add), ref db);
                    }
                    catch (Exception ex)
                    {
                        string message = _exception.HandleException(ex);
                        TempData["CSEXCL"] += message;
                        EventException      = true;
                    }

                    try
                    {
                        if (EventException)
                        {
                            throw new Exception();
                        }

                        db.SaveChanges();
                    }

                    catch (Exception ex)
                    {
                        string message = _exception.HandleException(ex);
                        TempData["CSEXCL"] += message;
                        PrepareViewBag(svm);
                        return(PartialView("_Create", svm));
                    }

                    LogActivity.LogActivityDetail(LogVm.Map(new ActiivtyLogViewModel
                    {
                        DocTypeId    = temp.DocTypeId,
                        DocId        = temp.ExcessMaterialHeaderId,
                        DocLineId    = s.ExcessMaterialLineId,
                        ActivityType = (int)ActivityTypeContants.Added,
                        DocNo        = temp.DocNo,
                        DocDate      = temp.DocDate,
                        DocStatus    = temp.Status,
                    }));

                    try
                    {
                        ExcessMaterialDocEvents.afterLineSaveEvent(this, new StockEventArgs(s.ExcessMaterialHeaderId, s.ExcessMaterialLineId, EventModeConstants.Add), ref db);
                    }
                    catch (Exception ex)
                    {
                        string message = _exception.HandleException(ex);
                        TempData["CSEXCL"] += message;
                    }

                    return(RedirectToAction("_Create", new { id = svm.ExcessMaterialHeaderId }));
                }


                else
                {
                    List <LogTypeViewModel> LogList = new List <LogTypeViewModel>();
                    int status = temp.Status;
                    ExcessMaterialLine templine = _ExcessMaterialLineService.Find(s.ExcessMaterialLineId);

                    ExcessMaterialLine ExRec = new ExcessMaterialLine();
                    ExRec = Mapper.Map <ExcessMaterialLine>(templine);

                    templine.ProductId    = s.ProductId;
                    templine.ProductUidId = s.ProductUidId;
                    templine.Dimension1Id = s.Dimension1Id;
                    templine.Dimension2Id = s.Dimension2Id;
                    templine.Dimension3Id = s.Dimension3Id;
                    templine.Dimension4Id = s.Dimension4Id;
                    templine.LotNo        = s.LotNo;
                    templine.ProcessId    = s.ProcessId;
                    templine.ProductUidId = s.ProductUidId;
                    templine.Remark       = s.Remark;
                    templine.Qty          = s.Qty;
                    templine.Remark       = s.Remark;

                    templine.ModifiedDate = DateTime.Now;
                    templine.ModifiedBy   = User.Identity.Name;
                    templine.ObjectState  = Model.ObjectState.Modified;
                    db.ExcessMaterialLine.Add(templine);

                    if (temp.Status != (int)StatusConstants.Drafted && temp.Status != (int)StatusConstants.Import)
                    {
                        temp.Status       = (int)StatusConstants.Modified;
                        temp.ModifiedBy   = User.Identity.Name;
                        temp.ModifiedDate = DateTime.Now;
                        temp.ObjectState  = Model.ObjectState.Modified;
                    }
                    db.ExcessMaterialHeader.Add(temp);


                    LogList.Add(new LogTypeViewModel
                    {
                        ExObj = ExRec,
                        Obj   = templine,
                    });


                    XElement Modifications = new ModificationsCheckService().CheckChanges(LogList);

                    try
                    {
                        ExcessMaterialDocEvents.onLineSaveEvent(this, new StockEventArgs(s.ExcessMaterialHeaderId, templine.ExcessMaterialLineId, EventModeConstants.Edit), ref db);
                    }
                    catch (Exception ex)
                    {
                        string message = _exception.HandleException(ex);
                        TempData["CSEXCL"] += message;
                        EventException      = true;
                    }

                    try
                    {
                        if (EventException)
                        {
                            throw new Exception();
                        }
                        db.SaveChanges();
                    }

                    catch (Exception ex)
                    {
                        string message = _exception.HandleException(ex);
                        TempData["CSEXCL"] += message;
                        PrepareViewBag(svm);
                        return(PartialView("_Create", svm));
                    }

                    try
                    {
                        ExcessMaterialDocEvents.afterLineSaveEvent(this, new StockEventArgs(s.ExcessMaterialHeaderId, templine.ExcessMaterialLineId, EventModeConstants.Edit), ref db);
                    }
                    catch (Exception ex)
                    {
                        string message = _exception.HandleException(ex);
                        TempData["CSEXC"] += message;
                    }

                    //Saving the Activity Log

                    LogActivity.LogActivityDetail(LogVm.Map(new ActiivtyLogViewModel
                    {
                        DocTypeId       = temp.DocTypeId,
                        DocId           = templine.ExcessMaterialHeaderId,
                        DocLineId       = templine.ExcessMaterialLineId,
                        ActivityType    = (int)ActivityTypeContants.Modified,
                        DocNo           = temp.DocNo,
                        xEModifications = Modifications,
                        DocDate         = temp.DocDate,
                        DocStatus       = temp.Status,
                    }));

                    //End of Saving the Activity Log

                    return(Json(new { success = true }));
                }
            }
            PrepareViewBag(svm);
            return(PartialView("_Create", svm));
        }