示例#1
0
        public User ValidateUser(string userName, string password)
        {
            password = SecurityFunction.EncryptString(password);
            var user = GetUsers().SingleOrDefault(u => u.UserName == userName && u.Password == password);

            return(user);
        }
示例#2
0
        public User ValidateUserByEmail(string EmailId, string password)
        {
            password = SecurityFunction.EncryptString(password);
            var user = GetUsers().SingleOrDefault(u => u.UserEmailAddress == EmailId && u.Password == password);

            return(user);
        }
示例#3
0
        public User ValidateUserByTrebId(string TrebId, string password)
        {
            password = SecurityFunction.EncryptString(password);
            var user = GetUsers().FirstOrDefault(u => u.TrebId == TrebId && u.Password == password);

            return(user);
        }
        public string ForgotPasswordMethod(string Email)
        {
            string UserName = "";
            var    user     = _UserService.GetUserByEmailId(Email);

            if (user != null)             //By Email Id
            {
                UserName = user.UserName; //Get User Name
            }
            else //By User Name
            {
                UserName = Email; //Here Email is UserName, Set User Name
                user     = _UserService.GetUserByName(UserName);
            }
            if (user != null)
            {
                //Send Email to User
                string Password = SecurityFunction.DecryptString(user.Password);
                SendMailToUser(UserName, Email, Password);

                TempData["ShowMessage"] = "success";
                TempData["MessageBody"] = "Password send to your email. Please check your email";
                return("success");
            }
            else
            {
                TempData["ShowMessage"] = "error";
                TempData["MessageBody"] = "User doesnot exist or Incorrect email id.";
                return("failed");
            }
        }
        public ActionResult ChangePassword(ChangePasswordModel changepasswordmodel)
        {
            try
            {
                if (string.IsNullOrEmpty(changepasswordmodel.OldPassword))
                {
                    ModelState.AddModelError("OldPassword", "Please enter old password.");
                }
                if (string.IsNullOrEmpty(changepasswordmodel.NewPassword))
                {
                    ModelState.AddModelError("NewPassword", "Please enter new password.");
                }
                if (string.IsNullOrEmpty(changepasswordmodel.ConfirmPassword))
                {
                    ModelState.AddModelError("ConfirmPassword", "Please enter confirm password.");
                }
                //if (!string.IsNullOrEmpty(changepasswordmodel.NewPassword) && changepasswordmodel.NewPassword.Length < 4)
                //{
                //    ModelState.AddModelError("NewPassword", "Please enter minimum Length 4 in new/confirm password .");

                //}
                if (!string.IsNullOrEmpty(changepasswordmodel.NewPassword) && !string.IsNullOrEmpty(changepasswordmodel.ConfirmPassword))
                {
                    if (changepasswordmodel.NewPassword != changepasswordmodel.ConfirmPassword)
                    {
                        ModelState.AddModelError("ConfirmPassword", "New password should match confirm password.");
                    }
                }
                int UserId = Convert.ToInt32(Session["UserId"].ToString());

                var user    = _UserService.GetUserById(UserId);
                var pasword = SecurityFunction.DecryptString(user.Password);
                if (pasword != changepasswordmodel.OldPassword)
                {
                    ModelState.AddModelError("OldPassword", "Please enter valid old password.");
                }
                if (ModelState.IsValid)
                {
                    if (user != null)
                    {
                        user.Password = SecurityFunction.EncryptString(changepasswordmodel.NewPassword);
                        _UserService.UpdateUser(user);
                        TempData["ShowMessage"] = "success";
                        TempData["MessageBody"] = "Password changed successfully.";
                        return(RedirectToAction("LogOn"));
                    }
                }
            }
            catch (Exception ex)
            {
                string ErrorMsg = ex.Message.ToString();//
                ErrorLogging.LogError(ex);
            }
            var errors           = ModelState.Where(x => x.Value.Errors.Count > 0).Select(x => new { x.Key, x.Value.Errors }).ToArray();
            var modelStateErrors = this.ModelState.Keys.SelectMany(key => this.ModelState[key].Errors);

            return(View(changepasswordmodel));
        }
        // ChangePassword method not implemented in CustomMembershipProvider.cs
        // Feel free to update!

        //
        // POST: /Account/ChangePassword
        public string ChangePasswordMethod(string OldPassword, string NewPassword, string ConfirmPassword)
        {
            if (OldPassword == "") //Old Password Blank
            {
                TempData["ShowMessage"] = "error";
                TempData["MessageBody"] = "Please enter a valid old password.";
                return("Please enter a valid old password.");
            }
            else if ((NewPassword == "") || (ConfirmPassword == ""))
            {
                TempData["ShowMessage"] = "error";
                TempData["MessageBody"] = "Please enter a valid new/confirm password.";
                return("Please enter a valid new/confirm password.");
            }
            else if (NewPassword != ConfirmPassword)
            {
                TempData["ShowMessage"] = "error";
                TempData["MessageBody"] = "New Password and confirm password doesnot matching.";
                return("New Password and confirm password doesnot matching.");
            }

            try
            {
                int UserId = Convert.ToInt32(Session["UserId"].ToString());

                var user = _UserService.GetUserById(UserId);
                if (user != null)
                {
                    if (SecurityFunction.DecryptString(user.Password) == OldPassword)
                    {
                        //Update the User Password
                        user.Password = SecurityFunction.EncryptString(NewPassword);
                        _UserService.UpdateUser(user);
                        //End : Update the User Password
                        TempData["ShowMessage"] = "success";
                        TempData["MessageBody"] = "Password changed successfully.";
                        return("success");
                    }
                    else
                    {
                        TempData["ShowMessage"] = "error";
                        TempData["MessageBody"] = "Please enter a valid old password.";
                        return("Please enter a valid old password.");
                    }
                }
            }
            catch (Exception ex)
            {
                string ErrorMsg = ex.Message.ToString();
                ErrorLogging.LogError(ex);
            }

            TempData["ShowMessage"] = "error";
            TempData["MessageBody"] = "Unknown Error Occurred while processing request.";
            return("Unknown Error Occurred while processing request.");
        }
        public JsonResult ResetPassword([Bind(Include = "Password,UserId,RequestId")] RegisterModel registerModel)
        {
            try
            {
                Mapper.CreateMap <RegisterModel, User>();
                User userMaster = Mapper.Map <RegisterModel, User>(registerModel);
                User userFound  = _userService.GetUser(registerModel.UserId.ToString());
                if (userFound != null)
                {
                    if (!userFound.IsActive)
                    {
                        return(Json(Infrastructure.CommonClass.CreateMessage("error", "Your email verification is pending.")));
                    }

                    //Update User
                    userFound.Password = SecurityFunction.EncryptString(userMaster.Password);
                    var userDetail = _userService.UpdateUser(userFound);
                    //End : Update User

                    //Start : Update Email Verification
                    var emailVerification = _emailVerificationService.GetEmailVerification(registerModel.RequestId); //Here RequestId is EmailVerificationId
                    if (emailVerification != null)
                    {
                        emailVerification.IsOperationDone = true;
                        _emailVerificationService.UpdateEmailVerification(emailVerification);
                    }
                    //End : Update Email Verification

                    //Start : Send Email
                    EmailManager emailManager = new EmailManager();
                    EMailEntity  emailEntity  = new EMailEntity();
                    emailEntity.ToMail    = userFound.EmailId;
                    emailEntity.RequestId = registerModel.RequestId; //There is no use of RequestId. It is just for error handing in SendMailForConfirmResetPassword function.
                    emailEntity.FirstName = userFound.FirstName;
                    emailManager.SendMailForConfirmResetPassword(emailEntity);
                    //End : Send Email
                    return(Json(Infrastructure.CommonClass.CreateMessage("success", "Password is changed successfully.")));
                }
                else
                {
                    return(Json(Infrastructure.CommonClass.CreateMessage("error", "User does not exists.")));
                }
            }
            catch (Exception ex)
            {
                string ErrorMsg = ex.Message.ToString();

                ErrorLog errorlog = new ErrorLog();
                errorlog.LogError(ex);
                return(Json(Infrastructure.CommonClass.CreateMessage("error", "Please try again.")));
            }
        }
        public JsonResult Register(RegisterModel registerModel)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    Mapper.CreateMap <RegisterModel, User>();
                    User user = Mapper.Map <RegisterModel, User>(registerModel);
                    user.UserName = registerModel.Email;
                    user.EmailId  = registerModel.Email;

                    //Check Email already exist
                    User isEmailFound = _userService.GetUserByName(user.EmailId);
                    if (isEmailFound != null)
                    {
                        return(Json(Infrastructure.CommonClass.CreateMessage("error", "Email already in use.")));
                    }

                    //Insert User
                    user.Password = SecurityFunction.EncryptString(user.Password);
                    user.IsActive = false;
                    var userResult = _userService.InsertUser(user);
                    //End : Insert User

                    if (userResult != null)
                    {
                        //Start : Add Job for Send Welcome Email
                        JobScheduler.WelcomeEmailJob(user.UserId.ToString(), EnumValue.GetEnumDescription(EnumValue.EmailType.WelcomeEmail));
                        //End : Add Job for Send Welcome Email

                        //return Json(Infrastructure.CommonClass.CreateMessage("success", "Successfully registered. Please check your email for account verification."));
                        return(Json(Infrastructure.CommonClass.CreateMessage("success", "Successfully registered. Please check your email.")));
                    }
                    else
                    {
                        return(Json(Infrastructure.CommonClass.CreateMessage("error", "There is problem while saving data.")));
                    }
                }
                return(Json(Infrastructure.CommonClass.CreateMessage("error", "Please fill all the fields")));
            }
            catch (Exception ex)
            {
                string   ErrorMsg = ex.Message.ToString();
                ErrorLog errorlog = new ErrorLog();
                errorlog.LogError(ex);
                return(Json(Infrastructure.CommonClass.CreateMessage("error", "Please try again.")));
                //var errors = ModelState.Where(x => x.Value.s.SelectMany(key => this.ModelState[key].Errors);
            }
        }
        public HttpResponseMessage ForgotPassword([FromBody] ForgetPasswordsModel usermodel)
        {
            try
            {
                if (usermodel.CustomerType == "" || usermodel.CustomerType == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("error", "Customer Type is blank."), Configuration.Formatters.JsonFormatter));
                }
                if (usermodel.CustomerType != EnumValue.GetEnumDescription(EnumValue.CustomerType.Customer) && usermodel.CustomerType != EnumValue.GetEnumDescription(EnumValue.CustomerType.ServiceProvider))
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("error", "Wrong Customer Type."), Configuration.Formatters.JsonFormatter));
                }
                if (usermodel.EmailId == "" || usermodel.CustomerType == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("error", "Customer Type is blank."), Configuration.Formatters.JsonFormatter));
                }
                var customer = _CustomerService.GetCustomers().Where(x => x.EmailId == usermodel.EmailId && x.CustomerType == usermodel.CustomerType).FirstOrDefault();
                if (customer != null)
                {
                    var user = _UserService.GetUserById(Convert.ToInt32(customer.UserId));
                    if (user != null)
                    {
                        if (!customer.IsActive)
                        {
                            return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("error", "User is deactivated."), Configuration.Formatters.JsonFormatter));
                        }
                        //Send Email to User
                        string Password = SecurityFunction.DecryptString(user.Password);
                        SendMailToUser(customer.FirstName + " " + customer.LastName, usermodel.EmailId, Password);

                        return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("success", "Password has been sent to your email. Please check your email."), Configuration.Formatters.JsonFormatter));
                    }
                    else
                    {
                        return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("error", "User is not found."), Configuration.Formatters.JsonFormatter));
                    }
                }
                else
                {
                    return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("error", "Incorrect email id."), Configuration.Formatters.JsonFormatter));
                }
            }
            catch (Exception ex)
            {
                string ErrorMsg = ex.Message.ToString();
                ErrorLogging.LogError(ex);
                return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("error", "Please try later."), Configuration.Formatters.JsonFormatter));
            }
        }
 public HttpResponseMessage ChangePassword([FromBody] ChangePasswordsModel changeModel)
 {
     try
     {
         var customer = _CustomerService.GetCustomers().Where(x => x.CustomerId == changeModel.CustomerId && x.IsActive == true).FirstOrDefault();
         if (customer != null)
         {
             if (customer.Password == "")
             {
                 return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("error", "only manually registered users can change their password."), Configuration.Formatters.JsonFormatter));
             }
             var user = _UserService.GetUserById(Convert.ToInt32(customer.UserId));//(customer.UserId);
             if (user != null)
             {
                 var sp = _AgencyIndividualService.GetAgencyIndividuals().Where(a => a.UserId == Convert.ToInt32(customer.UserId)).FirstOrDefault();
                 if (SecurityFunction.DecryptString(user.Password) == changeModel.OldPassword)
                 {
                     sp.Password = customer.Password = user.Password = SecurityFunction.EncryptString(changeModel.NewPassword);
                     _UserService.UpdateUser(user);
                     _CustomerService.UpdateCustomer(customer);
                     _AgencyIndividualService.UpdateAgencyIndividual(sp);
                     return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("success", "Password changed successfully."), Configuration.Formatters.JsonFormatter));
                 }
                 else
                 {
                     return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("error", "Wrong old password."), Configuration.Formatters.JsonFormatter));
                 }
             }
             else
             {
                 return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("error", "User does not exist."), Configuration.Formatters.JsonFormatter));
             }
         }
         else
         {
             return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("error", "User does not exist."), Configuration.Formatters.JsonFormatter));
         }
     }
     catch (Exception ex)
     {
         string ErrorMsg = ex.Message.ToString();
         ErrorLogging.LogError(ex);
         return(Request.CreateResponse(HttpStatusCode.OK, CommonCls.CreateMessage("error", "Please try later."), Configuration.Formatters.JsonFormatter));
     }
 }
        //
        // GET: /Account/LogOn

        public ActionResult LogOn()
        {
            DateTime date = DateTime.Now.AddDays(-1);
            string   gjh  = String.Format("{0:M/d/yyyy}", date);
            //string appid = "eqfAxBSZeCo:APA91bGyWabm11I5pA0OOM-3d6wzTSNBMoJtXvnnnUgkO9f-VmH5Ic5URd3HFgqDMBfgQe__Lyc666D3Ibs_bAe2K_vKZsZTfzIBOg7kApQKdgRhSsqzqz6MqVjBegMH-2XyERlhTK3y";
            //string UserMessage = "hello";
            //string Message = "6";

            //CommonCls.TestSendFCM_Notifications(appid, Message, UserMessage);
            //string ApplicationId = "";
            //string JsonMessage = "{\"Flag\":\"" + "6" + "\",\"Message\":\"" + "hello" + "\"}";

            //CommonCls.SendGCM_Notifications(ApplicationId, JsonMessage, true);
            var pas      = "******";
            var password = SecurityFunction.DecryptString(pas);


            return(View());
        }
