예제 #1
0
        public async Task <AgentVM> GetAgentListAsync(int pageno, int pagesize, string sterm)
        {
            AgentVM model    = new AgentVM();
            var     parStart = new SqlParameter("@Start", (pageno - 1) * pagesize);
            var     parEnd   = new SqlParameter("@PageSize", pagesize);

            var parSearchTerm = new SqlParameter("@SearchTerm", DBNull.Value);

            if (!(sterm == null || sterm == ""))
            {
                parSearchTerm.Value = sterm;
            }
            // setting stored procedure OUTPUT value
            // This return total number of rows, and avoid two database call for data and total number of rows
            var spOutput = new SqlParameter
            {
                ParameterName = "@TotalCount",
                SqlDbType     = System.Data.SqlDbType.BigInt,
                Direction     = System.Data.ParameterDirection.Output
            };

            model.AgentList = await objDB.Database.SqlQuery <AgentView>("udspAgentList @Start, @PageSize,@SearchTerm, @TotalCount out",
                                                                        parStart, parEnd, parSearchTerm, spOutput).ToListAsync();

            model.TotalRecords = int.Parse(spOutput.Value.ToString());
            return(model);
        }
예제 #2
0
        public ActionResult AddAgent()
        {
            var agentVM = new AgentVM();

            agentVM.Aliases = Alias.All();
            return(View(agentVM));
        }
        public bool UpdateAgent(AgentVM agentVM)
        {
            using (var dbTransaction = unitOfWork.dbContext.Database.BeginTransaction())
            {
                try
                {
                    tblAgent agent = unitOfWork.TblAgentRepository.GetByID(agentVM.AgentID);
                    agent.CompID       = agentVM.CompanyID;
                    agent.AgentName    = agentVM.AgentName;
                    agent.Address1     = agentVM.Address1;
                    agent.Address2     = agentVM.Address2;
                    agent.Address3     = agentVM.Address3;
                    agent.RateValue    = agentVM.RateValue;
                    agent.ModifiedDate = DateTime.Now;
                    agent.ModifiedBy   = agentVM.ModifiedBy;
                    agent.AgentType    = agentVM.AgentType;
                    agent.AgentNIC     = agentVM.AgentNIC;
                    agent.AgentBRNo    = agentVM.AgentBR;
                    agent.AgentCode    = agentVM.AgentCode;
                    unitOfWork.TblAgentRepository.Update(agent);
                    unitOfWork.Save();

                    //Complete the Transaction
                    dbTransaction.Commit();
                    return(true);
                }
                catch (Exception ex)
                {
                    //Roll back the Transaction
                    dbTransaction.Rollback();
                    return(false);
                }
            }
        }
        public IHttpActionResult UpdateAgent([FromBody] JObject data)
        {
            try
            {
                int    agentID   = !string.IsNullOrEmpty(data.SelectToken("agentID").Value <string>()) ? Convert.ToInt32(data.SelectToken("agentID").Value <string>()) : 0;
                int    companyID = !string.IsNullOrEmpty(data.SelectToken("companyID").Value <string>()) ? Convert.ToInt32(data.SelectToken("companyID").Value <string>()) : 0;
                string agentName = !string.IsNullOrEmpty(data.SelectToken("agentName").Value <string>()) ? data.SelectToken("agentName").Value <string>() : string.Empty;
                string address1  = !string.IsNullOrEmpty(data.SelectToken("address1").Value <string>()) ? data.SelectToken("address1").Value <string>() : string.Empty;
                string address2  = !string.IsNullOrEmpty(data.SelectToken("address2").Value <string>()) ? data.SelectToken("address2").Value <string>() : string.Empty;
                string address3  = !string.IsNullOrEmpty(data.SelectToken("address3").Value <string>()) ? data.SelectToken("address3").Value <string>() : string.Empty;
                double rateValue = !string.IsNullOrEmpty(data.SelectToken("rateValue").Value <string>()) ? Convert.ToDouble(data.SelectToken("rateValue").Value <string>()) : 0;
                int    userID    = !string.IsNullOrEmpty(data.SelectToken("userID").Value <string>()) ? Convert.ToInt32(data.SelectToken("userID").Value <string>()) : 0;
                string agentCode = !string.IsNullOrEmpty(data.SelectToken("agentCode").Value <string>()) ? data.SelectToken("agentCode").Value <string>() : string.Empty;
                string agentType = !string.IsNullOrEmpty(data.SelectToken("agentType").Value <string>()) ? data.SelectToken("agentType").Value <string>() : string.Empty;
                string agentNIC  = !string.IsNullOrEmpty(data.SelectToken("agentNIC").Value <string>()) ? data.SelectToken("agentNIC").Value <string>() : string.Empty;
                string agentBR   = !string.IsNullOrEmpty(data.SelectToken("agentBR").Value <string>()) ? data.SelectToken("agentBR").Value <string>() : string.Empty;

                if (!manageAgent.IsAgentAvailable(agentID, agentName))
                {
                    AgentVM agentVM = new AgentVM();
                    agentVM.AgentID    = agentID;
                    agentVM.CompanyID  = companyID;
                    agentVM.AgentName  = agentName;
                    agentVM.Address1   = address1;
                    agentVM.Address2   = address2;
                    agentVM.Address3   = address3;
                    agentVM.RateValue  = rateValue;
                    agentVM.ModifiedBy = userID;
                    agentVM.AgentCode  = agentCode;
                    agentVM.AgentNIC   = agentNIC;
                    agentVM.AgentBR    = agentBR;
                    agentVM.CreatedBy  = userID;
                    agentVM.AgentType  = agentType;



                    bool status = manageAgent.UpdateAgent(agentVM);

                    if (status)
                    {
                        return(Json(new { status = true, message = "Successfully updated" }));
                    }
                    else
                    {
                        return(Json(new { status = false, message = "Update Failed" }));
                    }
                }
                else
                {
                    return(Json(new { status = false, message = "Agent Name already exists" }));
                }
            }
            catch (Exception ex)
            {
                return(Json(new { status = false, message = "Unknown error occurred" }));
            }
        }
