protected void Page_Load(object sender, EventArgs e) { var bll = new BLL.UserComponents(); var user = new Entities.User(); if (Session["UserLogin"] != null) user = bll.GetUser(Session["UserLogin"].ToString()); var test = new BLL.TestComponents().FindTest(Guid.Parse(Request["test"])); var blls = new BLL.StatisticComponents(); var guid = Guid.Parse(Request["stat"]); var stat = new BLL.StatisticComponents().GetTestStatistics().Where(s => s.ID.CompareTo(guid) == 0).First(); foreach (var q in test.Questions) { var temp = stat.CorrectQuestions.Where(s => s.Correct == q.Text); if (temp.Count() > 0) stats.Add(new Tuple<string, string>(q.Text, "Верно")); else stats.Add(new Tuple<string, string>(q.Text, "Неверно")); } RepeaterStats.DataSource = stats; DataBind(); if (Session["IsTrue"] != null) { blls.DeleteStatistic(stat); Session["IsTrue"] = null; } }
public void AssignDataToControls(string profile) { try { SPWeb web = SPContext.Current.Web; BLL.UserBLL userBLL = new CAFAM.WebPortal.BLL.UserBLL(web); UserEntity = userBLL.GetUser(profile); lblFirstName.Text = UserEntity.FirstName; lblSecondName.Text = UserEntity.SecondName; lblFirstSurname.Text = UserEntity.FirstSurname; lblSecondSurname.Text = UserEntity.SecondSurname; lblPosition.Text = UserEntity.Position; txtCompanyEmail.Text = UserEntity.CompanyEmail; WebUI.TelephoneControl telCompany = (WebUI.TelephoneControl)pnlCompanyTel.FindControl("telCompany"); telCompany.Tel = UserEntity.CompanyTel; txtTelExtension.Text = UserEntity.TelExtension; WebUI.TelephoneControl telCompanyMobile = (WebUI.TelephoneControl)pnlCompanyMobile.FindControl("telCompanyMobile"); telCompanyMobile.Tel = UserEntity.CompanyMobile; txtAuthorizedBy.Text = UserEntity.AuthorizedBy; WebUI.DateTimeCustomControl dateTimeCustomControl = (WebUI.DateTimeCustomControl)this.pnlAuthorizationDate.FindControl("dateTimeCustomControl"); if (dateTimeCustomControl != null) { dateTimeCustomControl.Date = UserEntity.BirthDate; } chkAuthorizedToGetBasicData.Checked = UserEntity.AuthorizedToGetBasicData; chkAuthorizedToGetContibutionData.Checked = UserEntity.AuthorizedToGetContibutionData; chkAuthorizedToGetMemberData.Checked = UserEntity.AuthorizedToGetMemberData; } catch (Exception ex) { throw ex; } }
public User CreateByExternalCredentials(string LoginProvider, string ProviderKey, string EmailAddress, string Name) { using (new FunctionLogger(Log)) { Log.InfoFormat("Login Provider: {0}", LoginProvider); Log.InfoFormat("Provider Key: {0}", ProviderKey); Log.InfoFormat("Email Address: {0}", EmailAddress); Log.InfoFormat("Name: {0}", Name); if (EmailAddress == null) { EmailAddress = string.Concat("none.", Guid.NewGuid()); } using (var UnitOfWork = DataAccessFactory.CreateUnitOfWork()) { var UserRepository = DataAccess.DataAccessFactory.CreateRepository<IUserRepository>(UnitOfWork); var UserEntity = UserRepository.GetByExternalCredentials(LoginProvider, ProviderKey); if (UserEntity != null) throw new Exception("External credentials already in use"); UserEntity = new Entities.User(); UserEntity.CurrentExternalCredentialState.Register(EmailAddress, Name); UserEntity.CurrentExternalCredentialState.Link(LoginProvider, ProviderKey, EmailAddress); UserRepository.CascadeInsert(UserEntity); UnitOfWork.Commit(); return Mapper.Map<Entities.User, Dtos.User>(UserEntity); } } }
public void AssignDataToControls(string profile) { try { SPWeb web = SPContext.Current.Web; BLL.UserBLL userBLL = new CAFAM.WebPortal.BLL.UserBLL(web); UserEntity = userBLL.GetUser(profile); lblFirstName.Text = UserEntity.FirstName; lblSecondName.Text = UserEntity.SecondName; lblFirstSurname.Text = UserEntity.FirstSurname; lblSecondSurname.Text = UserEntity.SecondSurname; lblIdentificationType.Text = UserEntity.IdentificationType; lblIdentificationNumber.Text = UserEntity.IdentificationNumber; WebUI.DateTimeCustomControl dateTimeCustomControl = (WebUI.DateTimeCustomControl)this.pnlBirthDate.FindControl("dateTimeCustomControl"); if (dateTimeCustomControl != null) { dateTimeCustomControl.Date = UserEntity.BirthDate; } if(!string.IsNullOrEmpty(UserEntity.MaritalState)) { rdlMaritalState.SelectedValue = UserEntity.MaritalState; } ddlOccupation.SelectedValue = UserEntity.Ocupattion; if (!string.IsNullOrEmpty(UserEntity.CompensationFund)) { ddlCompensationFund.SelectedValue = UserEntity.CompensationFund; } txtCompany.Text = UserEntity.Company; txtPosition.Text = UserEntity.Position; txtPrivateEmail.Text = UserEntity.PrivateEmail; txtCompanyEmail.Text = UserEntity.CompanyEmail; WebUI.TelephoneControl telPrivate = (WebUI.TelephoneControl)pnlPrivateTel.FindControl("telPrivate"); telPrivate.Tel = UserEntity.PrivateTel; WebUI.TelephoneControl telPrivateMobile = (WebUI.TelephoneControl)pnlPrivateMobile.FindControl("telPrivateMobile"); telPrivateMobile.Tel = UserEntity.PrivateMobile; WebUI.TelephoneControl telCompany = (WebUI.TelephoneControl)pnlCompanyTel.FindControl("telCompany"); telCompany.Tel = UserEntity.CompanyTel; txtTelExtension.Text = UserEntity.TelExtension; WebUI.AddressControl address = (WebUI.AddressControl)pnlAddress.FindControl("address"); address.Address = UserEntity.Address; if (!string.IsNullOrEmpty(UserEntity.EPS)) { ddlEPS.SelectedValue = UserEntity.EPS; } if (UserEntity.ChildrenQuantity.HasValue) { txtChildrenQuantity.Text = UserEntity.ChildrenQuantity.ToString(); } if (!string.IsNullOrEmpty(UserEntity.IncomeLevel)) { ddlIncomeLevel.SelectedValue = UserEntity.IncomeLevel; } } catch (Exception ex) { throw ex; } }
protected void Page_Load(object sender, EventArgs e) { if (Request["user"] == null) user = new BLL.UserComponents().GetUser(Session["UserLogin"].ToString()); else user = new BLL.UserComponents().GetUser(Request["user"].ToString()); if (user != null) DataBind(); }
public Entities.User GetProfile(string profile) { Entities.User entitiesUser = new Entities.User(); if (!string.IsNullOrEmpty(profile)) { SPSite site = new SPSite(ConfigurationManager.AppSettings["MOSSSite"]); BLL.UserBLL userBBL = new CAFAM.WebPortal.BLL.UserBLL(site.OpenWeb()); entitiesUser = userBBL.GetUser(profile); } return entitiesUser; }
public static Entities.User CreateUser() { var userNew = new Entities.User(); userNew.Active = true; userNew.Email = CreateEmail(); userNew.Login = RandomString(20, false); userNew.Password = new byte[10]; userNew.Phone = CreateRandomStringNumber(11); userNew.LastLogin = DateTime.Now; userNew.Verified = true; return userNew; }
public virtual Guid RegisterUser(IUserContract userValue) { var userId = Guid.NewGuid(); var passwordInfo = passwordHelper.GetEncryptedPasswordAndSalt(userValue.Password); var user = new Entities.User() { EmailAddress = userValue.EmailAddress, Id = userId, Telephone = userValue.Telephone, FirstName = userValue.FirstName, LastName = userValue.LastName, Password = passwordInfo.EncryptedPassword, PasswordExpirtyDate = DateTime.Now.AddDays(authenticationService.PasswordExpiryDays), PasswordSalt = passwordInfo.Salt, AccountLocked = false, Disabled = false, FailedLoginAttempts = 0 }; this.session.Save(user); return userId; }
/// <summary> /// Action responsible for leaving a game /// </summary> /// <param name="id">The game id to leave</param> /// <param name="playerType">The type of player leaving</param> /// <returns>The view for game listing screen</returns> public ActionResult Index(Int32 id, Entities.Enums.GamePlayerType playerType, Boolean windowUnload = false) { Entities.User user = new Entities.User { UserId = Authentication.Security.CurrentUserId, DisplayName = Authentication.Security.CurrentUserName }; if(windowUnload) { String jobId = BackgroundJob.Schedule(() => _leaveGame.Execute(id, user.UserId, user.DisplayName, playerType), TimeSpan.FromSeconds(20)); String key = String.Format("LeaveGame_{0}_JobId", id); Session.Add(key, MachineKey.Protect(Encoding.ASCII.GetBytes(jobId), Session.SessionID)); } else { _leaveGame.Execute(id, user, playerType); } return Redirect("/GameListing"); }
public void AssignDataToControls(string profile) { try { SPWeb web = SPContext.Current.Web; BLL.UserBLL userBLL = new CAFAM.WebPortal.BLL.UserBLL(web); UserEntity = userBLL.GetUser(profile); lblFirstName.Text = UserEntity.FirstName; lblSecondName.Text = UserEntity.SecondName; lblFirstSurname.Text = UserEntity.FirstSurname; lblSecondSurname.Text = UserEntity.SecondSurname; lblIdentificationType.Text = UserEntity.IdentificationType; lblIdentificationNumber.Text = UserEntity.IdentificationNumber; lblOccupation.Text = UserEntity.Ocupattion; lblCompensationFund.Text = UserEntity.CompensationFund; lblCompany.Text = UserEntity.Company; txtPrivateEmail.Text = UserEntity.PrivateEmail; txtCompanyEmail.Text = UserEntity.CompanyEmail; WebUI.TelephoneControl telPrivate = (WebUI.TelephoneControl)pnlPrivateTel.FindControl("telPrivate"); telPrivate.Tel = UserEntity.PrivateTel; WebUI.TelephoneControl telPrivateMobile = (WebUI.TelephoneControl)pnlPrivateMobile.FindControl("telPrivateMobile"); telPrivateMobile.Tel = UserEntity.PrivateMobile; WebUI.TelephoneControl telCompany = (WebUI.TelephoneControl)pnlCompanyTel.FindControl("telCompany"); telCompany.Tel = UserEntity.CompanyTel; txtTelExtension.Text = UserEntity.TelExtension; WebUI.AddressControl address = (WebUI.AddressControl)pnlAddress.FindControl("address"); address.Address = UserEntity.Address; lblEPS.Text = UserEntity.EPS; } catch (Exception ex) { throw ex; } }
public ActionResult AddUser(string username, string password, string role) { RolesData rolesData = RolesData.GetRolesData(); if (Request.IsAuthenticated) { if(User.IsInRole("admin")) { UserData userData = UserData.GetUserData(); if (!userData.CheckIfExists(username)) { User user = new Entities.User(); user.username = username; PasswordMethods pass = new PasswordMethods(); user.password = pass.Hash(password); userData.AddUser(user); rolesData.AddUser(username, role); TempData["Message"] = "Kullanıcı başarıyla eklendi"; return RedirectToAction("Index","Home"); } else { TempData["Message"] = "Kullanıcı zaten var"; return RedirectToAction("Index","Home"); } } else { TempData["Message"] = "Yeterli yetkiniz yok"; return RedirectToAction("Index", "Home"); } } else { return RedirectToAction("Index", "Home"); } }
public void Handle(byte[] packet, IPEndPoint endPoint) { uint type = packet.ToUShort(0); ushort sessionID = packet.ToUShort(4); Entities.User user = Managers.UserManager.Instance.Get(sessionID); if (user == null) { return; } switch (type) { case 0x1001: //Initial packet packet.WriteUShort((ushort)(this.port + 1), 4); socket.SendTo(packet, endPoint); break; case 0x1010: //UDP Ping packet if (packet[14] == 0x21) { user.LocalEndPoint = packet.ToIPEndPoint(32); user.RemoteEndPoint = endPoint; user.RemotePort = ReversePort(endPoint); user.LocalPort = ReversePort(user.LocalEndPoint); byte[] response = packet.Extend(65); #region old response bytes /* * byte[] response = new byte[65] * { * 0x10, 0x10, //0 * 0x0, 0x0, //2 * 0x0, 0x0, //4 * 0xFF, 0xFF, 0xFF, 0xFF, //6 * 0x0, 0x0, 0x0, 0x0, //10 * 0x21, 0x0, 0x0, 0x41, //14 * 0x0, 0x0, 0x0, 0x0, //18 * 0x0, 0x0, 0x0, 0x0, //22 * 0x0, 0x0, //26 * 0x1, 0x11, 0x13, 0x11, //28 * 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, //32 remoteip * 0x11, 0x11, 0x11, 0x11, //38 * 0x11, 0x11, 0x11, 0x11, //42 * 0x01, 0x11, 0x13, 0x11, //48 * 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, //50 localip * 0x19, 0x19, 0x19, 0x19, //56 * 0x19, 0x19, 0x19, 0x19, //60 * 0x11 //64 * }; */ #endregion response[17] = 0x41; response[response.Length - 1] = 0x11; response.WriteUShort((ushort)user.SessionID, 4); //Not really necessary response.WriteIPEndPoint(user.RemoteEndPoint, 32); response.WriteIPEndPoint(user.LocalEndPoint, 50); socket.SendTo(response, endPoint); } else if (packet[14] == 0x31) { //if (user.CurrentRoom == null) return; //uint room = packet.ToUShort(6); //if (user.CurrentRoom.ID == room) { // ushort targetID = packet.ToUShort(22); // Player target = PlayerManager.GetUser(targetID); // if (target != null) { // _server.SendTo(packet, target.RemoteEP); // } else { // Log.Instance.WriteLine("UDP TUNNEL PACKET FAULT - TARGET DOES NOT EXIST"); // Log.Instance.WriteLine("Press enter to continue..."); // Console.ReadLine(); // } //} else { // Log.Instance.WriteLine("UDP TUNNEL PACKET FAULTY - ROOM DID NOT MATCH SENDER"); // Log.Instance.WriteLine("Press enter to continue..."); // Console.ReadLine(); //} } else { Log.Instance.WriteError("UNHANDLED UDP SUB PACKET " + packet[14].ToString()); } break; default: Log.Instance.WriteError("Unhandled UDP Packet " + type); break; } }
public static void CreateUser(string userName, string email) { using (var context = DataContext.GetContext()) { var aspNetUser = context.aspnet_Users.Single(a => a.UserName == userName); var newUser = new Entities.User { aspNetUserId = aspNetUser.Id, Email = email, CreatedOn = DateTime.Now, LastModifiedOn = DateTime.Now }; context.Users.AddObject(newUser); newUser.CreatedBy = newUser.UserId; newUser.LastModifiedBy = newUser.UserId; context.SaveChanges(); } }
public async Task <LoginResult> PerfromExternalLogin() { var info = await signin_manager.GetExternalLoginInfoAsync(); if (info == null) { throw new UnauthorizedAccessException(); } // Check if the login is known in our database var user = await user_manager.FindByLoginAsync(info.LoginProvider, info.ProviderKey); if (user == null) { string username = info.Principal.FindFirstValue(ClaimTypes.Name); string email = info.Principal.FindFirstValue(ClaimTypes.Email); var new_user = new Entities.User { UserName = username, Email = email, PictureUrl = null }; var id_result = await user_manager.CreateAsync(new_user); if (id_result.Succeeded) { user = new_user; } else { // User creation failed, probably because the email address is already present in the database if (id_result.Errors.Any(e => e.Code == "DuplicateEmail")) { var existing = await user_manager.FindByEmailAsync(email); var existing_logins = await user_manager.GetLoginsAsync(existing); if (existing_logins.Any()) { throw new OtherAccountException(existing_logins); } else { throw new Exception("Could not create account from social profile"); } } else { throw new Exception("Could not create account from social profile"); } } await user_manager.AddLoginAsync(user, new UserLoginInfo(info.LoginProvider, info.ProviderKey, info.ProviderDisplayName)); } await signin_manager.SignInAsync(user, true); return(new LoginResult { Status = true, Platform = info.LoginProvider, User = ToDto(user) }); }
public abstract void Process(Entities.User Caster);
public ActionResult ExternalLoginConfirmation(Authentication.Models.Account.RegisterExternalLogin model) { string provider = null; string providerUserId = null; if (User.Identity.IsAuthenticated || !Authentication.OAuthSecurity.TryDeserializeProviderUserId(model.ExternalLoginData, out provider, out providerUserId)) { return RedirectToAction("Manage"); } if (ModelState.IsValid) { Entities.User user = new Entities.User { DisplayName = model.UserName, PictureUrl = String.Format("/Account/Image?hash={0}", HttpUtility.UrlEncode(Library.Helpers.EncryptUtil.Encrypt(CalculateMD5Hash(model.UserEmail)))) }; // Insert name into the profile table _insertUser.Execute(user); // Check if user already exists if (user.UserId > 0) { Authentication.OAuthSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName); Authentication.OAuthSecurity.Login(provider, providerUserId, createPersistentCookie: false); return RedirectToLocal(model.ReturnUrl); } else { ModelState.AddModelError("UserName", "User name already exists. Please enter a different user name."); } } return View(model); }
public string ClientRegister(Entities.User user) { return(_service.ClientRegister(user)); }
public async Task <Models.RegistrationResponse> RegisterUserAsync(Register register) { List <string> passwordErrors = new List <string>(); var validators = user_manager.PasswordValidators; foreach (var validator in validators) { var result = await validator.ValidateAsync(user_manager, null, register.Password); if (!result.Succeeded) { foreach (var error in result.Errors) { passwordErrors.Add(error.Description); } return(new RegistrationResponse() { Success = false, Error = new ApiError() { Message = "Cannot register user", Detail = "Password is invalid", Code = (int)ServerResponse.ErrorCodes.PASSWORD_INVALID }, PasswordValidationErrors = new Models.standard.Collection <string>() { values = passwordErrors.ToArray() } }); } } var user = new Entities.User { Forename = register.Forename, UserName = register.Username, Surname = register.Surname }; Task <IdentityResult> t = user_manager.CreateAsync(user, register.Password); t.Wait(); if (!t.Result.Succeeded) { return(new RegistrationResponse() { Success = false, Error = new ApiError() { Message = "Cannot register user", Detail = "There was a problem", Code = (int)ServerResponse.ErrorCodes.REGISTRATION_ERROR } }); } //put the user in the role await user_manager.AddToRoleAsync(user, register.Role); await user_manager.UpdateAsync(user); return(new RegistrationResponse() { Success = true }); }
//public User GetClassroomDetailsInvitation(string userId) //{ // var educatorusers = _context.Users.Include(c => c.EducatorDetails) // .FirstOrDefault(c => c.Id == userId).EducatorDetails; // return educatorusers.Classrooms.; // //return _context.Users.Include(c => c.EducatorDetails) // // .Where(c => c.Id == userId).FirstOrDefault(); //} public void AddUser(Entities.User user) { _context.Users.Add(user); }
public Entities.User Update(Entities.User user) { return(base.Channel.Update(user)); }
public System.Threading.Tasks.Task <Entities.User> UpdateAsync(Entities.User user) { return(base.Channel.UpdateAsync(user)); }
public Entities.User Add(Entities.User user) { return(base.Channel.Add(user)); }
public System.Threading.Tasks.Task <Entities.User> CheckUserAsync(Entities.User user) { return(base.Channel.CheckUserAsync(user)); }
public Entities.User CheckUser(Entities.User user) { return(base.Channel.CheckUser(user)); }
protected void ibtnCheckEMail_Click(object sender, EventArgs e) { try { string sEMail = txtEMail.Text.Trim().ToLower(); BLL.UserBLL userBLL = new CAFAM.WebPortal.BLL.UserBLL(SPContext.Current.Web); Entities.User FoundUser = userBLL.GetUserByPrivateEmail(sEMail); if (FoundUser != null) { UserEntity = FoundUser; pnlSecretQuestion.Visible = true; lblSecretQuestion.Text = FoundUser.SecurityQuestion; lblMessage.Text = "Ingrese la respuesta"; txtEMail.Enabled = false; ibtnCheckEMail.Enabled = false; } else { lblMessage.Text = "El correo electrónico ingresado no se encuentra en el sistema"; } } catch (Exception Ex) { CAFAM.WebPortal.ErrorLogger.ErrorLogger.Log(Ex, ref lblMessage, ConfigurationSettings.AppSettings["LogInEventViewer"]); } }
private void CreateUser(string personType) { var userBiz = _container.Resolve<Business.IUser>(); Entities.User user = new Entities.User(); user.Andresses.Add(CreateAndress(user)); user.Email = txtEmail.Text; user.Login = txtLogin.Text; user.Password = Infrastructure.Encrypt.HashText(txtPassword.Text); user.Phone = txtPhoneAreaCode.Text + txtPhone.Text; user.Phone = txtMobilePhoneAreaCode.Text + txtMobilePhone.Text; if (personType.Equals("physical")) user.PhysicalPerson = CreatePhysicalPerson(user); else user.LegalPerson = CreateLegalPerson(user); userBiz.Save(user, true); }
public void StartGame(Int32 gameID) { AS.Game.Base.IStart _startGame = BusinessLogic.UnityConfig.Container.Resolve<AS.Game.Base.IStart>(); Entities.User user = new Entities.User { UserId = Authentication.Security.CurrentUserId, DisplayName = Authentication.Security.CurrentUserName }; _startGame.Execute(gameID, user); }
public abstract void New(Entities.User user);
protected void btnSave_Click(object sender, EventArgs e) { this.lblMessage.Text = ""; if (this.txtConfirmPassword.Text != this.txtPassword.Text) { this.lblMessage.Text = "密码不匹配,请确认!"; return; } if (this.lblId.Text == "") { if (this.txtPassword.Text == "") { this.lblMessage.Text = "新建用户,必须输入密码!"; return; } } JMReports.Entities.User user1 = new Entities.User(); user1.UserId = this.txtUserId.Text.Trim(); user1.RoleId = int.Parse(this.ddlRole.SelectedItem.Value); user1.Title = this.txtTitle.Text.Trim(); user1.Email = this.txtEmail.Text.Trim(); user1.Psd = this.txtPassword.Text.Trim(); Business.UserComponent uc = new UserComponent(); if (this.lblId.Text == "") { user1 = uc.Create(user1); if (user1.Id != 0) { this.lblMessage.Text = "用户新增成功!"; getUsers(); this.txtUserId.Text = ""; this.txtEmail.Text = ""; this.txtTitle.Text = ""; this.txtPassword.Text = ""; this.txtConfirmPassword.Text = ""; this.ddlRole.SelectedValue = ""; this.lblId.Text = ""; } } else { user1.Id = int.Parse(this.lblId.Text); int i = uc.Update(user1); if (i > 0) { this.lblMessage.Text = "用户修改成功!"; getUsers(); this.txtUserId.Text = ""; this.txtEmail.Text = ""; this.txtTitle.Text = ""; this.txtPassword.Text = ""; this.txtConfirmPassword.Text = ""; this.ddlRole.SelectedValue = ""; this.lblId.Text = ""; } } }
public abstract void Delete(Entities.User user);
public HttpResponseMessage Register(HttpRequestMessage request, RestaurantUserAddressViewModel restaurantuseraddressvm) { return(CreateHttpResponse(request, () => { HttpResponseMessage response = null; UserViewModel uservm = new UserViewModel(); if (!ModelState.IsValid) { // response = request.CreateResponse(HttpStatusCode.BadRequest, new { success = false }); response = request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); } else { if (restaurantuseraddressvm.RestaurantUserVM != null) { var existingUser = _userRepository.GetSingleByUsername(restaurantuseraddressvm.RestaurantUserVM.Username); if (existingUser != null) { //throw new Exception("Username is already in use"); // ModelState.AddModelError("Invalid user", "Email or User number already exists"); //response = request.CreateResponse(HttpStatusCode.BadRequest, //ModelState.Keys.SelectMany(k => ModelState[k].Errors) // .Select(m => m.ErrorMessage).ToArray()); response = request.CreateErrorResponse(HttpStatusCode.Ambiguous, "Email or User number already exists"); } else { //Add Address details Address newaddress = new Address(); Restaurant newRestaurant = new Restaurant(); RestaurantAddress newrestaurantAddress = new RestaurantAddress(); UserRestaurant newuserestaurant = new UserRestaurant(); //Note : - //Username --> Email Entities.User _user = _membershipService.CreateUser(restaurantuseraddressvm.RestaurantUserVM.Username, restaurantuseraddressvm.RestaurantUserVM.Username, restaurantuseraddressvm.RestaurantUserVM.Password, new int[] { 1 }); newRestaurant.UpdateRestaurant(restaurantuseraddressvm, _user.ID); _restaurant.Add(newRestaurant); _unitOfWork.Commit(); newuserestaurant.RestaurantId = newRestaurant.ID; newuserestaurant.UserId = _user.ID; _userrestaurant.Add(newuserestaurant); _unitOfWork.Commit(); //// Update view model //customer = Mapper.Map<Customer, CustomerViewModel>(newCustomer); //response = request.CreateResponse<CustomerViewModel>(HttpStatusCode.Created, customer); foreach (var restaurantAddress in restaurantuseraddressvm.RestaurantAddressVM) { newaddress.UpdateAddress(restaurantAddress, restaurantuseraddressvm.RestaurantUserVM.Username, _user.ID); _address.Add(newaddress); _unitOfWork.Commit(); newrestaurantAddress.RestaurantId = newRestaurant.ID; newrestaurantAddress.AddressId = newaddress.ID; _restaurantaddress.Add(newrestaurantAddress); _unitOfWork.Commit(); //int i = restaurantuseraddressvm.PlanID; Subscription newsubscription = new Subscription(); newsubscription.SubscriptionPlanId = 1003; newsubscription.StartDate = DateTime.UtcNow; newsubscription.TrialStartDate = DateTime.UtcNow; newsubscription.EndDate = GetPlanIntervalEnddate(1003); newsubscription.EndDate = GetPlanIntervalEnddate(1003); newsubscription.RestaurantId = newRestaurant.ID; newsubscription.TransId = ""; newsubscription.Status = true; _subscriptionRepository.Add(newsubscription); _unitOfWork.Commit(); } if (_user != null) { uservm = Mapper.Map <User, UserViewModel>(_user); response = request.CreateResponse <UserViewModel>(HttpStatusCode.OK, uservm); // response = request.CreateResponse(HttpStatusCode.OK, new { success = true }); } else { response = request.CreateErrorResponse(HttpStatusCode.BadRequest, "Registration failed. Try again."); } } } //restaurantuseraddressvm.RestaurantUserVM.Add(uservm); // response = request.CreateResponse<RestaurantUserAddressViewModel>(HttpStatusCode.OK, restaurantuseraddressvm); // response = request.CreateResponse(HttpStatusCode.OK, new { success = true }); } return response; })); }
public abstract void GetAll(Entities.User user);
public bool IsRepositoryValid(Entities.User user, IUserRepository userRepository) { Validate(user, new CreateUserRepositoryValidation(userRepository)); return(Valid); }
/// <summary> /// Este metodo elimina un usuario de la base de datos /// </summary> /// <param name="id">id del usuario que se desea eliminar</param> /// <returns>Retorna el usuario modificado con sus respectivos datos</returns> public void Delete(int id) { Entities.User user = _context.User.FirstOrDefault(u => u.Id == id); _context.User.Remove(user); _context.SaveChanges(); }
public List <collectionPoint> getCollectionPointTime(Entities.User u) { return(df.getCollectionPointTime(u)); }
public Entities.User Get(Guid id) { Entities.User userModel = _userRepository.FindById(id); return(userModel); }
public bool Add(Entities.User u) { if (Players.Count < MaximumPlayers && !UserLimit) { if (isClanWar && u.ClanRank < 1) { return(false); } lock (_playerLock) { Team targetTeam = Team.Derbaran; byte startScanIndex = 0; byte endScanIndex = (byte)(MaximumPlayers / 2); var debTeam = Players.Select(n => n.Value).Where(n => n.Team == Team.Derbaran).Count(); var niuTeam = Players.Select(n => n.Value).Where(n => n.Team == Team.NIU).Count(); if (debTeam > niuTeam) { targetTeam = Team.NIU; startScanIndex = (byte)(MaximumPlayers / 2); endScanIndex = MaximumPlayers; } for (byte i = startScanIndex; i < endScanIndex; i++) { if (!Players.ContainsKey(i)) { Player plr = new Player(i, u, targetTeam); // Send Room // if (Players.Count > 0) { Send((new Packets.RoomPlayers(new ArrayList() { plr }).BuildEncrypted())); } else { Master = i; } // Add Player Players.TryAdd(i, plr); u.SetRoom(this, i); // Send Join Packet // u.Send(new Packets.RoomJoin(i, this)); u.Send(new Packets.RoomPlayers(new ArrayList(Players.Select(n => n.Value).Where(n => n.Id != i).ToArray()))); // Send to all spectators foreach (Entities.User Spectator in Spectators.Values) { u.Send(new Packets.RoomPlayers(new ArrayList(Players.Select(n => n.Value).Where(n => n.Id != i).ToArray()))); } //Tell de players if (State == RoomState.Playing) { string _message = Cristina.Core.Cristina.Localization.GetLocMessageFrom("PLAYER_JOINED_GAME"); if (_message.Contains("%/nickname/%")) { _message = _message.Replace("%/nickname/%", u.Displayname); } Cristina.Core.Cristina.Chat.SaytoRoom(_message, this); //Cristina.Core.Cristina.Chat.SaytoRoom(u.Displayname + " se ha conectado", this); } // SEND THE ROOM UPDATE TO THE LOBBY // byte roomPage = (byte)Math.Floor((decimal)(this.ID / 8)); var targetList = Managers.ChannelManager.Instance.Get(this.Channel).Users.Select(n => n.Value).Where(n => n.RoomListPage == roomPage && n.Room == null); if (targetList.Count() > 0) { byte[] outBuffer = new Packets.RoomUpdate(this, true).BuildEncrypted(); foreach (Entities.User usr in targetList) { usr.Send(outBuffer); } } return(true); } } } } return(false); }
public bool Save(Entities.User user) { return(_userRepository.SaveUser(user)); }
public Entities.User GetUser(UserProfile uProfile) { try { Entities.User user = new Entities.User(); user.CreationDate = GetPropertyValueDateTime(uProfile["CreationDate"].Value); user.UserName = GetPropertyValueString(uProfile["AccountName"].Value); try { user.UserType = (Entities.EnumUserType)Enum.Parse(typeof(Entities.EnumUserType), GetPropertyValueString(uProfile["UserType"].Value)); } catch { throw new Exception("No valid usertype defined in User Profile"); } user.FirstName = GetPropertyValueString(uProfile["FirstName"].Value); user.SecondName = GetPropertyValueString(uProfile["SecondName"].Value); user.FirstSurname = GetPropertyValueString(uProfile["FirstSurname"].Value); user.SecondSurname = GetPropertyValueString(uProfile["SecondSurname"].Value); user.IdentificationType = GetPropertyValueString(uProfile["IdentificationType"].Value); user.IdentificationNumber = GetPropertyValueString(uProfile["IdentificationNumber"].Value); user.NIT = GetPropertyValueString(uProfile["NIT"].Value); user.SubNIT = GetPropertyValueString(uProfile["SubNIT"].Value); user.Audience = GetPropertyValueString(uProfile["Audience"].Value); user.TradeName = GetPropertyValueString(uProfile["TradeName"].Value); user.BirthDate = GetPropertyValueDateTime(uProfile["BirthDate"].Value); user.MaritalState = GetPropertyValueString(uProfile["MaritalState"].Value); user.Ocupattion = GetPropertyValueString(uProfile["Ocupattion"].Value); user.CompensationFund = GetPropertyValueString(uProfile["CompensationFund"].Value); user.Company = GetPropertyValueString(uProfile["Company"].Value); user.Position = GetPropertyValueString(uProfile["Position"].Value); user.PrivateEmail = GetPropertyValueString(uProfile["PrivateEmail"].Value); user.CompanyEmail = GetPropertyValueString(uProfile["CompanyEmail"].Value); user.PrivateTel = GetPropertyValueString(uProfile["PrivateTel"].Value); user.PrivateMobile = GetPropertyValueString(uProfile["PrivateMobile"].Value); user.CompanyMobile = GetPropertyValueString(uProfile["CompanyMobile"].Value); user.CompanyTel = GetPropertyValueString(uProfile["CompanyTel"].Value); user.TelExtension = GetPropertyValueString(uProfile["TelExtension"].Value); user.Address.AddressCombo1 = GetPropertyValueString(uProfile["AddressCombo1"].Value); user.Address.AddressCombo2 = GetPropertyValueString(uProfile["AddressCombo2"].Value); user.Address.AddressCombo3 = GetPropertyValueString(uProfile["AddressCombo3"].Value); user.Address.AddressCombo4 = GetPropertyValueString(uProfile["AddressCombo4"].Value); user.Address.AddressCombo5 = GetPropertyValueString(uProfile["AddressCombo5"].Value); user.Address.AddressCombo6 = GetPropertyValueString(uProfile["AddressCombo6"].Value); user.Address.AddressText1 = GetPropertyValueString(uProfile["AddressText1"].Value); user.Address.AddressText2 = GetPropertyValueInt(uProfile["AddressText2"].Value); user.Address.AddressText3 = GetPropertyValueString(uProfile["AddressText3"].Value); user.Address.AddressText4 = GetPropertyValueString(uProfile["AddressText4"].Value); user.Address.AddressText5 = GetPropertyValueString(uProfile["AddressText5"].Value); user.EPS = GetPropertyValueString(uProfile["EPS"].Value); user.ChildrenQuantity = GetPropertyValueInt(uProfile["ChildrenQuantity"].Value); user.IncomeLevel = GetPropertyValueString(uProfile["IncomeLevel"].Value); user.PersonalManager = GetPropertyValueString(uProfile["PersonalManager"].Value); user.TopicOfInterest.MarketSales = GetProperyValueBool(uProfile["MarketSales"].Value); user.TopicOfInterest.Recreation = GetProperyValueBool(uProfile["Recreation"].Value); user.TopicOfInterest.Education = GetProperyValueBool(uProfile["Education"].Value); user.TopicOfInterest.Home = GetProperyValueBool(uProfile["Home"].Value); user.TopicOfInterest.Health = GetProperyValueBool(uProfile["Health"].Value); user.TopicOfInterest.Subsidy = GetProperyValueBool(uProfile["Subsidy"].Value); user.TopicOfInterest.Credits = GetProperyValueBool(uProfile["Credits"].Value); user.AuthorizedBy = GetPropertyValueString(uProfile["AuthorizedBy"].Value); user.AuthorizationDate = GetPropertyValueDateTime(uProfile["AuthorizationDate"].Value); user.AuthorizedToGetBasicData = GetProperyValueBool(uProfile["AuthorizedToGetBasicData"].Value); user.AuthorizedToGetContibutionData = GetProperyValueBool(uProfile["AuthorizedToGetContibutionData"].Value); user.AuthorizedToGetMemberData = GetProperyValueBool(uProfile["AuthorizedToGetMemberData"].Value); user.SecurityAnswer = GetPropertyValueString(uProfile["SecurityAnswer"].Value); user.SecurityQuestion = GetPropertyValueString(uProfile["SecurityQuestion"].Value); return user; } catch (Exception ex) { throw ex; } }
public void Remove(Entities.User u) { if (u.Room != null) { if (u.Room.ID == this.ID) { lock (this.RoomLock) { Player p; byte oldSlot = 0; lock (_playerLock) { if (Players.ContainsKey(u.RoomSlot)) { Players.TryRemove(u.RoomSlot, out p); if (p != null) { oldSlot = u.RoomSlot; p.User.SetRoom(null, 0); } else { u.SetRoom(null, 0); } if (Players.Count > 0) { // Asign new master // if (oldSlot == Master) { // Remove the suppermaster buff :) this.Supermaster = false; // Calculate the priority level. int[] priority = new int[MaximumPlayers]; for (byte i = 0; i < MaximumPlayers; i++) { if (Players.ContainsKey(i)) { if (Players[i] != null) { priority[i] = 1 + (int)Players[i].User.Premium; } else { priority[i] = 0; // no priority. } } else { priority[i] = 0; // no priority. } } // Find the new master. sbyte newMaster = -1; int masterPrior = 0; for (byte j = 0; j < MaximumPlayers; j++) { if (priority[j] > masterPrior) // A player with higher piority has been found. { newMaster = (sbyte)j; // set the master slot masterPrior = priority[j]; // store the piority. } } // We have found a new master! if (newMaster >= 0) { Master = (byte)newMaster; Players[Master].Ready = true; } else { Destroy(); } } } else { Destroy(); } byte[] pBuffer = new Packets.RoomLeave(u, oldSlot, this).BuildEncrypted(); if (Players.Count > 0) { Send(pBuffer); } u.Send(pBuffer); //tell the players if (State == RoomState.Playing) { string _playerLeft = Cristina.Core.Cristina.Localization.GetLocMessageFrom("PLAYER_LEFT_GAME"); if (_playerLeft.Contains("%/nickname/%")) { _playerLeft = _playerLeft.Replace("%/nickname/%", u.Displayname); } Cristina.Core.Cristina.Chat.SaytoRoom(_playerLeft, this); //Cristina.Core.Cristina.Chat.SaytoRoom(u.Displayname + " ha salido de la sala", this); } } } } } } }
public EmailUtils(Entities.User activeUser) { _activeUser = activeUser; }
public async Task <IdentityResult> CreateRoleForUserAsync(Entities.User user, Role role) { return(await this._userManager.AddToRoleAsync(user, role.ToString())); }
public override void OnActionExecuting(ActionExecutingContext context) { base.OnActionExecuting(context); string scheme = HttpContext.Request.Scheme; string host = HttpContext.Request.Host.Value; string path = HttpContext.Request.Path; string queryString = HttpContext.Request.QueryString.HasValue ? HttpContext.Request.QueryString.Value : ""; string url = $"{scheme}://{host}{path}{queryString}"; logger.Info($"Request: {url}"); string item = Settings.List("UrlWhitelist").Where(x => x == path).FirstOrDefault(); if (item != null) { return; } Entities.User user = Session.Get <Entities.User>(Keys.SessionUser); if (user == null) { logger.Info($"User is null with session id {Session.Id}"); Session.Clear(); if (Settings.GetBool("ThrowsOnAccessDenied")) { logger.Warn($"Access denied for resource {path}"); Trace.Write(new TraceItem() { Error = Messages.AccessDenied }, context.HttpContext); throw new SecurityException(Messages.AccessDenied); } else { logger.Warn($"Access denied for resource {path}"); Trace.Write(new TraceItem() { Error = Messages.AccessDenied }, context.HttpContext); ErrorMessage = Messages.AccessDenied; Redirect(Settings.Get("RedirectPathOnAccessDenied")); } } else { bool canAccess = Business.Authorization.CanAccess(path, user); logger.Info($"User {user.Username} can access path {path}: {canAccess}"); if (!canAccess) { Session.Clear(); if (Settings.GetBool("ThrowsOnAuthorizationFailed")) { logger.Warn($"Access denied for resource {path}"); Trace.Write(new TraceItem() { Error = Messages.AuthorizationFailed }, context.HttpContext); throw new SecurityException(Messages.AuthorizationFailed); } else { ErrorMessage = Messages.AuthorizationFailed; logger.Warn($"Access denied for resource {path}"); Trace.Write(new TraceItem() { Error = Messages.AuthorizationFailed }, context.HttpContext); Redirect(Settings.Get("RedirectPathOnAccessDenied")); } } else { Context.Current.User = user; if (Business.Authorization.RequireToken(path)) { string tokenValue = CurrentHttpContext.Request.Query["t"]; logger.Info($"Token: {tokenValue}"); if (!Business.Authorization.IsValid(user.Id, CurrentHttpContext.Session.Id, tokenValue)) { if (Settings.GetBool("ThrowsOnAuthorizationFailed")) { logger.Warn($"Access denied for resource {path}"); Trace.Write(new TraceItem() { Error = Messages.AuthorizationFailed }, context.HttpContext); throw new SecurityException(Messages.TokenMissing); } else { logger.Warn($"Access denied for resource {path}"); Trace.Write(new TraceItem() { Error = Messages.AuthorizationFailed }, context.HttpContext); ErrorMessage = Messages.AuthorizationFailed; Redirect(Settings.Get("RedirectPathOnAccessDenied")); } } } } } }
public async Task <string> GetRoleOfUserAsync(Entities.User user) { var roles = await this._userManager.GetRolesAsync(user); return(roles.FirstOrDefault()); }
public Entities.User UserAuthenticationDB(int userID) { Entities.User user = null; try { using (SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["LoginDb"].ConnectionString)) { SqlCommand cmd = new SqlCommand("GetUserAuth", con); cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@userID", userID); con.Open(); SqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { user = new Entities.User( userID, dr["Login"].ToString(), dr["UserName"].ToString(), dr["Status"].ToString(), dr["RoleName"].ToString().Trim(), Convert.ToBoolean(dr["ConfirmRegistration"]) ); } } } catch (Exception e) { ErrorDAL.AddNewError(DateTime.Now, e.ToString(), ""); throw new Exception("Oшибка данных"); } return user; }
public List <Role> GetRolesForUser(Entities.User pUser) { return(GetRolesForUserName(pUser.Name)); }
/// <summary> /// Authenticates and returns the user with the given credentials. /// </summary> /// <param name="username">The username</param> /// <param name="password">The password</param> /// <returns>If the user was successfully authenticated</returns> public bool Authenticate(string username, string password) { var user = new Entities.User(); return UserManager.Find(username, password) != null; }
protected override void Process(Entities.User user) { string inputUserName = GetString(2); string inputPassword = GetString(3); bool forceDisconnect = true; //valid UserName? if (inputUserName.Length >= 3 && Core.Constants.isAlphaNumeric(inputUserName)) { //is password long enough? if (inputPassword.Length >= 3) { MySqlDataReader reader = Databases.Auth.Select( new string[] { "id", "username", "status", "displayname", "password", "passwordsalt" }, "users", new Dictionary <string, object>() { { "username", inputUserName } }); //Does the username exists? if (reader.HasRows && reader.Read()) { //The user does exist: retrieve data uint id = reader.GetUInt32(0); string dbUserName = inputUserName; byte status = reader.GetByte(2); //0 = global network account ban string displayname = reader.GetString(3); string dbPassword = reader.GetString(4); string dbPasswordSalt = reader.GetString(5); //We hash password typed by the player and check it against the one stored in the DB string hashedPassword = Core.Constants.GenerateSHAHash(String.Concat(inputPassword, dbPasswordSalt)); //CHECK!! Proceed if (hashedPassword == dbPassword.ToLower()) { var IsOnline = Managers.SessionManager.Instance.Sessions.Select(n => n.Value).Where(n => n.ID == id && n.IsActivated && !n.IsEnded).Count(); //Check to see if the same account is already logged in //TODO: Improve this. What if a GameServer does not update this? if (IsOnline == 0) { if (status > 0) { user.OnAuthorize(id, dbUserName, displayname, status); user.Send(new Packets.ServerList(user)); } else { user.Send(new Packets.ServerList(Packets.ServerList.ErrorCodes.Banned)); } } else { user.Send(new Packets.ServerList(Packets.ServerList.ErrorCodes.AlreadyLoggedIn)); } } else { user.Send(new Packets.ServerList(Packets.ServerList.ErrorCodes.WrongPW)); } } else { user.Send(new Packets.ServerList(Packets.ServerList.ErrorCodes.WrongUser)); } if (!reader.IsClosed) { reader.Close(); } } else { user.Send(new Packets.ServerList(Packets.ServerList.ErrorCodes.EnterPasswordError)); } } else { user.Send(new Packets.ServerList(Packets.ServerList.ErrorCodes.EnterIDError)); } if (forceDisconnect) { user.Disconnect(); } }
public Guid RegistrationInitiate(string EmailAddress, string Password, string Firstname, string Surname, bool AssumeSent) { using (new FunctionLogger(Log)) { if (EmailAddressIsFree(EmailAddress) == false) throw new EmailAddressDuplicationException(EmailAddress); if (EmailAddressPassesValidation(EmailAddress) == false) throw new EmailAddressValidationException(EmailAddress); if (PasswordPassesValidation(Password) == false) throw new PasswordValidationException(); using (var UnitOfWork = DataAccessFactory.CreateUnitOfWork()) { var UserRepository = DataAccessFactory.CreateRepository<IUserRepository>(UnitOfWork); var UserEntity = new Entities.User() { Id = Guid.NewGuid(), CreatedUtc = DateTime.UtcNow }; Guid ConfirmationId = ConfirmationService.QueueConfirmation(UnitOfWork, REGISTRATION, UserEntity.Id, EmailAddress, AssumeSent); UserEntity.CurrentLocalCredentialState.InitiateRegistration(EmailAddress, Password, Firstname, Surname); UserRepository.CascadeInsert(UserEntity); UnitOfWork.Commit(); return ConfirmationId; } } }
public UserWithRoles UpdateUser(Entities.User user, string username, string email) { throw new NotImplementedException(); }
public async Task <IdentityResult> CreateNewUserAsync(Entities.User user) { return(await this._userManager.CreateAsync(user)); }
public bool Validate(Entities.User data) { //Aqui deberia ir el codigo para realizar las validaciones correspondientes return(true); }