示例#12
0
        // GET: /User/Details/5
        public ActionResult Details(int id)
        {
            UserPermissionAction("user", RoleAction.detail.ToString());
            CheckPermission();

            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            User user = _UserService.GetUserById(id);// db.Users.Find(id);

            Mapper.CreateMap <CommunicationApp.Entity.User, CommunicationApp.Models.UserModel>();
            CommunicationApp.Models.UserModel usermodel = Mapper.Map <CommunicationApp.Entity.User, CommunicationApp.Models.UserModel>(user);
            usermodel.Password = SecurityFunction.DecryptString(user.Password);
            if (usermodel == null)
            {
                return(HttpNotFound());
            }
            return(View(usermodel));
        }
        // GET: /Customer/Edit/5
        public ActionResult Edit(int id)
        {
            AdminModel AdminModel = new CommunicationApp.Models.AdminModel();
            var        Customer   = _CustomerService.GetCustomers().Where(c => c.CustomerId == id).FirstOrDefault();

            if (Customer != null)
            {
                var models = new List <AdminModel>();
                Mapper.CreateMap <CommunicationApp.Entity.Customer, CommunicationApp.Models.AdminModel>();
                AdminModel = Mapper.Map <CommunicationApp.Entity.Customer, CommunicationApp.Models.AdminModel>(Customer);
                var User    = _UserService.GetUser(Customer.UserId);
                var Company = _CompanyService.GetCompany(Customer.CompanyID);
                if (Company != null)
                {
                    AdminModel.AdminCompanyLogo    = Company.LogoPath;
                    AdminModel.CompanyName         = Company.CompanyName;
                    AdminModel.AdminCompanyAddress = Company.CompanyAddress;
                }
                if (User != null)
                {
                    AdminModel.Password = SecurityFunction.DecryptString(User.Password);
                }
                if (AdminModel.PhotoPath != null && AdminModel.PhotoPath != "")
                {
                    AdminModel.PhotoPath = AdminModel.PhotoPath;
                }
                else
                {
                    AdminModel.PhotoPath = CommonCls.GetURL() + "/images/noImage.jpg";
                }
            }


            ViewBag.CityID      = (Customer.CityID <= 0 ? "" : Customer.CityID.ToString());
            ViewBag.StateID     = (Customer.StateID <= 0 ? "" : Customer.StateID.ToString());
            ViewBag.Countrylist = new SelectList(_CountryService.GetCountries(), "CountryID", "CountryName", Customer.CountryID);
            ViewBag.Citylist    = new SelectList(_CityService.GetCities(), "CityID", "CityName", Customer.CityID);
            ViewBag.UserId      = new SelectList(_UserService.GetUsers(), "UserId", "FirstName", Customer.UserId);

            return(View(AdminModel));
        }
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var user = _UserService.ValidateUser(model.UserName, SecurityFunction.EncryptString(model.Password));
                if (user != null)
                {
                    SetSessionVariables(model.UserName);
                    var tt = Session["RoleType"].ToString();
                    if (tt == "SuperAdmin")
                    {
                        return(Json("superadmin", JsonRequestBehavior.AllowGet));
                    }
                    else if (tt == "Agency")
                    {
                        return(Json("agency", JsonRequestBehavior.AllowGet));
                    }
                    else
                    {
                        Session["RoleType"] = null;
                        Session["UserId"]   = null;
                        return(Json("notAllow", JsonRequestBehavior.AllowGet));
                    }
                }
                else
                {
                    Session["RoleType"] = null;
                    Session["UserId"]   = null;
                    return(Json(false, JsonRequestBehavior.AllowGet));
                }
            }
            ModelState.AddModelError("Password", "The user name or password provided is incorrect.");

            // If we got this far, something failed, redisplay form
            var errors           = ModelState.Where(x => x.Value.Errors.Count > 0).Select(x => new { x.Key, x.Value.Errors }).ToArray();
            var modelStateErrors = this.ModelState.Keys.SelectMany(key => this.ModelState[key].Errors);

            return(View(model));
        }
