예제 #1
0
        public override object Save(M.AspNetUser entity)
        {
            if (entity.HasKey())
            {
                var result = base.Save(entity);

                addRoles(entity, entity.Id);

                return(result);
            }
            else
            {
                var user = new Models.AppUser
                {
                    Email        = entity.Email,
                    PasswordHash = UserManager.PasswordHasher.HashPassword(entity.Password),
                    PhoneNumber  = entity.PhoneNumber,
                    UserName     = entity.UserName
                };

                var result = UserManager.Create(user);
                if (!result.Succeeded)
                {
                    throw new SeatException(String.Join(",", result.Errors));
                }

                addRoles(entity, user.Id);

                entity.Id = user.Id;
                return(entity);
            }
        }
예제 #2
0
        public async Task <IActionResult> CheckOrCreate(string phone)
        {
#if Polly
            //Polly 重试和熔断测试
            throw new HttpRequestException();
#else
            //TODO: 做手机号码的格式验证

            var user = await _userContext.Users.SingleOrDefaultAsync(u => u.Phone == phone);

            if (user == null) //await _userContext.Users.AnyAsync(u => u.Phone == phone)
            {
                user = new Models.AppUser {
                    Phone = phone
                };
                _userContext.Users.Add(user);
                await _userContext.SaveChangesAsync();

                //_userContext.Users.Add(new Models.AppUser { Phone = phone });
            }

            // return Ok(user.Id);

            return(Ok(new
            {
                UserId = user.Id,//这里要新建一个UserId字段,与UserInfo的字段名称UserId对应上,否则在Identity.UserService的CheckOrCreate方法中对该方法返回的结果进行反序列化时,不能获取到user.Id的值,使用的是默认值0
                user.Name,
                user.Company,
                user.Title,
                user.Avatar
            }));
#endif
        }
예제 #3
0
        private async Task SignIn(Models.AppUser user)
        {
            var identity = await userManager.CreateIdentityAsync(
                user, DefaultAuthenticationTypes.ApplicationCookie);

            GetAuthenticationManager().SignIn(identity);
        }
예제 #4
0
        public SelectList GetAllCustomers()
        {
            var roles = db.Roles.Where(r => r.Name == "Customer");

            if (roles.Any())
            {
                var roleId      = roles.First().Id;
                var dbCustomers = from user in db.Users
                                  where user.Roles.Any(r => r.RoleId == roleId)
                                  select user;
                List <AppUser> Customers = dbCustomers.ToList();

                AppUser AllCustomers = new Models.AppUser()
                {
                    UserName = "******"
                };

                Customers.Insert(0, AllCustomers);

                SelectList CustomersList = new SelectList(Customers.OrderBy(u => u.Id), "UserName", "UserName");

                return(CustomersList);
            }

            return(null);
        }
예제 #5
0
        public ActionResult Login(LoginVM model, string ReturnUrl)
        {
            if (!ModelState.IsValid)
            {
                return(View("Login", model));
            }
            var userManager = HttpContext.GetOwinContext().GetUserManager <UserManager <Models.AppUser> >();
            var authManager = HttpContext.GetOwinContext().Authentication;

            Models.AppUser user = userManager.Find(model.UserName, model.Password);
            if (user == null)
            {
                ModelState.AddModelError("", "Invalid username or password");

                return(View("Login", model));
            }
            else
            {
                var identity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
                authManager.SignIn(new AuthenticationProperties {
                    IsPersistent = model.RememberMe
                }, identity);

                if (!string.IsNullOrEmpty(ReturnUrl))
                {
                    return(Redirect(ReturnUrl));
                }
                else
                {
                    return(RedirectToAction("Index"));
                }
            }
        }
예제 #6
0
        public ActionResult ChangePassword(UserAdminVM model)
        {
            EmployeeRepo eRepo = new EmployeeRepo();

            if (string.IsNullOrWhiteSpace(model.password1))
            {
                ModelState.AddModelError("password1", "Please enter your current password");
            }
            if (string.IsNullOrWhiteSpace(model.password2))
            {
                ModelState.AddModelError("password2", "Please enter a new password");
            }
            var userManager = HttpContext.GetOwinContext().GetUserManager <UserManager <AppUser> >();

            Models.AppUser user = userManager.Find(model.NewUser.UserName, model.password1);

            if (user == null || user.Id.ToString() != model.NewUser.EmployeeID)
            {
                ModelState.AddModelError("password1", "incorrect password");
            }
            if (ModelState.IsValid)
            {
                userManager.ChangePassword(model.NewUser.EmployeeID, model.password1, model.password2);
                return(RedirectToAction("index", "home"));
            }
            return(View("ChangePassword", model));
        }