예제 #5
0
        public ActionResult AddAgent()
        {
            var agent    = new Agent();
            var agencies = new Agencies();
            var clear    = new SecurityClearance();

            var agents = new AgentVM(agent, agencies.All(), clear.All());

            return(View(agents));
        }
예제 #6
0
        public ActionResult EditAgent(string identifier)
        {
            var agentVM = new AgentVM();

            agentVM.Agent     = service.FindAgentById(identifier);
            ViewBag.countries = GetCountries();
            agentVM.Aliases   = Alias.All();
            agentVM.SynchToAgentAliases();
            agentVM.SynchToSelectedAliasIds();
            return(View(agentVM));
        }
예제 #7
0
        public ActionResult AddAgent(Agent agent)
        {
            var repo = new AgentRepo();


            repo.Add(agent);
            var agencies = new Agencies();
            var clear    = new SecurityClearance();

            var agents = new AgentVM(agent, agencies.All(), clear.All());

            return(Redirect("/"));
        }
예제 #8
0
        public ActionResult Create()
        {
            //ViewBag.country = db.CountryMasters.ToList();
            //ViewBag.city = db.CityMasters.ToList();
            //ViewBag.location = db.LocationMasters.ToList();
            ViewBag.currency     = db.CurrencyMasters.ToList();
            ViewBag.zonecategory = db.ZoneCategories.ToList();
            ViewBag.achead       = db.AcHeads.ToList();
            ViewBag.roles        = db.RoleMasters.ToList();
            AgentVM v = new AgentVM();

            v.sCreditLimit = "0";
            v.ID           = 0;
            v.StatusActive = true;
            return(View(v));
        }