示例#15
0
        // GET: /User/Edit/5
        public ActionResult Edit(int id)
        {
            UserPermissionAction("user", RoleAction.edit.ToString());
            CheckPermission();

            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            User user = _UserService.GetUserById(id);//db.Users.Find(id);

            Mapper.CreateMap <CommunicationApp.Entity.User, CommunicationApp.Models.UserModel>();
            CommunicationApp.Models.UserModel usermodel = Mapper.Map <CommunicationApp.Entity.User, CommunicationApp.Models.UserModel>(user);
            if (usermodel == null)
            {
                return(HttpNotFound());
            }
            user.Password = SecurityFunction.EncryptString(user.Password);

            ViewBag.CompanyID = new SelectList(_CompanyService.GetCompanies(), "CompanyID", "CompanyName", user.CompanyID);
            return(View(usermodel));
        }
        public ActionResult ForgotPassword([Bind(Include = "UserName")] ForgotPasswordModel model)
        {
            try
            {
                if (string.IsNullOrEmpty(model.UserName))
                {
                    ModelState.AddModelError("Name", "Please enter email.");
                }
                if (ModelState.IsValid)
                {
                    string UserName = "";
                    var    user     = _UserService.GetUserByEmailId(model.UserName);
                    if (user != null)              //By Email Id
                    {
                        UserName = user.FirstName; //Get User Name

                        //Send Email to User
                        string Password = SecurityFunction.DecryptString(user.Password);
                        CommonCls.SendMailToUser(UserName, model.UserName, Password);
                        TempData["MessageBody"] = "Your password has been sent to this email address.";
                        ViewBag.Error           = TempData["MessageBody"];
                    }
                    else
                    {
                        TempData["MessageBody"] = "This email address does not exist in our records.";
                        ViewBag.Error           = TempData["MessageBody"];
                    }
                }
            }
            catch (Exception ex)
            {
                string ErrorMsg = ex.Message.ToString();//
                ErrorLogging.LogError(ex);
            }
            var errors           = ModelState.Where(x => x.Value.Errors.Count > 0).Select(x => new { x.Key, x.Value.Errors }).ToArray();
            var modelStateErrors = this.ModelState.Keys.SelectMany(key => this.ModelState[key].Errors);

            return(View(model));
        }
        public ActionResult Register([Bind(Include = "CustomerId,FirstName,LastName,EmailId,MobileNo,Password")] CustomerModel Customermodel)
        {
            try
            {
                TempData["ShowMessage"] = "error";
                TempData["MessageBody"] = "Please fill the required field with valid data";
                if (ModelState.IsValid)
                {
                    Mapper.CreateMap <CommunicationApp.Models.CustomerModel, CommunicationApp.Entity.Customer>();
                    CommunicationApp.Entity.Customer Customer = Mapper.Map <CommunicationApp.Models.CustomerModel, CommunicationApp.Entity.Customer>(Customermodel);


                    Customer Customers = _CustomerService.GetCustomers().Where(c => c.FirstName.Trim() == Customer.FirstName.Trim() || c.EmailId.Trim() == Customer.EmailId.Trim() || c.MobileNo.Trim() == Customer.MobileNo.Trim()).FirstOrDefault();

                    if (Customers == null)
                    {
                        //There is no session in API Controller. So we will find solution in future
                        Customer.CompanyID = 1;
                        //Insert User first
                        string Password = Customermodel.Password;
                        CommunicationApp.Entity.User user = new CommunicationApp.Entity.User();
                        //user.UserId =0; //New Case
                        user.FirstName        = Customer.FirstName;
                        user.LastName         = Customer.LastName;
                        user.UserName         = Customer.MobileNo;                        // insert mobile number//
                        user.Password         = SecurityFunction.EncryptString(Password); //No password right now. We will create send email procedure for password recovery
                        user.UserEmailAddress = Customer.EmailId;
                        user.CompanyID        = Customer.CompanyID;
                        user.IsActive         = true;
                        _UserService.InsertUser(user);
                        //End : Insert User first

                        if (user.UserId > 0)
                        {
                            //Insert User Role
                            CommunicationApp.Entity.UserRole userRole = new CommunicationApp.Entity.UserRole();
                            userRole.UserId = user.UserId;
                            userRole.RoleId = 3; //By Default set new Customer/user role id=3
                            _UserroleService.InsertUserRole(userRole);
                            //End : Insert User Role

                            //Insert the Customer

                            //Save the Driver photo in Folder


                            //Check SubPath Exist or Not


                            Customer.UserId = user.UserId;

                            Customer.Longitude     = 0;
                            Customer.Latitude      = 0;
                            Customer.ApplicationId = "";
                            _CustomerService.InsertCustomer(Customer); //Save Operation
                            //End : Insert the Customer
                        }
                        TempData["ShowMessage"] = "success";
                        TempData["MessageBody"] = Customer.FirstName + " is saved successfully.";
                        ModelState.Clear();
                        return(RedirectToAction("LogOn", "Account"));
                    }
                    else
                    {
                        TempData["ShowMessage"] = "error";
                        if (Customers.FirstName.Trim() == Customermodel.FirstName.Trim())
                        {
                            TempData["MessageBody"] = Customermodel.FirstName + " is already exists.";
                        }
                        else if (Customers.EmailId.Trim() == Customermodel.EmailID.Trim())
                        {
                            TempData["MessageBody"] = Customermodel.EmailID + " is already exists.";
                        }
                        else if (Customers.MobileNo.Trim() == Customermodel.MobileNo.Trim())
                        {
                            TempData["MessageBody"] = Customermodel.MobileNo + " is already exists.";
                        }
                        else
                        {
                            TempData["MessageBody"] = "Please fill the required field with valid data";
                        }

                        //_DriverService.UpdateDriver(driver); //Update Operation
                    }
                }
            }

            catch (RetryLimitExceededException)
            {
                TempData["ShowMessage"] = "error";
                TempData["MessageBody"] = "Some unknown problem occured while proccessing save operation on " + Customermodel.FirstName + " ";
            }


            return(View(Customermodel));
        }
        public ActionResult Edit([Bind(Include = "CustomerId,TrebId,WebsiteUrl,ApplicationID,Password,CompanyID,CompanyName,UserId,PhotoPath,AdminCompanyLogo,FirstName,LastName,MiddleName,EmailID,MobileNo,CountryID,StateID,CityID,ZipCode,Latitude,Longitude,CreatedOn,LastUpdatedOn,MobileVerifyCode,EmailVerifyCode,IsMobileVerified,IsEmailVerified,IsActive,AdminCompanyAddress")] AdminModel AdminModel, HttpPostedFileBase file, HttpPostedFileBase Logo)
        {
            UserPermissionAction("property", RoleAction.view.ToString());
            CheckPermission();
            TempData["ShowMessage"] = "";
            TempData["MessageBody"] = "";
            try
            {
                if (ModelState.IsValid)
                {
                    var CustomerFound = _CustomerService.GetCustomers().Where(c => ((c.EmailId.Trim() == AdminModel.EmailID.Trim() || c.MobileNo.Trim() == AdminModel.MobileNo.Trim()) && c.CustomerId != AdminModel.CustomerId)).FirstOrDefault();
                    if (CustomerFound == null)
                    {
                        var PhotoPath      = "";
                        var CompanyLogo    = "";
                        var CustomerUpdate = _CustomerService.GetCustomer(AdminModel.CustomerId);//.Where(c => c.CustomerId == AdminModel.CustomerId).FirstOrDefault();
                        if (CustomerUpdate != null)
                        {
                            var Company = _CompanyService.GetCompany(CustomerUpdate.CompanyID);
                            if (Company != null)
                            {
                                Company.CompanyName    = AdminModel.CompanyName != null ? AdminModel.CompanyName : "Company";
                                Company.CompanyAddress = AdminModel.AdminCompanyAddress;
                                if (Logo != null)
                                {
                                    CompanyLogo      = SaveFile(AdminModel.PhotoPath, Logo);
                                    Company.LogoPath = CompanyLogo;
                                }

                                _CompanyService.UpdateCompany(Company);
                            }

                            if (file != null)
                            {
                                PhotoPath = SaveFile(AdminModel.PhotoPath, file);
                                CustomerUpdate.PhotoPath = PhotoPath;
                            }

                            CustomerUpdate.FirstName  = AdminModel.FirstName;
                            CustomerUpdate.LastName   = AdminModel.LastName;
                            CustomerUpdate.MiddleName = AdminModel.MiddleName;
                            CustomerUpdate.Address    = AdminModel.Address;
                            CustomerUpdate.EmailId    = AdminModel.EmailID;
                            CustomerUpdate.DOB        = AdminModel.DOB;
                            CustomerUpdate.MobileNo   = AdminModel.MobileNo;
                            CustomerUpdate.WebsiteUrl = AdminModel.WebsiteUrl;
                            CustomerUpdate.IsActive   = true;
                            if (AdminModel.Designation != null && AdminModel.Designation != "")
                            {
                                CustomerUpdate.Designation = AdminModel.Designation;
                            }
                            _CustomerService.UpdateCustomer(CustomerUpdate);

                            //Update user table.
                            var User = _UserService.GetUser(CustomerUpdate.UserId);
                            User.FirstName = AdminModel.FirstName;
                            User.LastName  = AdminModel.LastName;
                            if (AdminModel != null)
                            {
                                User.Password = SecurityFunction.EncryptString(AdminModel.Password);
                                User.TrebId   = "0000000000000";
                            }
                            _UserService.UpdateUser(User);
                            TempData["ShowMessage"] = "success";
                            TempData["MessageBody"] = CustomerUpdate.FirstName + " is update successfully.";
                            return(RedirectToAction("Index", "Admin"));
                        }
                        else
                        {
                            TempData["ShowMessage"] = "error";
                            TempData["MessageBody"] = "Customer not found.";
                            return(RedirectToAction("Index", "Admin"));
                        }
                    }
                    else
                    {
                        TempData["ShowMessage"] = "error";

                        if (CustomerFound.EmailId.Trim() == AdminModel.EmailID.Trim())
                        {
                            TempData["MessageBody"] = AdminModel.EmailID + " is already exists.";
                        }
                        if (CustomerFound.TrebId.Trim() == AdminModel.TrebId.Trim())
                        {
                            TempData["MessageBody"] = AdminModel.TrebId + " is already exists.";
                        }
                        if (CustomerFound.MobileNo.Trim() == AdminModel.MobileNo.Trim())
                        {
                            TempData["MessageBody"] = "This" + " " + AdminModel.MobileNo + " is already exists.";
                        }
                        else
                        {
                            TempData["MessageBody"] = "Please fill the required field with valid data";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                CommonCls.ErrorLog(ex.ToString());
                TempData["ShowMessage"] = "error";
                TempData["MessageBody"] = "Some unknown problem occured while proccessing save operation on " + AdminModel.FirstName + " client";
            }
            var errors           = ModelState.Where(x => x.Value.Errors.Count > 0).Select(x => new { x.Key, x.Value.Errors }).ToArray();
            var modelStateErrors = this.ModelState.Keys.SelectMany(key => this.ModelState[key].Errors);

            ViewBag.UserId      = new SelectList(_UserService.GetUsers(), "UserId", "FirstName", AdminModel.UserId);
            ViewBag.CityID      = (AdminModel.CityID <= 0 ? "" : AdminModel.CityID.ToString());
            ViewBag.StateID     = (AdminModel.StateID <= 0 ? "" : AdminModel.StateID.ToString());
            ViewBag.Countrylist = new SelectList(_CountryService.GetCountries(), "CountryID", "CountryName", AdminModel.CountryID);
            ViewBag.Statelist   = new SelectList(_StateService.GetStates(), "StateID", "StateName", AdminModel.StateID);
            ViewBag.Citylist    = new SelectList(_CityService.GetCities(), "CityID", "CityName", AdminModel.CityID);


            return(View(AdminModel));
        }
        public ActionResult Create([Bind(Include = "CustomerId,TrebId,WebsiteUrl,ApplicationID,Password,CompanyID,UserId,PhotoPath,FirstName,LastName,MiddleName,EmailID,MobileNo,CountryID,StateID,CityID,ZipCode,Latitude,Longitude,CreatedOn,LastUpdatedOn,MobileVerifyCode,EmailVerifyCode,IsMobileVerified,IsEmailVerified,IsActive,AdminCompanyAddress")] AdminModel AdminModel, HttpPostedFileBase file, HttpPostedFileBase Logo)
        {
            TempData["ShowMessage"] = "";
            TempData["MessageBody"] = "";
            UserPermissionAction("admin", RoleAction.create.ToString());
            CheckPermission();
            Mapper.CreateMap <CommunicationApp.Models.AdminModel, CommunicationApp.Entity.Customer>();
            CommunicationApp.Entity.Customer Customer = Mapper.Map <CommunicationApp.Models.AdminModel, CommunicationApp.Entity.Customer>(AdminModel);

            if (ModelState.IsValid)
            {
                var customerFound = _CustomerService.GetCustomers().Where(x => x.EmailId == Customer.EmailId || x.MobileNo == Customer.MobileNo || x.WebsiteUrl == Customer.WebsiteUrl).FirstOrDefault();
                if (customerFound == null)
                {
                    //Save Company of admin

                    Company Company = new Entity.Company();
                    Company.WebSite        = Customer.WebsiteUrl;
                    Company.CountryID      = 1;
                    Company.StateID        = 1;
                    Company.CityID         = 1;
                    Company.CompanyAddress = AdminModel.AdminCompanyAddress != "" ? AdminModel.AdminCompanyAddress : "*****@*****.**";
                    Company.CompanyName    = AdminModel.CompanyName != null ? AdminModel.CompanyName : "Company";
                    Company.EmailID        = "*****@*****.**";
                    Company.PhoneNo        = "123456987";
                    Company.IsActive       = true;
                    if (Logo != null)
                    {
                        Company.LogoPath = Savefile(Logo);
                    }

                    _CompanyService.InsertCompany(Company);

                    //Insert User first
                    CommunicationApp.Entity.User user = new CommunicationApp.Entity.User();
                    //user.UserId =0; //New Case
                    user.FirstName        = Customer.FirstName;
                    user.TrebId           = Customer.TrebId;
                    user.LastName         = Customer.LastName;
                    user.UserName         = Customer.EmailId;
                    user.Password         = SecurityFunction.EncryptString(AdminModel.Password);
                    user.UserEmailAddress = Customer.EmailId;
                    user.CompanyID        = Company.CompanyID;
                    user.CreatedOn        = DateTime.Now;
                    user.LastUpdatedOn    = DateTime.Now;
                    user.TrebId           = "0000000";
                    user.IsActive         = true;
                    _UserService.InsertUser(user);
                    //End : Insert User first

                    var UserID = user.UserId;
                    if (user.UserId > 0)
                    {
                        //Insert User Role
                        CommunicationApp.Entity.UserRole userRole = new CommunicationApp.Entity.UserRole();
                        userRole.UserId = user.UserId;
                        userRole.RoleId = 2; //By Default set new Admin/user role id=2
                        _UserRoleService.InsertUserRole(userRole);
                        //End : Insert User Role

                        //Insert the Customer
                        Customer.FirstName        = Customer.FirstName;
                        Customer.UserId           = user.UserId;
                        Customer.Designation      = "Admin";
                        Customer.MobileVerifyCode = CommonCls.GetNumericCode();
                        Customer.EmailVerifyCode  = CommonCls.GetNumericCode();
                        Customer.MobileVerifyCode = "9999";
                        Customer.EmailVerifyCode  = "9999";
                        Customer.CreatedOn        = DateTime.Now;
                        Customer.CompanyID        = Company.CompanyID;
                        Customer.Address          = "";
                        Customer.ZipCode          = "";
                        Customer.IsEmailVerified  = true;

                        var PhotoPath = "";
                        if (file != null)
                        {
                            PhotoPath = Savefile(file);
                        }

                        Customer.PhotoPath             = PhotoPath;
                        Customer.IsMobileVerified      = false;
                        Customer.ApplicationId         = AdminModel.ApplicationId;
                        Customer.DeviceSerialNo        = AdminModel.DeviceSerialNo;
                        Customer.DeviceType            = AdminModel.DeviceType;
                        Customer.IsUpdated             = false;
                        Customer.IsNotificationSoundOn = true;
                        if (Customer.FirstName == null)
                        {
                            Customer.FirstName = "";
                        }
                        if (Customer.LastName == null)
                        {
                            Customer.LastName = "";
                        }
                        if (Customer.MiddleName == null)
                        {
                            Customer.MiddleName = "";
                        }
                        _CustomerService.InsertCustomer(Customer);

                        var CustomerID = Customer.CustomerId.ToString();
                        AdminModel.CustomerId   = Customer.CustomerId;
                        TempData["ShowMessage"] = "Success";
                        TempData["MessageBody"] = "Admin successfully register.";
                    }
                }
                else
                {
                    if (customerFound.EmailId == AdminModel.EmailID)
                    {
                        TempData["ShowMessage"] = "Error";
                        TempData["MessageBody"] = "Email is already exist.";
                    }
                    else if (customerFound.MobileNo == AdminModel.MobileNo)
                    {
                        TempData["ShowMessage"] = "Error";
                        TempData["MessageBody"] = "MobileNos is already exist.";
                    }
                    else
                    {
                        TempData["ShowMessage"] = "Error";
                        TempData["MessageBody"] = "Some error occured.";
                    }
                }
            }
            else
            {
                var errors           = ModelState.Where(x => x.Value.Errors.Count > 0).Select(x => new { x.Key, x.Value.Errors }).ToArray();
                var modelStateErrors = this.ModelState.Keys.SelectMany(key => this.ModelState[key].Errors);
                TempData["ShowMessage"] = "Error";
                TempData["MessageBody"] = "Please fill the required data.";
                return(View(AdminModel));
            }


            return(RedirectToAction("Index"));
        }
示例#20
0
        public ActionResult Create([Bind(Include = "CustomerId,FirstName,EmailID,CompanyName,CompanyAddress,AboutCompany,OtherInformation,SelectedEquiments,LocationLists,VisionMission,LogoPath,BusinessBrochureUrl")] CustomerModel CustomerModel, FormCollection form, HttpPostedFileBase file1, HttpPostedFileBase file2)
        {
            UserPermissionAction("vendor", RoleAction.create.ToString());
            CheckPermission();

            string CustomerID = "-1";
            int    UserID     = 0;
            int    CompanyID  = 0;

            CustomerModel.CompanyAddress = "qq";
            try
            {
                if (ModelState.IsValid)
                {
                    //var Location = form["LocationLists"].ToString();
                    Mapper.CreateMap <Onlo.Models.CustomerModel, Onlo.Entity.Customer>();
                    Onlo.Entity.Customer Customer      = Mapper.Map <Onlo.Models.CustomerModel, Onlo.Entity.Customer>(CustomerModel);
                    Customer             customerFound = _CustomerService.GetCustomers().Where(x => x.EmailId == Customer.EmailId).FirstOrDefault();
                    if (customerFound == null)
                    {
                        string EmailId   = Customer.EmailId;
                        string FirstName = CustomerModel.FirstName;
                        string Password  = CustomerModel.Password;

                        if (CustomerModel.FirstName == "" || CustomerModel.FirstName == null)
                        {
                            FirstName = Customer.EmailId.Split('@')[0].Trim();
                        }
                        Customer.CompanyID = 1; //There is no session in API Controller. So we will find solution in future
                        Customer.Address   = "";
                        Customer.MobileNo  = "";
                        Customer.ZipCode   = "";
                        Customer.PhotoPath = "";
                        //Insert User first
                        Onlo.Entity.User user = new Onlo.Entity.User();
                        //user.UserId =0; //New Case
                        user.FirstName = CustomerModel.FirstName;
                        user.LastName  = Customer.LastName;
                        user.UserName  = CustomerModel.FirstName;;
                        user.Password  = SecurityFunction.EncryptString(FirstName + "@123");
                        //user.Password = SecurityFunction.EncryptString(Password);
                        user.UserEmailAddress = EmailId;
                        user.CompanyID        = Customer.CompanyID;
                        user.CreatedOn        = DateTime.Now;
                        user.LastUpdatedOn    = DateTime.Now;
                        user.IsActive         = true;
                        _UserService.InsertUser(user);
                        //End : Insert User firstss

                        UserID = user.UserId;
                        if (user.UserId > 0)
                        {
                            //Insert User Role
                            Onlo.Entity.UserRole userRole = new Onlo.Entity.UserRole();
                            userRole.UserId = user.UserId;
                            userRole.RoleId = 3; //By Default set new Customer/user role id=3
                            _UserRoleService.InsertUserRole(userRole);
                            //End : Insert User Role

                            //Insert the Customer
                            Customer.FirstName        = FirstName;
                            Customer.UserId           = user.UserId;
                            Customer.MobileVerifyCode = CommonClass.GetNumericCode();
                            Customer.EmailVerifyCode  = CommonClass.GetNumericCode();
                            if (CustomerModel.IsEmailVerified != null)
                            {
                                Customer.IsEmailVerified = CustomerModel.IsEmailVerified;
                            }
                            else
                            {
                                Customer.IsEmailVerified = false;
                            }
                            if ((CustomerModel.PhotoPath != null) && (CustomerModel.PhotoPath != ""))
                            {
                                if (!CustomerModel.PhotoPath.Contains('.'))
                                {
                                    Customer.PhotoPath = CommonClass.SaveImage(CustomerModel.PhotoPath, "CustomerPhoto", ".png");//SaveImage(CustomerModel.PhotoPath);
                                }
                            }
                            // Customer.RoleType = EnumValue.GetEnumDescription(EnumValue.RoleType.Manufacturer);
                            Customer.IsActive = true;
                            Customer.SubscriptionStartDate = DateTime.Now;
                            Customer.SubscriptionEndDate   = DateTime.UtcNow.AddMonths(1);
                            _CustomerService.InsertCustomer(Customer);
                            CustomerID = Convert.ToString(Customer.CustomerId);
                            if (CustomerID != null)
                            {
                                var Customers = _CustomerService.GetCustomers().Where(x => x.CustomerId == Convert.ToInt32(CustomerID));
                                if (Customers != null)
                                {
                                    Company Company = new Company();
                                    Company.CompanyName      = CustomerModel.CompanyName;
                                    Company.AboutCompany     = CustomerModel.AboutCompany;
                                    Company.CompanyAddress   = "aa";
                                    Company.CityID           = 0;
                                    Company.StateID          = 0;
                                    Company.CountryID        = 39;
                                    Company.OtherInformation = CustomerModel.OtherInformation;
                                    Company.VisionMission    = CustomerModel.VisionMission;

                                    if (file1 != null)
                                    {
                                        var    fileExt  = Path.GetExtension(file1.FileName);
                                        string fileName = Guid.NewGuid() + fileExt;
                                        var    subPath  = Server.MapPath("~/CompanyLogo");
                                        //Check SubPath Exist or Not
                                        if (!Directory.Exists(subPath))
                                        {
                                            Directory.CreateDirectory(subPath);
                                        }
                                        //End : Check SubPath Exist or Not
                                        var path      = Path.Combine(subPath, fileName);
                                        var shortPath = "~/CompanyLogo/" + fileName;
                                        file1.SaveAs(path);
                                        CommonClass.CreateThumbnail(shortPath, 218, 84, false);
                                        string URL = CommonClass.GetURL() + "/CompanyLogo/" + fileName;
                                        Company.LogoPath = URL;
                                        //Company.LogoPath = shortPath;
                                        //_CompanyService.UpdateCompany(Company);
                                    }
                                    if (file2 != null)
                                    {
                                        var    fileExt  = Path.GetExtension(file2.FileName);
                                        string fileName = Guid.NewGuid() + fileExt;
                                        var    subPath  = Server.MapPath("~/BusinessBrochure");
                                        //Check SubPath Exist or Not
                                        if (!Directory.Exists(subPath))
                                        {
                                            Directory.CreateDirectory(subPath);
                                        }
                                        //End : Check SubPath Exist or Not
                                        var path      = Path.Combine(subPath, fileName);
                                        var shortPath = "~/BusinessBrochure/" + fileName;
                                        file2.SaveAs(path);
                                        CommonClass.CreateThumbnail(shortPath, 218, 84, false);
                                        string URL = CommonClass.GetURL() + "/BusinessBrochure/" + fileName;
                                        Company.BusinessBrochureUrl = URL;
                                    }
                                    Company.IsActive = true;
                                    _CompanyService.InsertCompany(Company);

                                    CompanyID = Convert.ToInt32(Company.CompanyID);
                                    //SAVE company//

                                    //Insert CompanyEquipments
                                    if (CustomerModel.SelectedEquiments != null)
                                    {
                                        //foreach (var ItemId in CustomerModel.SelectedEquiments)
                                        //{
                                        //    CompanyEquipment CompanyEquipments = new CompanyEquipment();
                                        //    CompanyEquipments.ItemId = Convert.ToInt32(ItemId);
                                        //    CompanyEquipments.CompanyID = Convert.ToInt32(CompanyID);
                                        //    _CompanyEquipmentService.InsertCompanyEquipment(CompanyEquipments);
                                        //}
                                    }
                                    //insert CompanyLocation
                                    if (CompanyID > 0)
                                    {
                                        if (CustomerModel.LocationLists != null)
                                        {
                                            foreach (var Locationlist in CustomerModel.LocationLists)
                                            {
                                                CompanyLocation companyLocation = new CompanyLocation();
                                                var             _location       = GoogleOperation.GetLatLong(Locationlist);

                                                var lat     = _location[0];
                                                var log     = _location[1];
                                                var address = Locationlist;//latlong1[2];

                                                companyLocation.CompanyID = CompanyID;
                                                companyLocation.Location  = address.ToString();//"Latitude":30.71000000,"Longitude":76.69000000
                                                companyLocation.Latitude  = Convert.ToDecimal(lat);
                                                companyLocation.Longitude = Convert.ToDecimal(log);
                                                _CompanyLocationService.InsertCompanyLocation(companyLocation);
                                            }
                                        }
                                    }
                                    //End insert CompanyLocation
                                    //update company_id in customer table
                                    var customers = _CustomerService.GetCustomers().Where(x => x.CustomerId == Convert.ToInt32(CustomerID));
                                    foreach (var custormer in customers)
                                    {
                                        var customer = _CustomerService.GetCustomer(custormer.CustomerId);
                                        customer.CompanyID = CompanyID;
                                        _CustomerService.UpdateCustomer(customer);
                                    }
                                    string UserPassword = SecurityFunction.DecryptString(user.Password);
                                    JobScheduler.Registration(Customer.FirstName, Customer.EmailId, UserPassword);// using Scheduler//
                                }
                                TempData["ShowMessage"] = "success";
                                TempData["MessageBody"] = "Manufacturer is saved successfully.";
                                return(RedirectToAction("Index"));
                            }
                        }
                    }
                    else
                    {
                        TempData["ShowMessage"] = "error";
                        TempData["MessageBody"] = "vendors is already exists.";
                    }
                }
                var errors           = ModelState.Where(x => x.Value.Errors.Count > 0).Select(x => new { x.Key, x.Value.Errors }).ToArray();
                var modelStateErrors = this.ModelState.Keys.SelectMany(key => this.ModelState[key].Errors);
            }
            catch (Exception ex)
            {
                var UserRole = _UserRoleService.GetUserRoles().Where(x => x.UserId == UserID).FirstOrDefault();
                if (UserRole != null)
                {
                    _UserRoleService.DeleteUserRole(UserRole); // delete user role
                }
                var User = _UserService.GetUsers().Where(x => x.UserId == UserID).FirstOrDefault();
                if (User != null)
                {
                    _UserService.DeleteUser(User);       // delete user
                }
                string ErrorMsg = ex.Message.ToString(); //
                ErrorLogging.LogError(ex);
            }
            //var Equiment = _IItemService.GetItems();
            //CustomerModel.EquimentList = Equiment.Select(x => new SelectListItem { Value = x.ItemId.ToString(), Text = x.ItemName }).ToList();
            return(View(CustomerModel));
        }
示例#21
0
        public ActionResult Edit([Bind(Include = "UserId,UserName,Password,UserEmailAddress,CompanyID,IsActive")] UserModel usermodel, int id)
        {
            UserPermissionAction("user", RoleAction.edit.ToString());
            CheckPermission();

            try
            {
                ViewBag.CompanyID       = new SelectList(_CompanyService.GetCompanies(), "CompanyID", "CompanyName", usermodel.CompanyID);
                TempData["ShowMessage"] = "error";
                TempData["MessageBody"] = "Please fill the required field with valid data";

                if (ModelState.IsValid)
                {
                    User objUser = _UserService.GetUsers().Where(c => c.UserName.ToLower() == usermodel.UserName.ToLower() || c.UserEmailAddress.ToLower() == usermodel.UserEmailAddress.ToLower() && c.UserId != usermodel.UserId).FirstOrDefault(); //db.Users.Where(x => (x.UserName.ToLower() == user.UserName.ToLower() || x.UserEmailAddress.ToLower() == user.UserEmailAddress.ToLower()) && x.UserId != user.UserId).FirstOrDefault();
                    if (objUser == null)
                    {
                        Mapper.CreateMap <CommunicationApp.Models.UserModel, CommunicationApp.Entity.User>();
                        CommunicationApp.Entity.User user = Mapper.Map <CommunicationApp.Models.UserModel, CommunicationApp.Entity.User>(usermodel);
                        //Update the User Info
                        User us = _UserService.GetUsers().Where(c => c.UserId == id).FirstOrDefault();//db.Users.Where(z => z.UserId == id).FirstOrDefault();
                        us.UserName         = user.UserName;
                        us.Password         = SecurityFunction.EncryptString(user.Password);
                        us.UserEmailAddress = user.UserEmailAddress;
                        us.CompanyID        = user.CompanyID;
                        us.IsActive         = user.IsActive;
                        _UserService.UpdateUser(us);
                        //db.SaveChanges();


                        TempData["ShowMessage"] = "success";
                        TempData["MessageBody"] = user.UserName + " is update successfully.";

                        return(RedirectToAction("Index"));
                    }
                    else
                    {
                        TempData["ShowMessage"] = "error";
                        if (objUser.UserName.ToLower() == usermodel.UserName.ToLower()) //Check User Name
                        {
                            TempData["MessageBody"] = usermodel.UserName + " is already exist.";
                        }
                        else if (objUser.UserEmailAddress.ToLower() == usermodel.UserEmailAddress.ToLower()) //Check User Name
                        {
                            TempData["MessageBody"] = usermodel.UserEmailAddress + " is already exist.";
                        }
                        else
                        {
                            TempData["MessageBody"] = "Some unknown problem occured while proccessing update operation on " + usermodel.UserName + " user.";
                        }
                    }
                }
            }
            catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
            {
                //Exception raise = dbEx;
                //foreach (var validationErrors in dbEx.EntityValidationErrors)
                //{
                //    foreach (var validationError in validationErrors.ValidationErrors)
                //    {
                //        string message = string.Format("{0}:{1}",
                //            validationErrors.Entry.Entity.ToString(),
                //            validationError.ErrorMessage);
                //         raise a new exception nesting
                //         the current instance as InnerException
                //        raise = new InvalidOperationException(message, raise);
                //    }
                //}
                //throw raise;

                TempData["ShowMessage"] = "error";
                TempData["MessageBody"] = "Some problem occured while proccessing update operation on " + usermodel.UserName + " user.";
            }
            return(View(usermodel));
        }
        public ActionResult SignUp([Bind(Include = "FullName,EmailId,Password,WorkRate,ContactNumber,Address,CategoryId,IsAgency,Latitude,Longitude")] AgencyIndividualModel model)
        {
            AgencyIndividualModel agencyIndividualModel = new Models.AgencyIndividualModel();
            List <CategoryModel>  CategoryList          = new List <CategoryModel>();
            var categories = _CategoryService.GetCategories();

            //UserPermissionAction("vendor", RoleAction.view.ToString(), operation, ShowMessage, MessageBody);
            if (string.IsNullOrEmpty(model.FullName))
            {
                ModelState.AddModelError("FullName", "");
                return(View(model));
            }
            if (string.IsNullOrEmpty(model.EmailId))
            {
                ModelState.AddModelError("EmailId", "");
                return(View(model));
            }
            if (string.IsNullOrEmpty(model.Password))
            {
                ModelState.AddModelError("Password", "");
                return(View(model));
            }
            if (model.WorkRate == null)
            {
                ModelState.AddModelError("WorkRate", "");
                return(View(model));
            }
            if (string.IsNullOrEmpty(model.ContactNumber))
            {
                ModelState.AddModelError("ContactNumber", "");
                return(View(model));
            }
            if (string.IsNullOrEmpty(model.Address))
            {
                ModelState.AddModelError("Address", "");
                return(View(model));
            }

            try
            {
                if (ModelState.IsValid)
                {
                    var existingUser = _UserService.GetUserByEmailId(model.EmailId);
                    if (existingUser == null)
                    {
                        UserModel userModel = new UserModel();
                        userModel.EmailId       = model.EmailId;
                        userModel.Password      = SecurityFunction.EncryptString(model.Password);
                        userModel.FirstName     = model.FullName;
                        userModel.CompanyId     = 2;
                        userModel.IsActive      = true;
                        userModel.CreatedOn     = DateTime.Now;
                        userModel.LastUpdatedOn = DateTime.Now;
                        Mapper.CreateMap <UserModel, User>();
                        var User = Mapper.Map <UserModel, User>(userModel);
                        _UserService.InsertUser(User);

                        var           getUserDetail = _UserService.GetUserByEmailId(model.EmailId);
                        UserRoleModel userRoleModel = new UserRoleModel();
                        userRoleModel.UserId = getUserDetail.UserId;
                        userRoleModel.RoleId = 4;
                        Mapper.CreateMap <UserRoleModel, UserRole>();
                        var UserRole = Mapper.Map <UserRoleModel, UserRole>(userRoleModel);
                        _UserRoleService.InsertUserRole(UserRole);

                        model.CreatedOn     = DateTime.Now;
                        model.LastUpdatedOn = DateTime.Now;
                        model.Password      = SecurityFunction.EncryptString(model.Password);
                        model.UserId        = getUserDetail.UserId;
                        model.IsAgency      = true;
                        model.IsActive      = true;
                        model.IsInvited     = true;
                        model.ParentId      = new Guid();
                        Mapper.CreateMap <AgencyIndividualModel, AgencyIndividual>();
                        var agencyIndividual = Mapper.Map <AgencyIndividualModel, AgencyIndividual>(model);
                        _AgencyIndividualService.InsertAgencyIndividual(agencyIndividual);
                        TempData["MessageBody"] = "Registeration done.";
                        ViewBag.Error           = TempData["MessageBody"];
                        return(RedirectToAction("LogOn"));
                    }
                    else
                    {
                        TempData["MessageBody"] = "Email already exists.";
                        ViewBag.Error           = TempData["MessageBody"];
                        return(View(model));
                    }
                }
                else
                {
                    TempData["MessageBody"] = "Please fill the required fields.";
                    ViewBag.Error           = TempData["MessageBody"];
                    return(View(model));
                }
            }
            catch (Exception ex)
            {
                string ErrorMsg = ex.Message.ToString();//
                ErrorLogging.LogError(ex);
            }

            Mapper.CreateMap <HomeHelp.Entity.Category, HomeHelp.Models.CategoryModel>();
            foreach (var category in categories)
            {
                CategoryModel categoryModel = Mapper.Map <HomeHelp.Entity.Category, HomeHelp.Models.CategoryModel>(category);
                CategoryList.Add(categoryModel);
            }
            model.CategoryData      = CategoryList;
            TempData["MessageBody"] = "Something get wrong. please try again";
            ViewBag.Error           = TempData["MessageBody"];
            return(View(model));
        }