예제 #7
0
        public async Task <ActionResult <string> > Post([FromBody] Models.AppUser value)
        {
            Document document = await _cosmosDBclient.CreateDocumentAsync(
                UriFactory.CreateDocumentCollectionUri(_dbName, _collectionName),
                value);

            return(Ok(document.Id));
        }
        public async Task <IdentityResult> Handle(RegisterUserRequest request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation($"Starting {nameof(RegisterUserHandler)}");

                var user = new Models.AppUser
                {
                    UserName = request.Input.Email,
                    Email    = request.Input.Email,
                    Name     = request.Input.Name,
                };

                var result = await _userManager.CreateAsync(user, request.Input.Password);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    await _userManager.AddToRoleAsync(user, Roles.User);

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    var callbackUrl = request.RequestUrlSchema +
                                      "://localhost:4200" +
                                      "/account/confirmEmail" +
                                      $"?code={code}&userId={user.Id}";
                    var title = "Confirm your email";
                    var body  = new List <string>
                    {
                        "Please confirm your account by clicking the link below."
                    };
                    var url      = new UrlEmailTemplateViewModel("Confirm account", callbackUrl);
                    var template = await _emailTemplateGenerator.RenderActionTemplate(title, body, url);

                    await _emailDispatcher.SaveEmail(new Email
                    {
                        Body    = template,
                        Subject = title,
                        To      = request.Input.Email
                    });

                    await _signInManager.SignInAsync(user, isPersistent : false);
                }

                _logger.LogInformation($"Finished {nameof(RegisterUserHandler)}");

                return(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ex.Message);
                throw;
            }
        }
 // GET: AppUser
 public ActionResult Index()
 {
     foreach (var u in db.GetAllUsers())
     {
         user             = new Models.AppUser();
         user.UserName    = u.DMUserName;
         user.FullName    = u.DMFullName;
         user.PhoneNumber = u.DMPhoneNumber;
         userList.Add(user);
     }
     return(View(userList));
 }
예제 #10
0
        private async Task LoadAsync(Models.AppUser user)
        {
            var userName = await _userManager.GetUserNameAsync(user);

            var phoneNumber = await _userManager.GetPhoneNumberAsync(user);

            Username = userName;

            Input = new InputModel
            {
                PhoneNumber = phoneNumber
            };
        }
 public ActionResult AdminViewCustomer(Models.AdminSelection s)
 {
     ViewBag.Message = "Customers of Location#" + s.SelectedLocationID.ToString();
     foreach (var u in db.GetUsersByLocationID(s.SelectedLocationID))
     {
         user             = new Models.AppUser();
         user.UserName    = u.DMUserName;
         user.FullName    = u.DMFullName;
         user.PhoneNumber = u.DMPhoneNumber;
         userList.Add(user);
     }
     return(View(userList));
 }
예제 #12
0
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            AppUser appUser = new Models.AppUser()
            {
                UserName  = context.HttpContext.User.Identity.Name,
                LoginDate = DateTime.Now,
            };

            LoggerDbContext logger = new LoggerDbContext();

            logger.AppUsers.Add(appUser);
            logger.SaveChanges();
        }
예제 #13
0
        private async Task LoadAsync(Models.AppUser user)
        {
            var email = await _userManager.GetEmailAsync(user);

            Email = email;

            Input = new InputModel
            {
                NewEmail = email,
            };

            IsEmailConfirmed = await _userManager.IsEmailConfirmedAsync(user);
        }
 public ActionResult Create(Models.AppUser user)
 {
     if (!db.UsernameExist(user.UserName))
     {
         db.AddUser(user.UserName, user.PassWord, user.FullName, user.PhoneNumber);
         TempData["ID"] = db.GetUserIDByUserName(user.UserName);
         return(RedirectToAction("UserMenu"));
     }
     else
     {
         ViewBag.Message = "User Name existed, please try again";
         return(View());
     }
 }