예제 #9
0
        public IActionResult Put(Guid key, string values)
        {
            var newModel = new AgentVM();

            JsonConvert.PopulateObject(values, newModel);

            var oldModel = _agentRepo.GetByUid(key);

            if (oldModel == null)
            {
                return(StatusCode(409, "Agent not found"));
            }

            if (ChangeEmailAsync(oldModel, newModel).Result)
            {
                JsonConvert.PopulateObject(values, oldModel);

                if (!TryValidateModel(oldModel))
                {
                    return(BadRequest(GetFullErrorMessage(ModelState)));
                }

                var user      = _accountManager.GetUserAsync(oldModel.EMail).Result;
                var succeeded = true;

                if (newModel.RoleName != null)
                {
                    succeeded = _accountManager.ChangeRoleAsync(user, newModel.RoleName).Result;
                }

                if (succeeded)
                {
                    // *** Updating agent role around here
                    _agentRepo.Update(oldModel);

                    return(_uow.Commit() ? Ok() : StatusCode(StatusCodes.Status500InternalServerError));
                }
                else
                {
                    throw new ApplicationException("Failed changing user role.");
                }
            }
            else
            {
                return(BadRequest(GetFullErrorMessage(this.ModelState)));
            }
        }
        public List <AgentVM> GetAgentsByCompanyID(int companyID)
        {
            try
            {
                var agentData = unitOfWork.TblAgentRepository.Get(x => x.tblCompany.CompID == companyID).ToList();

                List <AgentVM> agentList = new List <AgentVM>();

                foreach (var agent in agentData)
                {
                    AgentVM agentVM = new AgentVM();
                    agentVM.AgentID   = agent.AgentID;
                    agentVM.CompanyID = agent.CompID != null?Convert.ToInt32(agent.CompID) : 0;

                    if (agentVM.CompanyID > 0)
                    {
                        agentVM.CompanyName = agent.tblCompany.CompanyName;
                    }

                    agentVM.AgentName = agent.AgentName;
                    agentVM.Address1  = agent.Address1;
                    agentVM.Address2  = agent.Address2;
                    agentVM.Address3  = agent.Address3;
                    agentVM.RateValue = agent.RateValue != null?Convert.ToDouble(agent.RateValue) : 0;

                    agentVM.CreatedDate = agent.CreatedDate != null?agent.CreatedDate.ToString() : string.Empty;

                    agentVM.ModifiedDate = agent.ModifiedDate != null?agent.ModifiedDate.ToString() : string.Empty;

                    agentVM.CreatedBy = agent.CreatedBy != null?Convert.ToInt32(agent.CreatedBy) : 0;

                    agentVM.ModifiedBy = agent.ModifiedBy != null?Convert.ToInt32(agent.ModifiedBy) : 0;

                    agentVM.AgentType = agent.AgentType;
                    agentVM.AgentNIC  = agent.AgentNIC;
                    agentVM.AgentBR   = agent.AgentBRNo;
                    agentVM.AgentCode = agent.AgentCode;
                    agentList.Add(agentVM);
                }

                return(agentList);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
예제 #11
0
        public ActionResult AddAgent(AgentVM agentVM)
        {
            agentVM.Aliases = Alias.All();
            agentVM.SynchToAgentAliases();
            if (!ModelState.IsValid)
            {
                return(View(agentVM));
            }
            var result = service.AddAgent(agentVM.Agent);

            if (!result.Success)
            {
                foreach (var e in result.Messages)
                {
                    ModelState.AddModelError("", e);
                }
                return(View(agentVM));
            }
            return(RedirectToAction("Index"));
        }
        public AgentVM GetAgentByID(int agentID)
        {
            try
            {
                var agentData = unitOfWork.TblAgentRepository.GetByID(agentID);

                AgentVM agentVM = new AgentVM();
                agentVM.AgentID   = agentData.AgentID;
                agentVM.CompanyID = agentData.CompID != null?Convert.ToInt32(agentData.CompID) : 0;

                if (agentVM.CompanyID > 0)
                {
                    agentVM.CompanyName = agentData.tblCompany.CompanyName;
                }

                agentVM.AgentName = agentData.AgentName;
                agentVM.Address1  = agentData.Address1;
                agentVM.Address2  = agentData.Address2;
                agentVM.Address3  = agentData.Address3;
                agentVM.RateValue = agentData.RateValue != null?Convert.ToDouble(agentData.RateValue) : 0;

                agentVM.CreatedDate = agentData.CreatedDate != null?agentData.CreatedDate.ToString() : string.Empty;

                agentVM.ModifiedDate = agentData.ModifiedDate != null?agentData.ModifiedDate.ToString() : string.Empty;

                agentVM.CreatedBy = agentData.CreatedBy != null?Convert.ToInt32(agentData.CreatedBy) : 0;

                agentVM.ModifiedBy = agentData.ModifiedBy != null?Convert.ToInt32(agentData.ModifiedBy) : 0;

                agentVM.AgentType = agentData.AgentType;
                agentVM.AgentNIC  = agentData.AgentNIC;
                agentVM.AgentBR   = agentData.AgentBRNo;
                agentVM.AgentCode = agentData.AgentCode;
                return(agentVM);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
예제 #13
0
        public ActionResult EditAgent(AgentVM agentVM, string currentIdentifier)
        {
            agentVM.Aliases = Alias.All();
            agentVM.SynchToAgentAliases();
            agentVM.SynchToSelectedAliasIds();
            if (!ModelState.IsValid)
            {
                return(View(agentVM));
            }
            var result = service.EditAgent(agentVM.Agent, currentIdentifier);

            if (!result.Success)
            {
                foreach (var e in result.Messages)
                {
                    ModelState.AddModelError("", e);
                }
                agentVM.Agent = result.Payload;
                return(View(agentVM));
            }
            return(RedirectToAction("Index"));
        }
예제 #14
0
        public IActionResult Post(string values)
        {
            var model = new Agent();

            JsonConvert.PopulateObject(values, model);

            var modelVM = new AgentVM();

            JsonConvert.PopulateObject(values, modelVM);

            if (!TryValidateModel(model))
            {
                return(BadRequest(GetFullErrorMessage(ModelState)));
            }

            var user = new ApplicationUser()
            {
                UserName = model.EMail, Email = model.EMail
            };

            //IdentityResult result = await _accountManager.CreateAccountAsync(user, EnumApplicationRole.Agent);
            IdentityResult result = _accountManager.CreateAccountAsync(user, modelVM.RoleName != null ? modelVM.RoleName : nameof(EnumApplicationRole.Agent)).Result;

            if (result.Succeeded)
            {
                _accountManager.SendEmailConfirmationAsync(user, this.Request, this.Url).Wait();

                model.ApplicationUserId = user.Id;
                _agentRepo.Add(model);

                return(_uow.Commit() ? Ok() : StatusCode(StatusCodes.Status500InternalServerError));
            }
            else
            {
                _accountManager.AddModelStateErrors(this.ModelState, result);
                return(BadRequest(GetFullErrorMessage(this.ModelState)));
            }
        }
예제 #15
0
        public IActionResult Index()
        {
            var Agent        = new AgentModel();
            var AgentProfile = new AgentVM();

            Agent.Id    = 0001;
            Agent.Name  = "Melissa Crosby";
            Agent.About = "<p>Being a full - service Realtor since 2007, I have been baptized by fire in a very tough housing market.I have successfully closed over 60 transactions and processed over 70 short sales both as the listing agent and some for other agents. I am very knowledgeable about lenders and their processes.I strive to exceed expectations and never forget that I am always accountable to my clients.</ p >" +
                          "<p> My objective is to establish relationships for life, not just for the current transaction.I enjoy assisting home buyers and sellers to get moved to a better place, one that is exciting. </ p >" +
                          "<p class='l-small'><strong>Brokerage:</strong> Berkshire Hathaway HomeServices Elite Real Estate</p>" +
                          "<p class='l-small'><strong>Specialties:</strong> Property Management, Buyer’s Agent, Listing Agent…</p>" +
                          "<p class='l-small'><strong>License Number(s):</strong> #5452129</p>";


            //Reviews 1
            var Reviews = GetReviewList();

            //Agent Reviews 1
            var comment     = "Being a full-service Realtor since 2007, I have been baptized by fire in a very tough housing market. I have successfully closed over 60 transactions and processed over 70 short sales both as the listing agent and some for other agents. I am very knowledgeable about lenders and their processes. I strive to exceed expectations and never forget that I am always accountable to my clients.";
            var AgentReview = GetAgentReview(comment, Reviews);

            AgentProfile.Review.Add(AgentReview);

            //Reviews 2
            Reviews = GetReviewList();

            //Agent Reviews 2
            comment     = "Most important to me was communication and Mark saw that every question or concern of ours we met with full and complete information. In most cases, Mark delivered information to us before we even had to ask. I look forward to working with Mark in the future because I know that I can trust him to";
            AgentReview = GetAgentReview(comment, Reviews);
            AgentProfile.Review.Add(AgentReview);

            AgentProfile.ActiveListing = GetActiveList();
            AgentProfile.Agent         = Agent;
            AgentProfile.AvgReview     = 4.5M;

            return(View(AgentProfile));
        }
 public ActionResult AgentList(int PageNo = 1, int PageSize = 10, string SearchTerm = "")
 {
     try
     {
         ViewBag.ActiveURL = "/Admin/AgentList";
         string     query    = "PageNo=" + PageNo + "&PageSize=" + PageSize + "&SearchTerm=" + SearchTerm;
         AgentAPIVM apiModel = objAPI.GetRecordByQueryString <AgentAPIVM>("AgentConfig", "agentlist", query);
         AgentVM    model    = new AgentVM();
         model.AgentList  = apiModel.AgentList;
         model.PagingInfo = new PagingInfo {
             CurrentPage = PageNo, ItemsPerPage = PageSize, TotalItems = apiModel.TotalRecords
         };
         if (Request.IsAjaxRequest())
         {
             return(PartialView("_pvAgentList", model));
         }
         return(View(model));
     }
     catch (AuthorizationException)
     {
         TempData["ErrMsg"] = "Your Login Session has expired. Please Login Again";
         return(RedirectToAction("Login", "Account", new { Area = "" }));
     }
 }
예제 #17
0
        public ActionResult Edit(int id)
        {
            int BranchID = Convert.ToInt32(Session["CurrentBranchID"].ToString());

            AgentVM a = new AgentVM();

            var item = (from c in db.AgentMasters where c.AgentID == id select c).FirstOrDefault();

            //ViewBag.country = db.CountryMasters.ToList();
            //ViewBag.city = (from c in db.CityMasters where c.CountryID == item.CountryID select c).ToList();
            //ViewBag.location = (from c in db.LocationMasters where c.CityID == item.CityID select c).ToList();
            ViewBag.currency     = db.CurrencyMasters.ToList();
            ViewBag.zonecategory = db.ZoneCategories.ToList();
            ViewBag.achead       = db.AcHeads.ToList();
            ViewBag.roles        = db.RoleMasters.ToList();

            if (item == null)
            {
                return(HttpNotFound());
            }
            else
            {
                a.ID             = item.AgentID;
                a.AgentName      = item.Name;
                a.AgentCode      = item.AgentCode;
                a.Address1       = item.Address1;
                a.Address2       = item.Address2;
                a.Address3       = item.Address3;
                a.Phone          = item.Phone;
                a.Fax            = item.Fax;
                a.WebSite        = item.WebSite;
                a.ContactPerson  = item.ContactPerson;
                a.CountryName    = item.CountryName;
                a.CityName       = item.CityName;
                a.LocationName   = item.LocationName;
                a.CurrencyID     = item.CurrencyID;
                a.ZoneCategoryID = item.ZoneCategoryID;
                a.AcHeadID       = item.AcHeadID;

                a.CreditLimit = item.CreditLimit;
                decimal cvalue = 0;
                if (item.CreditLimit != null)
                {
                    cvalue = Convert.ToDecimal(item.CreditLimit);
                }

                a.sCreditLimit = string.Format("{0:#,0}", cvalue);

                a.BranchID = BranchID;
                a.Email    = item.Email;


                if (item.UserID != 0)
                {
                    var user = db.UserRegistrations.Where(cc => cc.UserID == item.UserID).FirstOrDefault();

                    if (user != null)
                    {
                        a.RoleID   = Convert.ToInt32(user.RoleID);
                        a.Password = user.Password;
                    }
                }
                else
                {
                    a.UserID   = 0;
                    a.Password = "";
                }

                a.AgentType    = item.AgentType;
                a.StatusActive = item.StatusActive;
            }
            return(View(a));
        }
예제 #18
0
        public ActionResult Edit(AgentVM item)
        {
            UserRegistration u    = new UserRegistration();
            PickupRequestDAO _dao = new PickupRequestDAO();
            int BranchID          = Convert.ToInt32(Session["CurrentBranchID"].ToString());
            int accompanyid       = Convert.ToInt32(Session["CurrentCompanyID"].ToString());

            AgentMaster a = db.AgentMasters.Find(item.ID);

            a.AcCompanyID   = accompanyid;
            a.Name          = item.AgentName;
            a.AgentCode     = item.AgentCode;
            a.Address1      = item.Address1;
            a.Address2      = item.Address2;
            a.Address3      = item.Address3;
            a.Phone         = item.Phone;
            a.Fax           = item.Fax;
            a.WebSite       = item.WebSite;
            a.ContactPerson = item.ContactPerson;
            a.CountryName   = item.CountryName;
            a.CityName      = item.CityName;
            a.LocationName  = item.LocationName;
            a.CurrencyID    = item.CurrencyID;
            // a.ZoneCategoryID = item.ZoneCategoryID;
            //a.AcHeadID = item.AcHeadID;
            a.CreditLimit = item.CreditLimit;
            a.AgentType   = item.AgentType;

            if (item.StatusActive != null)
            {
                a.StatusActive = Convert.ToBoolean(item.StatusActive);
            }
            if (a.BranchID == null)
            {
                a.BranchID = BranchID;
            }

            UserRegistration x = null;

            if (a.UserID != null && a.UserID > 0)
            {
                x = (from b in db.UserRegistrations where b.UserID == a.UserID select b).FirstOrDefault();
            }

            if (a.Email != item.Email || x == null)
            {
                if (x == null)
                {
                    int max1 = (from c1 in db.UserRegistrations orderby c1.UserID descending select c1.UserID).FirstOrDefault();

                    int roleid = db.RoleMasters.Where(t => t.RoleName == "Agent").FirstOrDefault().RoleID;
                    u.UserID   = max1 + 1;
                    u.UserName = item.Email;
                    u.EmailId  = item.Email;

                    if (item.Password == "" || item.Password == null)
                    {
                        u.Password = _dao.RandomPassword(6);
                    }
                    else
                    {
                        u.Password = item.Password;
                    }
                    u.Phone    = item.Phone;
                    u.IsActive = true;
                    u.RoleID   = roleid;
                    db.UserRegistrations.Add(u);
                    db.SaveChanges();

                    a.Email  = item.Email;
                    a.UserID = u.UserID;
                }
                else
                {
                    //checking duplicate
                    UserRegistration x1 = (from b in db.UserRegistrations where b.UserName == item.Email && b.UserID != a.UserID select b).FirstOrDefault();
                    if (x1 == null)
                    {
                        x.EmailId = item.Email;
                        if (item.Password == "")
                        {
                            x.Password = _dao.RandomPassword(6);
                        }
                        else
                        {
                            x.Password = item.Password;
                        }

                        db.Entry(x).State = EntityState.Modified;
                        db.SaveChanges();
                    }

                    a.Email  = item.Email;
                    a.UserID = x.UserID;
                }
            }
            else
            {
                if (a.UserID == null || a.UserID == 0)
                {
                    int max1 = (from c1 in db.UserRegistrations orderby c1.UserID descending select c1.UserID).FirstOrDefault();

                    int roleid = db.RoleMasters.Where(t => t.RoleName == "Agent").FirstOrDefault().RoleID;
                    u.UserID   = max1 + 1;
                    u.UserName = item.Email;
                    u.EmailId  = item.Email;
                    if (item.Password == "")
                    {
                        u.Password = _dao.RandomPassword(6);
                    }
                    else
                    {
                        u.Password = item.Password;
                    }
                    u.Phone    = item.Phone;
                    u.IsActive = true;
                    u.RoleID   = roleid;
                    db.UserRegistrations.Add(u);
                    db.SaveChanges();
                    a.UserID = u.UserID;
                }
                else
                {
                    u = (from b in db.UserRegistrations where b.UserID == a.UserID select b).FirstOrDefault();
                    if (item.Password != u.Password)
                    {
                        u.Password = item.Password;
                    }

                    db.Entry(u).State = EntityState.Modified;
                    db.SaveChanges();
                }
            }



            if (ModelState.IsValid)
            {
                db.Entry(a).State = EntityState.Modified;
                db.SaveChanges();

                if (item.EmailNotify == true)
                {
                    EmailDAO _emaildao = new EmailDAO();
                    _emaildao.SendCustomerEmail(item.Email, item.Email, u.Password);
                }
                TempData["SuccessMsg"] = "You have successfully Updated Agent.";
                return(RedirectToAction("Index"));
            }
            return(View());
        }
예제 #19
0
        public ActionResult Create(AgentVM item)
        {
            int              companyId = Convert.ToInt32(Session["CurrentCompanyID"].ToString());
            int              BranchID  = Convert.ToInt32(Session["CurrentBranchID"].ToString());
            int?             max       = (from c in db.AgentMasters orderby c.AgentID descending select c.AgentID).FirstOrDefault();
            AgentMaster      a         = new AgentMaster();
            PickupRequestDAO _dao      = new PickupRequestDAO();
            int              roleid    = db.RoleMasters.Where(t => t.RoleName == "Agent").FirstOrDefault().RoleID;

            UserRegistration u = new UserRegistration();

            UserRegistration x = (from b in db.UserRegistrations where b.UserName == item.Email select b).FirstOrDefault();

            if (x == null)
            {
                int max1 = (from c1 in db.UserRegistrations orderby c1.UserID descending select c1.UserID).FirstOrDefault();

                u.UserID   = max1 + 1;
                u.UserName = item.Email;
                u.EmailId  = item.Email;

                if (item.Password == null)
                {
                    u.Password = _dao.RandomPassword(6);
                }
                else
                {
                    u.Password = item.Password;
                }

                u.Phone    = item.Phone;
                u.IsActive = true;
                u.RoleID   = roleid;
                db.UserRegistrations.Add(u);
                db.SaveChanges();
            }

            if (max == null || max == 0)
            {
                a.AgentID       = 1;
                a.Name          = item.AgentName;
                a.AgentCode     = item.AgentCode;
                a.Address1      = item.Address1;
                a.Address2      = item.Address2;
                a.Address3      = item.Address3;
                a.Phone         = item.Phone;
                a.Fax           = item.Fax;
                a.WebSite       = item.WebSite;
                a.ContactPerson = item.ContactPerson;
                a.AcCompanyID   = companyId;
                //a.CountryID = item.CountryID;
                //a.CityID = item.CityID;
                //a.LocationID = item.LocationID;
                a.CurrencyID     = item.CurrencyID;
                a.ZoneCategoryID = item.ZoneCategoryID;
                a.AcHeadID       = item.AcHeadID;
                a.CreditLimit    = item.CreditLimit;
                a.CountryName    = item.CountryName;
                a.CityName       = item.CityName;
                a.LocationName   = item.LocationName;
                a.Email          = item.Email;
                a.Password       = "";
                a.AgentType      = item.AgentType;
                a.UserID         = u.UserID;

                if (item.StatusActive == null)
                {
                    a.StatusActive = false;
                }
                else
                {
                    a.StatusActive = Convert.ToBoolean(item.StatusActive);
                }

                a.BranchID = BranchID;
            }
            else
            {
                a.AgentID        = Convert.ToInt32(max) + 1;
                a.Name           = item.AgentName;
                a.AgentCode      = item.AgentCode;
                a.Address1       = item.Address1;
                a.Address2       = item.Address2;
                a.Address3       = item.Address3;
                a.Phone          = item.Phone;
                a.Fax            = item.Fax;
                a.WebSite        = item.WebSite;
                a.ContactPerson  = item.ContactPerson;
                a.AcCompanyID    = companyId;
                a.CountryName    = item.CountryName;
                a.CityName       = item.CityName;
                a.LocationName   = item.LocationName;
                a.CurrencyID     = item.CurrencyID;
                a.ZoneCategoryID = item.ZoneCategoryID;
                a.AcHeadID       = item.AcHeadID;
                a.CreditLimit    = item.CreditLimit;

                a.Email     = item.Email;
                a.Password  = "";
                a.AgentType = item.AgentType;
                a.UserID    = u.UserID;
                a.BranchID  = BranchID;
                if (item.StatusActive == null)
                {
                    a.StatusActive = false;
                }
                else
                {
                    a.StatusActive = Convert.ToBoolean(item.StatusActive);
                }
            }

            try
            {
                db.AgentMasters.Add(a);
                db.SaveChanges();

                if (item.EmailNotify == true)
                {
                    EmailDAO _emaildao = new EmailDAO();
                    _emaildao.SendCustomerEmail(item.Email, item.Email, u.Password);
                }

                TempData["SuccessMsg"] = "You have successfully added Agent.";
                return(RedirectToAction("Index"));
            }

            catch (Exception ex)
            {
                ViewBag.currency       = db.CurrencyMasters.ToList();
                ViewBag.zonecategory   = db.ZoneCategories.ToList();
                ViewBag.achead         = db.AcHeads.ToList();
                ViewBag.roles          = db.RoleMasters.ToList();
                TempData["WarningMsg"] = ex.Message;
                return(View(item));
            }
        }