Example #1
0
        public ActionResult Create(JobWorkerViewModel JobWorkerVm)
        {
            string[] ProcessIdArr;
            if (JobWorkerVm.LedgerAccountGroupId == 0)
            {
                PrepareViewBag();
                return(View(JobWorkerVm).Danger("Account Group field is required"));
            }

            if (_PersonService.CheckDuplicate(JobWorkerVm.Name, JobWorkerVm.Suffix, JobWorkerVm.PersonId) == true)
            {
                PrepareViewBag();
                return(View(JobWorkerVm).Danger("Combination of name and sufix is duplicate"));
            }


            if (ModelState.IsValid)
            {
                if (JobWorkerVm.PersonId == 0)
                {
                    Person         person         = Mapper.Map <JobWorkerViewModel, Person>(JobWorkerVm);
                    BusinessEntity businessentity = Mapper.Map <JobWorkerViewModel, BusinessEntity>(JobWorkerVm);
                    JobWorker      JobWorker      = Mapper.Map <JobWorkerViewModel, JobWorker>(JobWorkerVm);
                    PersonAddress  personaddress  = Mapper.Map <JobWorkerViewModel, PersonAddress>(JobWorkerVm);
                    LedgerAccount  account        = Mapper.Map <JobWorkerViewModel, LedgerAccount>(JobWorkerVm);


                    person.CreatedDate  = DateTime.Now;
                    person.ModifiedDate = DateTime.Now;
                    person.CreatedBy    = User.Identity.Name;
                    person.ModifiedBy   = User.Identity.Name;
                    person.ObjectState  = Model.ObjectState.Added;
                    new PersonService(_unitOfWork).Create(person);


                    string Divisions = JobWorkerVm.DivisionIds;
                    if (Divisions != null)
                    {
                        Divisions = "|" + Divisions.Replace(",", "|,|") + "|";
                    }

                    businessentity.DivisionIds = Divisions;

                    string Sites = JobWorkerVm.SiteIds;
                    if (Sites != null)
                    {
                        Sites = "|" + Sites.Replace(",", "|,|") + "|";
                    }

                    businessentity.SiteIds = Sites;

                    _BusinessEntityService.Create(businessentity);
                    _JobWorkerService.Create(JobWorker);


                    personaddress.AddressType  = AddressTypeConstants.Work;
                    personaddress.CreatedDate  = DateTime.Now;
                    personaddress.ModifiedDate = DateTime.Now;
                    personaddress.CreatedBy    = User.Identity.Name;
                    personaddress.ModifiedBy   = User.Identity.Name;
                    personaddress.ObjectState  = Model.ObjectState.Added;
                    _PersonAddressService.Create(personaddress);


                    account.LedgerAccountName   = person.Name;
                    account.LedgerAccountSuffix = person.Suffix;
                    account.CreatedDate         = DateTime.Now;
                    account.ModifiedDate        = DateTime.Now;
                    account.CreatedBy           = User.Identity.Name;
                    account.ModifiedBy          = User.Identity.Name;
                    account.ObjectState         = Model.ObjectState.Added;
                    _AccountService.Create(account);

                    //if (JobWorkerVm.ProcessIds != null &&  JobWorkerVm.ProcessIds != "")
                    //{
                    //    ProcessIdArr = JobWorkerVm.ProcessIds.Split(new Char[] { ',' });

                    //    for (int i = 0; i <= ProcessIdArr.Length - 1; i++)
                    //    {
                    //        PersonProcess personprocess = new PersonProcess();
                    //        personprocess.PersonId = JobWorker.PersonID;
                    //        personprocess.ProcessId = Convert.ToInt32(ProcessIdArr[i]);
                    //        personprocess.CreatedDate = DateTime.Now;
                    //        personprocess.ModifiedDate = DateTime.Now;
                    //        personprocess.CreatedBy = User.Identity.Name;
                    //        personprocess.ModifiedBy = User.Identity.Name;
                    //        personprocess.ObjectState = Model.ObjectState.Added;
                    //        _PersonProcessService.Create(personprocess);
                    //    }
                    //}

                    if (JobWorkerVm.PanNo != "" && JobWorkerVm.PanNo != null)
                    {
                        PersonRegistration personregistration = new PersonRegistration();
                        personregistration.RegistrationType = PersonRegistrationType.PANNo;
                        personregistration.RegistrationNo   = JobWorkerVm.PanNo;
                        personregistration.CreatedDate      = DateTime.Now;
                        personregistration.ModifiedDate     = DateTime.Now;
                        personregistration.CreatedBy        = User.Identity.Name;
                        personregistration.ModifiedBy       = User.Identity.Name;
                        personregistration.ObjectState      = Model.ObjectState.Added;
                        _PersonRegistrationService.Create(personregistration);
                    }

                    try
                    {
                        _unitOfWork.Save();
                    }

                    catch (Exception ex)
                    {
                        string message = _exception.HandleException(ex);
                        ModelState.AddModelError("", message);
                        PrepareViewBag();
                        return(View(JobWorkerVm));
                    }



                    #region

                    //Saving Images if any uploaded after UnitOfWorkSave

                    if (Request.Files[0] != null && Request.Files[0].ContentLength > 0)
                    {
                        //For checking the first time if the folder exists or not-----------------------------
                        string uploadfolder;
                        int    MaxLimit;
                        int.TryParse(ConfigurationManager.AppSettings["MaxFileUploadLimit"], out MaxLimit);
                        var x = (from iid in db.Counter
                                 select iid).FirstOrDefault();
                        if (x == null)
                        {
                            uploadfolder = System.Guid.NewGuid().ToString();
                            Counter img = new Counter();
                            img.ImageFolderName = uploadfolder;
                            img.ModifiedBy      = User.Identity.Name;
                            img.CreatedBy       = User.Identity.Name;
                            img.ModifiedDate    = DateTime.Now;
                            img.CreatedDate     = DateTime.Now;
                            new CounterService(_unitOfWork).Create(img);
                            _unitOfWork.Save();
                        }

                        else
                        {
                            uploadfolder = x.ImageFolderName;
                        }


                        //For checking if the image contents length is greater than 100 then create a new folder------------------------------------

                        if (!Directory.Exists(System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder)))
                        {
                            Directory.CreateDirectory(System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder));
                        }

                        int count = Directory.GetFiles(System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder)).Length;

                        if (count >= MaxLimit)
                        {
                            uploadfolder = System.Guid.NewGuid().ToString();
                            var u = new CounterService(_unitOfWork).Find(x.CounterId);
                            u.ImageFolderName = uploadfolder;
                            new CounterService(_unitOfWork).Update(u);
                            _unitOfWork.Save();
                        }


                        //Saving Thumbnails images:
                        Dictionary <string, string> versions = new Dictionary <string, string>();

                        //Define the versions to generate
                        versions.Add("_thumb", "maxwidth=100&maxheight=100");  //Crop to square thumbnail
                        versions.Add("_medium", "maxwidth=200&maxheight=200"); //Fit inside 400x400 area, jpeg

                        string temp2    = "";
                        string filename = System.Guid.NewGuid().ToString();
                        foreach (string filekey in System.Web.HttpContext.Current.Request.Files.Keys)
                        {
                            HttpPostedFile pfile = System.Web.HttpContext.Current.Request.Files[filekey];
                            if (pfile.ContentLength <= 0)
                            {
                                continue;                           //Skip unused file controls.
                            }
                            temp2 = Path.GetExtension(pfile.FileName);

                            string uploadFolder = System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder);
                            if (!Directory.Exists(uploadFolder))
                            {
                                Directory.CreateDirectory(uploadFolder);
                            }

                            string filecontent = Path.Combine(uploadFolder, JobWorkerVm.Name + "_" + filename);

                            //pfile.SaveAs(filecontent);
                            ImageBuilder.Current.Build(new ImageJob(pfile, filecontent, new Instructions(), false, true));


                            //Generate each version
                            foreach (string suffix in versions.Keys)
                            {
                                if (suffix == "_thumb")
                                {
                                    string tuploadFolder = System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder + "/Thumbs");
                                    if (!Directory.Exists(tuploadFolder))
                                    {
                                        Directory.CreateDirectory(tuploadFolder);
                                    }

                                    //Generate a filename (GUIDs are best).
                                    string tfileName = Path.Combine(tuploadFolder, JobWorkerVm.Name + "_" + filename);

                                    //Let the image builder add the correct extension based on the output file type
                                    //fileName = ImageBuilder.Current.Build(file, fileName, new ResizeSettings(versions[suffix]), false, true);
                                    ImageBuilder.Current.Build(new ImageJob(pfile, tfileName, new Instructions(versions[suffix]), false, true));
                                }
                                else if (suffix == "_medium")
                                {
                                    string tuploadFolder = System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder + "/Medium");
                                    if (!Directory.Exists(tuploadFolder))
                                    {
                                        Directory.CreateDirectory(tuploadFolder);
                                    }

                                    //Generate a filename (GUIDs are best).
                                    string tfileName = Path.Combine(tuploadFolder, JobWorkerVm.Name + "_" + filename);

                                    //Let the image builder add the correct extension based on the output file type
                                    //fileName = ImageBuilder.Current.Build(file, fileName, new ResizeSettings(versions[suffix]), false, true);
                                    ImageBuilder.Current.Build(new ImageJob(pfile, tfileName, new Instructions(versions[suffix]), false, true));
                                }
                            }

                            //var tempsave = _FinishedProductService.Find(pt.ProductId);

                            person.ImageFileName   = JobWorkerVm.Name + "_" + filename + temp2;
                            person.ImageFolderName = uploadfolder;
                            person.ObjectState     = Model.ObjectState.Modified;
                            _PersonService.Update(person);
                            _unitOfWork.Save();
                        }
                    }

                    #endregion



                    //return RedirectToAction("Create").Success("Data saved successfully");
                    return(RedirectToAction("Edit", new { id = JobWorker.PersonID }).Success("Data saved Successfully"));
                }
                else
                {
                    List <LogTypeViewModel> LogList = new List <LogTypeViewModel>();


                    //string tempredirect = (Request["Redirect"].ToString());
                    Person             person         = Mapper.Map <JobWorkerViewModel, Person>(JobWorkerVm);
                    BusinessEntity     businessentity = Mapper.Map <JobWorkerViewModel, BusinessEntity>(JobWorkerVm);
                    JobWorker          JobWorker      = Mapper.Map <JobWorkerViewModel, JobWorker>(JobWorkerVm);
                    PersonAddress      personaddress  = _PersonAddressService.Find(JobWorkerVm.PersonAddressID);
                    LedgerAccount      account        = _AccountService.Find(JobWorkerVm.AccountId);
                    PersonRegistration PersonPan      = _PersonRegistrationService.Find(JobWorkerVm.PersonRegistrationPanNoID);


                    PersonAddress ExRec = new PersonAddress();
                    ExRec = Mapper.Map <PersonAddress>(personaddress);

                    LedgerAccount ExRecLA = new LedgerAccount();
                    ExRecLA = Mapper.Map <LedgerAccount>(account);

                    PersonRegistration ExRecP = new PersonRegistration();
                    ExRecP = Mapper.Map <PersonRegistration>(PersonPan);


                    StringBuilder logstring = new StringBuilder();

                    person.ModifiedDate = DateTime.Now;
                    person.ModifiedBy   = User.Identity.Name;
                    new PersonService(_unitOfWork).Update(person);

                    string Divisions = JobWorkerVm.DivisionIds;
                    if (Divisions != null)
                    {
                        Divisions = "|" + Divisions.Replace(",", "|,|") + "|";
                    }

                    businessentity.DivisionIds = Divisions;

                    string Sites = JobWorkerVm.SiteIds;
                    if (Sites != null)
                    {
                        Sites = "|" + Sites.Replace(",", "|,|") + "|";
                    }

                    businessentity.SiteIds = Sites;

                    _BusinessEntityService.Update(businessentity);
                    _JobWorkerService.Update(JobWorker);

                    personaddress.Address      = JobWorkerVm.Address;
                    personaddress.CityId       = JobWorkerVm.CityId;
                    personaddress.Zipcode      = JobWorkerVm.Zipcode;
                    personaddress.ModifiedDate = DateTime.Now;
                    personaddress.ModifiedBy   = User.Identity.Name;
                    personaddress.ObjectState  = Model.ObjectState.Modified;
                    _PersonAddressService.Update(personaddress);

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


                    account.LedgerAccountName    = person.Name;
                    account.LedgerAccountSuffix  = person.Suffix;
                    account.LedgerAccountGroupId = JobWorkerVm.LedgerAccountGroupId;
                    account.ModifiedDate         = DateTime.Now;
                    account.ModifiedBy           = User.Identity.Name;
                    _AccountService.Update(account);

                    LogList.Add(new LogTypeViewModel
                    {
                        ExObj = ExRecLA,
                        Obj   = account,
                    });

                    //if (JobWorkerVm.ProcessIds != "" && JobWorkerVm.ProcessIds != null)
                    //{

                    //    IEnumerable<PersonProcess> personprocesslist = _PersonProcessService.GetPersonProcessList(JobWorkerVm.PersonId);

                    //    foreach (PersonProcess item in personprocesslist)
                    //    {
                    //        new PersonProcessService(_unitOfWork).Delete(item.PersonProcessId);
                    //    }



                    //    ProcessIdArr = JobWorkerVm.ProcessIds.Split(new Char[] { ',' });

                    //    for (int i = 0; i <= ProcessIdArr.Length - 1; i++)
                    //    {
                    //        PersonProcess personprocess = new PersonProcess();
                    //        personprocess.PersonId = JobWorker.PersonID;
                    //        personprocess.ProcessId = Convert.ToInt32(ProcessIdArr[i]);
                    //        personprocess.CreatedDate = DateTime.Now;
                    //        personprocess.ModifiedDate = DateTime.Now;
                    //        personprocess.CreatedBy = User.Identity.Name;
                    //        personprocess.ModifiedBy = User.Identity.Name;
                    //        personprocess.ObjectState = Model.ObjectState.Added;
                    //        _PersonProcessService.Create(personprocess);
                    //    }
                    //}

                    if (JobWorkerVm.PanNo != null && JobWorkerVm.PanNo != "")
                    {
                        if (PersonPan != null)
                        {
                            PersonPan.RegistrationNo = JobWorkerVm.PanNo;
                            _PersonRegistrationService.Update(PersonPan);

                            LogList.Add(new LogTypeViewModel
                            {
                                ExObj = ExRecP,
                                Obj   = PersonPan,
                            });
                        }
                        else
                        {
                            PersonRegistration personregistration = new PersonRegistration();
                            personregistration.PersonId         = JobWorkerVm.PersonId;
                            personregistration.RegistrationType = PersonRegistrationType.PANNo;
                            personregistration.RegistrationNo   = JobWorkerVm.PanNo;
                            personregistration.CreatedDate      = DateTime.Now;
                            personregistration.ModifiedDate     = DateTime.Now;
                            personregistration.CreatedBy        = User.Identity.Name;
                            personregistration.ModifiedBy       = User.Identity.Name;
                            personregistration.ObjectState      = Model.ObjectState.Added;
                            _PersonRegistrationService.Create(personregistration);
                        }
                    }


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



                    try
                    {
                        _unitOfWork.Save();
                    }

                    catch (Exception ex)
                    {
                        string message = _exception.HandleException(ex);
                        ModelState.AddModelError("", message);
                        PrepareViewBag();
                        return(View("Create", JobWorkerVm));
                    }

                    LogActivity.LogActivityDetail(new ActiivtyLogViewModel
                    {
                        DocTypeId       = new DocumentTypeService(_unitOfWork).FindByName(MasterDocCategoryConstants.JobWorker).DocumentTypeId,
                        DocId           = JobWorkerVm.PersonId,
                        ActivityType    = (int)ActivityTypeContants.Modified,
                        DocNo           = JobWorkerVm.Name,
                        xEModifications = Modifications,
                    });
                    //End of Saving ActivityLog


                    #region

                    //Saving Image if file is uploaded
                    if (Request.Files[0] != null && Request.Files[0].ContentLength > 0)
                    {
                        string uploadfolder = JobWorkerVm.ImageFolderName;
                        string tempfilename = JobWorkerVm.ImageFileName;
                        if (uploadfolder == null)
                        {
                            var x = (from iid in db.Counter
                                     select iid).FirstOrDefault();
                            if (x == null)
                            {
                                uploadfolder = System.Guid.NewGuid().ToString();
                                Counter img = new Counter();
                                img.ImageFolderName = uploadfolder;
                                img.ModifiedBy      = User.Identity.Name;
                                img.CreatedBy       = User.Identity.Name;
                                img.ModifiedDate    = DateTime.Now;
                                img.CreatedDate     = DateTime.Now;
                                new CounterService(_unitOfWork).Create(img);
                                _unitOfWork.Save();
                            }
                            else
                            {
                                uploadfolder = x.ImageFolderName;
                            }
                        }
                        //Deleting Existing Images

                        var xtemp = System.Web.HttpContext.Current.Server.MapPath("~/Uploads/" + uploadfolder + "/" + tempfilename);
                        if (System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/" + uploadfolder + "/" + tempfilename)))
                        {
                            System.IO.File.Delete(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/" + uploadfolder + "/" + tempfilename));
                        }

                        //Deleting Thumbnail Image:

                        if (System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/" + uploadfolder + "/Thumbs/" + tempfilename)))
                        {
                            System.IO.File.Delete(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/" + uploadfolder + "/Thumbs/" + tempfilename));
                        }

                        //Deleting Medium Image:
                        if (System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/" + uploadfolder + "/Medium/" + tempfilename)))
                        {
                            System.IO.File.Delete(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/" + uploadfolder + "/Medium/" + tempfilename));
                        }

                        //Saving Thumbnails images:
                        Dictionary <string, string> versions = new Dictionary <string, string>();

                        //Define the versions to generate
                        versions.Add("_thumb", "maxwidth=100&maxheight=100");  //Crop to square thumbnail
                        versions.Add("_medium", "maxwidth=200&maxheight=200"); //Fit inside 400x400 area, jpeg

                        string temp2    = "";
                        string filename = System.Guid.NewGuid().ToString();
                        foreach (string filekey in System.Web.HttpContext.Current.Request.Files.Keys)
                        {
                            HttpPostedFile pfile = System.Web.HttpContext.Current.Request.Files[filekey];
                            if (pfile.ContentLength <= 0)
                            {
                                continue;                           //Skip unused file controls.
                            }
                            temp2 = Path.GetExtension(pfile.FileName);

                            string uploadFolder = System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder);
                            if (!Directory.Exists(uploadFolder))
                            {
                                Directory.CreateDirectory(uploadFolder);
                            }

                            string filecontent = Path.Combine(uploadFolder, JobWorkerVm.Name + "_" + filename);

                            //pfile.SaveAs(filecontent);

                            ImageBuilder.Current.Build(new ImageJob(pfile, filecontent, new Instructions(), false, true));

                            //Generate each version
                            foreach (string suffix in versions.Keys)
                            {
                                if (suffix == "_thumb")
                                {
                                    string tuploadFolder = System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder + "/Thumbs");
                                    if (!Directory.Exists(tuploadFolder))
                                    {
                                        Directory.CreateDirectory(tuploadFolder);
                                    }

                                    //Generate a filename (GUIDs are best).
                                    string tfileName = Path.Combine(tuploadFolder, JobWorkerVm.Name + "_" + filename);

                                    //Let the image builder add the correct extension based on the output file type
                                    //fileName = ImageBuilder.Current.Build(file, fileName, new ResizeSettings(versions[suffix]), false, true);
                                    ImageBuilder.Current.Build(new ImageJob(pfile, tfileName, new Instructions(versions[suffix]), false, true));
                                }
                                else if (suffix == "_medium")
                                {
                                    string tuploadFolder = System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder + "/Medium");
                                    if (!Directory.Exists(tuploadFolder))
                                    {
                                        Directory.CreateDirectory(tuploadFolder);
                                    }

                                    //Generate a filename (GUIDs are best).
                                    string tfileName = Path.Combine(tuploadFolder, JobWorkerVm.Name + "_" + filename);

                                    //Let the image builder add the correct extension based on the output file type
                                    //fileName = ImageBuilder.Current.Build(file, fileName, new ResizeSettings(versions[suffix]), false, true);
                                    ImageBuilder.Current.Build(new ImageJob(pfile, tfileName, new Instructions(versions[suffix]), false, true));
                                }
                            }
                        }
                        var temsave = _PersonService.Find(person.PersonID);
                        temsave.ImageFileName   = temsave.Name + "_" + filename + temp2;
                        temsave.ImageFolderName = uploadfolder;
                        _PersonService.Update(temsave);
                        _unitOfWork.Save();
                    }

                    #endregion



                    return(RedirectToAction("Index").Success("Data saved successfully"));
                }
            }
            PrepareViewBag();
            return(View(JobWorkerVm));
        }
Example #2
0
        public ActionResult Create(AgentViewModel AgentVm)
        {
            if (AgentVm.LedgerAccountGroupId == 0)
            {
                PrepareViewBag();
                return(View(AgentVm).Danger("Account Group field is required"));
            }

            if (_PersonService.CheckDuplicate(AgentVm.Name, AgentVm.Suffix, AgentVm.PersonId) == true)
            {
                PrepareViewBag();
                return(View(AgentVm).Danger("Combination of name and sufix is duplicate"));
            }


            if (ModelState.IsValid)
            {
                if (AgentVm.PersonId == 0)
                {
                    Person         person         = Mapper.Map <AgentViewModel, Person>(AgentVm);
                    BusinessEntity businessentity = Mapper.Map <AgentViewModel, BusinessEntity>(AgentVm);
                    Agent          Agent          = Mapper.Map <AgentViewModel, Agent>(AgentVm);
                    PersonAddress  personaddress  = Mapper.Map <AgentViewModel, PersonAddress>(AgentVm);
                    LedgerAccount  account        = Mapper.Map <AgentViewModel, LedgerAccount>(AgentVm);

                    person.CreatedDate  = DateTime.Now;
                    person.ModifiedDate = DateTime.Now;
                    person.CreatedBy    = User.Identity.Name;
                    person.ModifiedBy   = User.Identity.Name;
                    person.ObjectState  = Model.ObjectState.Added;
                    new PersonService(_unitOfWork).Create(person);

                    _BusinessEntityService.Create(businessentity);
                    _AgentService.Create(Agent);

                    personaddress.AddressType  = AddressTypeConstants.Work;
                    personaddress.CreatedDate  = DateTime.Now;
                    personaddress.ModifiedDate = DateTime.Now;
                    personaddress.CreatedBy    = User.Identity.Name;
                    personaddress.ModifiedBy   = User.Identity.Name;
                    personaddress.ObjectState  = Model.ObjectState.Added;
                    _PersonAddressService.Create(personaddress);


                    account.LedgerAccountName   = person.Name;
                    account.LedgerAccountSuffix = person.Suffix;
                    account.CreatedDate         = DateTime.Now;
                    account.ModifiedDate        = DateTime.Now;
                    account.CreatedBy           = User.Identity.Name;
                    account.ModifiedBy          = User.Identity.Name;
                    account.ObjectState         = Model.ObjectState.Added;
                    _AccountService.Create(account);


                    try
                    {
                        _unitOfWork.Save();
                    }

                    catch (Exception ex)
                    {
                        string message = _exception.HandleException(ex);
                        ModelState.AddModelError("", message);
                        return(View(AgentVm));
                    }


                    #region

                    //Saving Images if any uploaded after UnitOfWorkSave

                    if (Request.Files[0] != null && Request.Files[0].ContentLength > 0)
                    {
                        //For checking the first time if the folder exists or not-----------------------------
                        string uploadfolder;
                        int    MaxLimit;
                        int.TryParse(ConfigurationManager.AppSettings["MaxFileUploadLimit"], out MaxLimit);
                        var x = (from iid in db.Counter
                                 select iid).FirstOrDefault();
                        if (x == null)
                        {
                            uploadfolder = System.Guid.NewGuid().ToString();
                            Counter img = new Counter();
                            img.ImageFolderName = uploadfolder;
                            img.ModifiedBy      = User.Identity.Name;
                            img.CreatedBy       = User.Identity.Name;
                            img.ModifiedDate    = DateTime.Now;
                            img.CreatedDate     = DateTime.Now;
                            new CounterService(_unitOfWork).Create(img);
                            _unitOfWork.Save();
                        }

                        else
                        {
                            uploadfolder = x.ImageFolderName;
                        }


                        //For checking if the image contents length is greater than 100 then create a new folder------------------------------------

                        if (!Directory.Exists(System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder)))
                        {
                            Directory.CreateDirectory(System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder));
                        }

                        int count = Directory.GetFiles(System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder)).Length;

                        if (count >= MaxLimit)
                        {
                            uploadfolder = System.Guid.NewGuid().ToString();
                            var u = new CounterService(_unitOfWork).Find(x.CounterId);
                            u.ImageFolderName = uploadfolder;
                            new CounterService(_unitOfWork).Update(u);
                            _unitOfWork.Save();
                        }


                        //Saving Thumbnails images:
                        Dictionary <string, string> versions = new Dictionary <string, string>();

                        //Define the versions to generate
                        versions.Add("_thumb", "maxwidth=100&maxheight=100");  //Crop to square thumbnail
                        versions.Add("_medium", "maxwidth=200&maxheight=200"); //Fit inside 400x400 area, jpeg

                        string temp2    = "";
                        string filename = System.Guid.NewGuid().ToString();
                        foreach (string filekey in System.Web.HttpContext.Current.Request.Files.Keys)
                        {
                            HttpPostedFile pfile = System.Web.HttpContext.Current.Request.Files[filekey];
                            if (pfile.ContentLength <= 0)
                            {
                                continue;                           //Skip unused file controls.
                            }
                            temp2 = Path.GetExtension(pfile.FileName);

                            string uploadFolder = System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder);
                            if (!Directory.Exists(uploadFolder))
                            {
                                Directory.CreateDirectory(uploadFolder);
                            }

                            string filecontent = Path.Combine(uploadFolder, AgentVm.Name + "_" + filename);

                            //pfile.SaveAs(filecontent);
                            ImageBuilder.Current.Build(new ImageJob(pfile, filecontent, new Instructions(), false, true));


                            //Generate each version
                            foreach (string suffix in versions.Keys)
                            {
                                if (suffix == "_thumb")
                                {
                                    string tuploadFolder = System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder + "/Thumbs");
                                    if (!Directory.Exists(tuploadFolder))
                                    {
                                        Directory.CreateDirectory(tuploadFolder);
                                    }

                                    //Generate a filename (GUIDs are best).
                                    string tfileName = Path.Combine(tuploadFolder, AgentVm.Name + "_" + filename);

                                    //Let the image builder add the correct extension based on the output file type
                                    //fileName = ImageBuilder.Current.Build(file, fileName, new ResizeSettings(versions[suffix]), false, true);
                                    ImageBuilder.Current.Build(new ImageJob(pfile, tfileName, new Instructions(versions[suffix]), false, true));
                                }
                                else if (suffix == "_medium")
                                {
                                    string tuploadFolder = System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder + "/Medium");
                                    if (!Directory.Exists(tuploadFolder))
                                    {
                                        Directory.CreateDirectory(tuploadFolder);
                                    }

                                    //Generate a filename (GUIDs are best).
                                    string tfileName = Path.Combine(tuploadFolder, AgentVm.Name + "_" + filename);

                                    //Let the image builder add the correct extension based on the output file type
                                    //fileName = ImageBuilder.Current.Build(file, fileName, new ResizeSettings(versions[suffix]), false, true);
                                    ImageBuilder.Current.Build(new ImageJob(pfile, tfileName, new Instructions(versions[suffix]), false, true));
                                }
                            }

                            //var tempsave = _FinishedProductService.Find(pt.ProductId);

                            person.ImageFileName   = AgentVm.Name + "_" + filename + temp2;
                            person.ImageFolderName = uploadfolder;
                            person.ObjectState     = Model.ObjectState.Modified;
                            _PersonService.Update(person);
                            _unitOfWork.Save();
                        }
                    }

                    #endregion



                    //return RedirectToAction("Create").Success("Data saved successfully");
                    return(RedirectToAction("Edit", new { id = person.PersonID }).Success("Data saved Successfully"));
                }
                else
                {
                    //string tempredirect = (Request["Redirect"].ToString());
                    Person         person         = Mapper.Map <AgentViewModel, Person>(AgentVm);
                    BusinessEntity businessentity = Mapper.Map <AgentViewModel, BusinessEntity>(AgentVm);
                    Agent          Agent          = Mapper.Map <AgentViewModel, Agent>(AgentVm);
                    PersonAddress  personaddress  = _PersonAddressService.Find(AgentVm.PersonAddressID);
                    LedgerAccount  account        = _AccountService.Find(AgentVm.AccountId);

                    StringBuilder logstring = new StringBuilder();

                    person.ModifiedDate = DateTime.Now;
                    person.ModifiedBy   = User.Identity.Name;
                    new PersonService(_unitOfWork).Update(person);


                    _BusinessEntityService.Update(businessentity);
                    _AgentService.Update(Agent);

                    personaddress.Address      = AgentVm.Address;
                    personaddress.CityId       = AgentVm.CityId;
                    personaddress.Zipcode      = AgentVm.Zipcode;
                    personaddress.ModifiedDate = DateTime.Now;
                    personaddress.ModifiedBy   = User.Identity.Name;
                    personaddress.ObjectState  = Model.ObjectState.Modified;
                    _PersonAddressService.Update(personaddress);

                    account.LedgerAccountName   = person.Name;
                    account.LedgerAccountSuffix = person.Suffix;
                    account.ModifiedDate        = DateTime.Now;
                    account.ModifiedBy          = User.Identity.Name;
                    _AccountService.Update(account);

                    ////Saving Activity Log::
                    ActivityLog al = new ActivityLog()
                    {
                        ActivityType = (int)ActivityTypeContants.Modified,
                        DocId        = AgentVm.PersonId,
                        Narration    = logstring.ToString(),
                        CreatedDate  = DateTime.Now,
                        CreatedBy    = User.Identity.Name,
                        //DocTypeId = new DocumentTypeService(_unitOfWork).FindByName(TransactionDocCategoryConstants.ProcessSequence).DocumentTypeId,
                    };
                    new ActivityLogService(_unitOfWork).Create(al);
                    //End of Saving ActivityLog

                    try
                    {
                        _unitOfWork.Save();
                    }

                    catch (Exception ex)
                    {
                        string message = _exception.HandleException(ex);
                        ModelState.AddModelError("", message);
                        return(View("Create", AgentVm));
                    }



                    #region

                    //Saving Image if file is uploaded
                    if (Request.Files[0] != null && Request.Files[0].ContentLength > 0)
                    {
                        string uploadfolder = AgentVm.ImageFolderName;
                        string tempfilename = AgentVm.ImageFileName;
                        if (uploadfolder == null)
                        {
                            var x = (from iid in db.Counter
                                     select iid).FirstOrDefault();
                            if (x == null)
                            {
                                uploadfolder = System.Guid.NewGuid().ToString();
                                Counter img = new Counter();
                                img.ImageFolderName = uploadfolder;
                                img.ModifiedBy      = User.Identity.Name;
                                img.CreatedBy       = User.Identity.Name;
                                img.ModifiedDate    = DateTime.Now;
                                img.CreatedDate     = DateTime.Now;
                                new CounterService(_unitOfWork).Create(img);
                                _unitOfWork.Save();
                            }
                            else
                            {
                                uploadfolder = x.ImageFolderName;
                            }
                        }
                        //Deleting Existing Images
                        //ConfigurationManager.AppSettings["PhysicalRDLCPath"] + uploadfolder + "/" + tempfilename;
                        var xtemp = System.Web.HttpContext.Current.Server.MapPath("~/Uploads/" + uploadfolder + "/" + tempfilename);
                        if (System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/" + uploadfolder + "/" + tempfilename)))
                        {
                            System.IO.File.Delete(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/" + uploadfolder + "/" + tempfilename));
                        }

                        //Deleting Thumbnail Image:

                        if (System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/" + uploadfolder + "/Thumbs/" + tempfilename)))
                        {
                            System.IO.File.Delete(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/" + uploadfolder + "/Thumbs/" + tempfilename));
                        }

                        //Deleting Medium Image:
                        if (System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/" + uploadfolder + "/Medium/" + tempfilename)))
                        {
                            System.IO.File.Delete(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/" + uploadfolder + "/Medium/" + tempfilename));
                        }

                        //Saving Thumbnails images:
                        Dictionary <string, string> versions = new Dictionary <string, string>();

                        //Define the versions to generate
                        versions.Add("_thumb", "maxwidth=100&maxheight=100");  //Crop to square thumbnail
                        versions.Add("_medium", "maxwidth=200&maxheight=200"); //Fit inside 400x400 area, jpeg

                        string temp2    = "";
                        string filename = System.Guid.NewGuid().ToString();
                        foreach (string filekey in System.Web.HttpContext.Current.Request.Files.Keys)
                        {
                            HttpPostedFile pfile = System.Web.HttpContext.Current.Request.Files[filekey];
                            if (pfile.ContentLength <= 0)
                            {
                                continue;                           //Skip unused file controls.
                            }
                            temp2 = Path.GetExtension(pfile.FileName);

                            string uploadFolder = System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder);
                            if (!Directory.Exists(uploadFolder))
                            {
                                Directory.CreateDirectory(uploadFolder);
                            }

                            string filecontent = Path.Combine(uploadFolder, AgentVm.Name + "_" + filename);

                            //pfile.SaveAs(filecontent);

                            ImageBuilder.Current.Build(new ImageJob(pfile, filecontent, new Instructions(), false, true));

                            //Generate each version
                            foreach (string suffix in versions.Keys)
                            {
                                if (suffix == "_thumb")
                                {
                                    string tuploadFolder = System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder + "/Thumbs");
                                    if (!Directory.Exists(tuploadFolder))
                                    {
                                        Directory.CreateDirectory(tuploadFolder);
                                    }

                                    //Generate a filename (GUIDs are best).
                                    string tfileName = Path.Combine(tuploadFolder, AgentVm.Name + "_" + filename);

                                    //Let the image builder add the correct extension based on the output file type
                                    //fileName = ImageBuilder.Current.Build(file, fileName, new ResizeSettings(versions[suffix]), false, true);
                                    ImageBuilder.Current.Build(new ImageJob(pfile, tfileName, new Instructions(versions[suffix]), false, true));
                                }
                                else if (suffix == "_medium")
                                {
                                    string tuploadFolder = System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder + "/Medium");
                                    if (!Directory.Exists(tuploadFolder))
                                    {
                                        Directory.CreateDirectory(tuploadFolder);
                                    }

                                    //Generate a filename (GUIDs are best).
                                    string tfileName = Path.Combine(tuploadFolder, AgentVm.Name + "_" + filename);

                                    //Let the image builder add the correct extension based on the output file type
                                    //fileName = ImageBuilder.Current.Build(file, fileName, new ResizeSettings(versions[suffix]), false, true);
                                    ImageBuilder.Current.Build(new ImageJob(pfile, tfileName, new Instructions(versions[suffix]), false, true));
                                }
                            }
                        }

                        person.ImageFileName   = person.Name + "_" + filename + temp2;
                        person.ImageFolderName = uploadfolder;
                        _PersonService.Update(person);
                        _unitOfWork.Save();
                    }

                    #endregion



                    return(RedirectToAction("Index").Success("Data saved successfully"));
                }
            }
            PrepareViewBag();
            return(View(AgentVm));
        }
        public ActionResult _CreatePost(PersonAddressViewModel svm)
        {
            if (svm.AddressType == null || svm.AddressType == "")
            {
                PrepareViewBag();
                string message = "Address Type is required.";
                ModelState.AddModelError("", message);
                return(PartialView("_Create", svm));
            }

            if (ModelState.IsValid)
            {
                if (svm.PersonAddressId == 0)
                {
                    PersonAddress PersonAddress = new PersonAddress();

                    PersonAddress.PersonId     = svm.PersonId;
                    PersonAddress.AddressType  = svm.AddressType;
                    PersonAddress.Address      = svm.Address;
                    PersonAddress.CityId       = svm.CityId;
                    PersonAddress.Zipcode      = svm.Zipcode;
                    PersonAddress.CreatedDate  = DateTime.Now;
                    PersonAddress.ModifiedDate = DateTime.Now;
                    PersonAddress.CreatedBy    = User.Identity.Name;
                    PersonAddress.ModifiedBy   = User.Identity.Name;
                    PersonAddress.ObjectState  = Model.ObjectState.Added;
                    _PersonAddressService.Create(PersonAddress);


                    try
                    {
                        _unitOfWork.Save();
                    }

                    catch (Exception ex)
                    {
                        string message = _exception.HandleException(ex);
                        PrepareViewBag();
                        ModelState.AddModelError("", message);
                        return(PartialView("_Create", svm));
                    }
                    return(RedirectToAction("_Create", new { id = PersonAddress.PersonId }));
                }
                else
                {
                    PersonAddress PersonAddress = _PersonAddressService.Find(svm.PersonAddressId);

                    PersonAddress.AddressType = svm.AddressType;
                    PersonAddress.Address     = svm.Address;
                    PersonAddress.CityId      = svm.CityId;
                    PersonAddress.Zipcode     = svm.Zipcode;

                    _PersonAddressService.Update(PersonAddress);

                    try
                    {
                        _unitOfWork.Save();
                    }

                    catch (Exception ex)
                    {
                        string message = _exception.HandleException(ex);
                        PrepareViewBag();
                        ModelState.AddModelError("", message);
                        return(PartialView("_Create", svm));
                    }


                    return(Json(new { success = true }));
                }
            }

            PrepareViewBag();
            return(PartialView("_Create", svm));
        }