예제 #15
0
파일: BaseFixture.cs 프로젝트: Krztk/KtTest
        public Task AddUser(Models.AppUser user)
        {
            Func <UserManager <Models.AppUser>, Task> action = async x =>
            {
                var result = await x.CreateAsync(user, "password");

                if (!result.Succeeded)
                {
                    throw new Exception(string.Join(",", result.Errors));
                }
            };

            return(ExecuteScope(sp => action(sp.GetService <UserManager <Models.AppUser> >())));
        }
예제 #16
0
 private void RaiseUserprofileChangedEvent(Models.AppUser user)
 {
     if (_userContext.Entry(user).Property(nameof(user.Name)).IsModified || _userContext.Entry(user).Property(nameof(user.Title)).IsModified || _userContext.Entry(user).Property(nameof(user.Avatar)).IsModified || _userContext.Entry(user).Property(nameof(user.Company)).IsModified)
     {
         _capPublisher.Publish("finbook.userapi.userprofilechanged", new Dtos.UserIdentity
         {
             UserId  = user.Id.ToString(),
             Name    = user.Name,
             Title   = user.Title,
             Company = user.Company,
             Avatar  = user.Avatar
         });
     }
 }
예제 #17
0
        public async Task <IActionResult> CheckOrCreate(string phone)
        {
            // TODO:做手机号码格式验证
            var user = _userContext.Users.SingleOrDefault(u => u.Phone == phone);

            if (user == null)
            {
                user = new Models.AppUser {
                    Phone = phone
                };
                _userContext.Users.Add(user);
                await _userContext.SaveChangesAsync();
            }
            return(Ok(user.Id));
        }
예제 #18
0
        private void createRolesandUsers()
        {
            AppDbContext context = new AppDbContext();

            var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context));
            var UserManager = new UserManager <Models.AppUser>(new UserStore <Models.AppUser>(context));

            // In Startup iam creating first Admin Role and creating a default Admin User
            if (!roleManager.RoleExists("Admin"))
            {
                // first we create Admin rool
                var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
                role.Name = "Admin";
                roleManager.Create(role);

                //Here we create a Admin super user who will maintain the website

                var user = new Models.AppUser();
                user.UserName = "******";
                user.Email    = "*****@*****.**";

                string userPWD = "1qaz7410";

                var chkUser = UserManager.Create(user, userPWD);

                //Add default User to Role Admin
                if (chkUser.Succeeded)
                {
                    var result1 = UserManager.AddToRole(user.Id, "Admin");
                }
            }

            // creating Creating Manager role
            if (!roleManager.RoleExists("Manager"))
            {
                var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
                role.Name = "Manager";
                roleManager.Create(role);
            }

            // creating Creating Employee role
            if (!roleManager.RoleExists("Employee"))
            {
                var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
                role.Name = "Employee";
                roleManager.Create(role);
            }
        }
예제 #19
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl ??= Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            if (ModelState.IsValid)
            {
                var user = new Models.AppUser {
                    UserName = Input.Email, Email = Input.Email
                };
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { area = "Identity", userId = user.Id, code = code, returnUrl = returnUrl },
                        protocol: Request.Scheme);

                    await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                                                      $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                    if (_userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        return(RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl }));
                    }
                    else
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
예제 #20
0
 private async Task RaiseUserProfileChangedEventAsync(Models.AppUser user)
 {
     if (_userContext.Entry(user).Property(nameof(user.Name)).IsModified ||
         _userContext.Entry(user).Property(nameof(user.Title)).IsModified ||
         _userContext.Entry(user).Property(nameof(user.Company)).IsModified ||
         _userContext.Entry(user).Property(nameof(user.Avatar)).IsModified)
     {
         await _capPublisher.PublishAsync("userapi.userprofileChanged", new Dtos.UserIdentity
         {
             UserId  = user.Id,
             Name    = user.Name,
             Company = user.Company,
             Title   = user.Title,
             Avatar  = user.Avatar
         });
     }
 }
예제 #21
0
        public async Task <IActionResult> CheckOrCreate(string phone)
        {
            if (string.IsNullOrWhiteSpace(phone))
            {
                throw new UserOperationException("系统繁忙");
            }
            var user = await _userContext.Users.SingleOrDefaultAsync(x => x.Phone == phone);

            if (user == null)
            {
                user = new Models.AppUser {
                    Phone = phone
                };
                _userContext.Users.Add(user);
                await _userContext.SaveChangesAsync();
            }
            return(Ok(user.ID));
        }
예제 #22
0
 private void RaiseUserprofileChangedEvent(Models.AppUser appUser)
 {
     if (_userContext.Entry(appUser).Property(nameof(appUser.Name)).IsModified ||
         _userContext.Entry(appUser).Property(nameof(appUser.Title)).IsModified ||
         _userContext.Entry(appUser).Property(nameof(appUser.Company)).IsModified ||
         _userContext.Entry(appUser).Property(nameof(appUser.Avatar)).IsModified)
     {
         //发布
         _capPublisher.Publish("finbook.userapi.user_profile_changed", new UserProfileChangedEvent
         {
             UserId  = appUser.Id,
             Name    = appUser.Name,
             Title   = appUser.Title,
             Company = appUser.Company,
             Avatar  = appUser.Avatar
         });
     }
 }
        private async Task LoadSharedKeyAndQrCodeUriAsync(Models.AppUser user)
        {
            // Load the authenticator key & QR code URI to display on the form
            var unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user);

            if (string.IsNullOrEmpty(unformattedKey))
            {
                await _userManager.ResetAuthenticatorKeyAsync(user);

                unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user);
            }

            SharedKey = FormatKey(unformattedKey);

            var email = await _userManager.GetEmailAsync(user);

            AuthenticatorUri = GenerateQrCodeUri(email, unformattedKey);
        }
예제 #24
0
        public async Task <ActionResult <Models.AppUser> > GetUserByDocumentId(string documentId)
        {
            try
            {
                Models.AppUser user = await _cosmosDBclient.ReadDocumentAsync <Models.AppUser>(UriFactory.CreateDocumentUri(
                                                                                                   _dbName, _collectionName, documentId));

                return(Ok(user));
            }
            catch (DocumentClientException de)
            {
                switch (de.StatusCode.Value)
                {
                case System.Net.HttpStatusCode.NotFound:
                    return(NotFound());
                }
            }
            return(BadRequest());
        }
 public ActionResult Login(Models.AppUser user)
 {
     if (db.LoginValidation(user.UserName, user.PassWord))
     {
         if (user.UserName == "admin")
         {
             return(RedirectToAction("AdminMenu"));
         }
         else
         {
             TempData["ID"] = db.GetUserIDByUserName(user.UserName);
             return(RedirectToAction("UserMenu"));
         }
     }
     else
     {
         ViewBag.Message = "Incorrect User Name or Password, please try again";
         return(View());
     }
 }
예제 #26
0
        public async Task <IActionResult> CheckOrCreate(string phone)
        {
            //TODO:手机格式验证
            var user = await _userContext.Users.SingleOrDefaultAsync(u => u.Tel == phone);

            if (user == null)
            {
                user = new Models.AppUser {
                    Tel = phone
                };
                _userContext.Users.Add(user);
                await _userContext.SaveChangesAsync();
            }

            return(Ok(new {
                user.Id,
                user.Name,
                user.Company,
                user.Title,
                user.Avatar
            }));
        }
예제 #27
0
        public async Task <IActionResult> CheckOrCreate([FromForm] string phone)
        {
            //TBD 做手机号码的格式验证
            var user = _userContext.Users.SingleOrDefault(u => u.Phone == phone);

            if (user == null)
            {
                user = new Models.AppUser {
                    Phone = phone
                };
                _userContext.Users.Add(user);
                await _userContext.SaveChangesAsync();
            }
            return(Ok(new
            {
                user.Id,
                user.Name,
                user.Company,
                user.Title,
                user.Avatar
            }));
        }
예제 #28
0
        public async Task <LoginResultViewModel> Handle(FacebookExternalLoginRequest request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation($"Starting {nameof(FacebookExternalLoginHandler)}");

                var appAccessTokenResponse = await _httpClient.GetStringAsync($"https://graph.facebook.com/oauth/access_token?client_id={_fbAuthSettings.AppId}&client_secret={_fbAuthSettings.AppSecret}&grant_type=client_credentials");

                var appAccessToken = JsonConvert.DeserializeObject <FacebookAppAccessToken>(appAccessTokenResponse);

                var userAccessTokenValidationResponse = await _httpClient.GetStringAsync($"https://graph.facebook.com/debug_token?input_token={request.AccessToken}&access_token={appAccessToken.AccessToken}");

                var userAccessTokenValidation = JsonConvert.DeserializeObject <FacebookUserAccessTokenValidation>(userAccessTokenValidationResponse);

                if (!userAccessTokenValidation.Data.IsValid)
                {
                    throw new ArgumentException("Invalid facebook token.");
                }

                var userInfoResponse = await _httpClient.GetStringAsync($"https://graph.facebook.com/v2.8/me?fields=id,email,first_name,last_name,name&access_token={request.AccessToken}");

                var userInfo = JsonConvert.DeserializeObject <FacebookUserData>(userInfoResponse);

                var user = await _userManager.FindByEmailAsync(userInfo.Email);

                if (user == null)
                {
                    user = new Models.AppUser
                    {
                        Name     = $"{userInfo.FirstName} {userInfo.LastName}",
                        Email    = userInfo.Email,
                        UserName = userInfo.Email,
                    };

                    var result = await _userManager.CreateAsync(user);

                    if (!result.Succeeded)
                    {
                        throw new ArgumentException(string.Join(",", result.Errors));
                    }

                    var externalLoginInfo = new ExternalLoginInfo(
                        null,
                        ExternalLoginProviders.Facebook,
                        $"{userInfo.Id}",
                        userInfo.Name
                        );
                    await _userManager.AddLoginAsync(user, externalLoginInfo);
                }

                var roles = await _userManager.GetRolesAsync(user);

                var accessToken = await _jwtFactory.GenerateEncodedToken(user.UserName, roles);

                _logger.LogInformation($"Finished {nameof(FacebookExternalLoginHandler)}");

                return(new LoginResultViewModel(accessToken, _mapper.Map <AppUserViewModel>(user)));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message, ex);
                throw;
            }
        }
        public async Task <LoginResultViewModel> Handle(GoogleExternalLoginRequest request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation($"Starting {nameof(GoogleExternalLoginHandler)}");

                var url = $"https://www.googleapis.com/oauth2/v4/token?code={request.Code}&client_id={_googleAuthSettings.ClientId}&client_secret={_googleAuthSettings.ClientSecret}&redirect_uri=http://localhost:5000/google-auth.html&grant_type=authorization_code";
                var uri = new Uri(url);
                _httpClient.BaseAddress = uri;
                _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                var req = new HttpRequestMessage(HttpMethod.Post, uri);
                var httpResponseMessage = await _httpClient.SendAsync(req, cancellationToken);

                if (!httpResponseMessage.IsSuccessStatusCode)
                {
                    throw new ArgumentException("Invalid google token.");
                }

                httpResponseMessage.EnsureSuccessStatusCode();
                var httpContent    = httpResponseMessage.Content;
                var responseString = await httpContent.ReadAsStringAsync();

                var resultData = JsonConvert.DeserializeObject <GoogleAppAccessToken>(responseString);

                var userAccessTokenValidationResponse = await _httpClient.GetStringAsync($"https://www.googleapis.com/plus/v1/people/me/openIdConnect?access_token={resultData.AccessToken}");

                var userInfo = JsonConvert.DeserializeObject <GoogleUserData>(userAccessTokenValidationResponse);

                var user = await _userManager.FindByEmailAsync(userInfo.Email);

                if (user == null)
                {
                    user = new Models.AppUser
                    {
                        Name     = $"{userInfo.GivenName} {userInfo.FamilyName}",
                        Email    = userInfo.Email,
                        UserName = userInfo.Email,
                    };

                    var result = await _userManager.CreateAsync(user);

                    if (!result.Succeeded)
                    {
                        throw new ArgumentException(string.Join(",", result.Errors));
                    }

                    var externalLoginInfo = new ExternalLoginInfo(
                        null,
                        ExternalLoginProviders.Google,
                        userInfo.Sub,
                        userInfo.Name
                        );
                    await _userManager.AddLoginAsync(user, externalLoginInfo);
                }

                var roles = await _userManager.GetRolesAsync(user);

                var accessToken = await _jwtFactory.GenerateEncodedToken(user.UserName, roles);

                _logger.LogInformation($"Finished {nameof(GoogleExternalLoginHandler)}");

                return(new LoginResultViewModel(accessToken, _mapper.Map <AppUserViewModel>(user)));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message, ex);
                throw;
            }
        }
예제 #30
0
        public AppUserAddEditForm()
        {
            InitializeComponent();
            this.AcceptButton = this.btnOk;
            this.CancelButton = this.btnCancel;
            this.FormClosed  += (s, e) => {
                //释放 资源
                if (bll != null)
                {
                    bll.Dispose();
                    bll = null;
                }
            };
            //设置dataentity
            this.deMain.FitToParentWidth    = true;
            this.deMain.ShowValidationPanel = true;
            this.deMain.EditorInitializing += (s, e) => {
                e.Editor.Name = e.Property.Name;
                if (e.Property.Name == "UserName" && EditMode == Enums.EditFormMode.Edit)
                {
                    e.Editor.Enabled = false;
                }
                else if (e.Property.Name == "Email")
                {
                    RadMaskedEditBox editor = new RadMaskedEditBox();
                    editor.MaskType = MaskType.EMail;
                    editor.MaskedEditBoxElement.StretchVertically = true;
                    e.Editor = editor;
                }
                //else if (e.Property.Name == "Tel")
                //{
                //    RadMaskedEditBox editor = new RadMaskedEditBox();
                //    editor.MaskType = MaskType.Regex;
                //    editor.MaskedEditBoxElement.StretchVertically = true;
                //    //editor.Mask = "9";
                //    e.Editor = editor;
                //}
            };
            this.deMain.ItemValidating += (s, e) => {
                Models.AppUser user = this.deMain.CurrentObject as Models.AppUser;
                switch (e.Label.Text)
                {
                case "用户名":
                    if (string.IsNullOrWhiteSpace(user.UserName))
                    {
                        string errorMessage = "用户名不能为空!";
                        e.ErrorProvider.SetError(s as Control, errorMessage);
                        e.Cancel = true;
                        AddErrorLabel(this.deMain, e.Label.Text, errorMessage);
                    }
                    else
                    {
                        e.ErrorProvider.Clear();
                        this.deMain.ValidationPanel.PanelContainer.Controls.RemoveByKey(e.Label.Text);
                    }
                    break;

                default:
                    break;
                }
            };

            this.Shown += (s, e) => {
                //设置窗体title
                switch (EditMode)
                {
                case Enums.EditFormMode.Add:
                    this.Text = "新增";
                    DataEntry = new Models.AppUser()
                    {
                        Password = Helpers.EncryptDecryptHelper.GetStringMD5("888888")
                    };                                                                                                   //新增用户默认密码
                    break;

                case Enums.EditFormMode.Edit:
                    this.Text = "编辑";
                    break;

                case Enums.EditFormMode.Delete:
                    this.Text = "删除";
                    break;

                default:
                    this.Text = "新增/编辑";
                    break;
                }
                if (DataEntry != null)
                {
                    this.deMain.DataSource = this.DataEntry;
                }
            };

            this.btnCancel.Click += (s, e) => {
                //this.UserRole.CancelEdit();
                this.DialogResult = DialogResult.Cancel;
            };

            this.btnOk.Click += (s, e) => {
                var t = ValidationHelper.hasValidationErrors(this.deMain.Controls);
                if (t)
                {
                    return;
                }

                this.btnOk.Enabled = false;

                Task.Factory.StartNew <AppUser>(() => {
                    Models.AppUser re = null;
                    if (EditMode == Enums.EditFormMode.Add)
                    {
                        re = bll.Insert <Models.AppUser>(this.DataEntry);
                    }
                    else if (EditMode == Enums.EditFormMode.Edit)
                    {
                        re = bll.Update <Models.AppUser>(this.DataEntry);
                    }


                    return(re);
                }).ContinueWith(tt => {
                    if (!tt.IsFaulted)
                    {
                        syncContext.Post((state) => {
                            Models.AppUser sta = (Models.AppUser)state;
                            if (sta != null)
                            {
                                this.DataEntry    = sta;
                                this.DialogResult = DialogResult.OK;
                                //this.SubmitSucess = true;
                            }
                            else
                            {
                                RadMessageBox.Show(this, "保存失败!", "", MessageBoxButtons.OK, RadMessageIcon.Error);
                            }
                        }, tt.Result);
                    }
                    syncContext.Post((state) => {
                        this.btnOk.Enabled = true;
                    }, tt.Result);
                });
            };
        }