public UserDataContract GetActiveUser(int userID) { UserDataContract user = new UserDataContract(); using (var loyalkeyDB = new LoyalKeyDB.LoyalKeyDBEntities()) { try { LoyalKeyDB.User userDB = loyalkeyDB.Users.Where(u => u.UserID == userID && u.IsActive == true).FirstOrDefault(); user.UserID = userDB.UserID; user.CompanyID = userDB.CompanyID == null ? -1 : userDB.CompanyID.Value; user.BassCode = userDB.BassCode; user.Identifier = userDB.Identifier; user.IsActive = userDB.IsActive; } catch { user.UserID = -1; user.CompanyID = -1; user.BassCode = -1; user.Identifier = ""; user.IsActive = false; } } return(user); }
public async Task <IActionResult> CreateUser([FromBody] UserDataContract user) { if (ModelState.IsValid) { if (user == null) { return(BadRequest($"{nameof(user)} cannot be null")); } ApplicationUser appUser = _mapper.Map <ApplicationUser>(user); var result = await _accountManager.CreateUserAsync(appUser, user.RoleIds, user.NewPassword); if (result.Succeeded) { UserDataContract newUser = await GetUserFromDatabase(appUser.Id); return(Ok(newUser)); } AddError(result.Errors); } return(BadRequest(ModelState)); }
static void Main(string[] args) { WCFServiceClient proxy = new WCFServiceClient("BasicHttpBinding_IWCFService"); Console.WriteLine("Test call service using HTTP--------------------."); //实例化数据契约对象,设置信息 UserDataContract user = new UserDataContract(); user.UserName = "******"; user.UserEmail = "WCF Client: [email protected] "; user.Mobile = "WCF Client:1666666666"; proxy.AddNewUser(user); string name = "WCF Client: Frank Xu"; UserDataContract user1 = proxy.GetUserByName(name); if (user1 != null) { Console.WriteLine(user1.UserName); Console.WriteLine(user1.UserEmail); Console.WriteLine(user1.Mobile); } //Debuging Console.WriteLine("Press any key to continue"); Console.Read(); }
private void BackAuthDoWork(object sender, DoWorkEventArgs e) { try { Loader = this.ShowLoader(); UserDataContract user = UsersService.GetUserByLogin(LoginTE.Text).Result; if (user.IsNull()) { throw new Exception( "Пользователь не найден в БД." + Environment.NewLine + "Проверьте данные и повторите попытку."); } if (!user.Password.Equals(PasswordTE.Text)) { throw new Exception( "Введенный пароль не совпадает с паролем из БД." + Environment.NewLine + "Проверьте данные и повторите попытку."); } memory.StoreData(mapper.Map <UserDataContract, UserModel>(user), "CurrentUser"); AuthDialogResult = true; } catch (Exception ex) { message.ShowInfo(ex.Message); } finally { this.HideLoader(Loader); } }
private void AddUser(object parameter) { try { if (string.IsNullOrEmpty(FirstName.Trim())) { throw new Exception("Необходимо заполнить хотя бы фамилию"); } using (var userService = _ppsClientViewModel.ServiceProxy.GetPpsChannelFactory <IUserService>()) { var channel = userService.CreateChannel(); var newUser = new UserDataContract { UserFirstName = FirstName, UserLastName = LastName, UserMiddleName = MiddleName }; var result = channel.AddUser(newUser); if (!result.BoolRes || !string.IsNullOrEmpty(result.ErrorRes)) { throw new Exception(result.ErrorRes); } _ppsClientViewModel.UpdateUserCollection(); _ppsClientViewModel.AddEvent(EventConstants.EVENT_ADD_USER, newUser.UserName); } } catch (Exception ex) { _ppsClientViewModel.WriteLogMessage("Не удалось добавить пользователя - " + ex.Message); } }
public bool AddUser(UserDataContract user) { Mapper.Initialize(o => o.CreateMap <UserDataContract, User>()); var userNew = Mapper.Map <UserDataContract, User>(user); _unitOfWork.UserRepository.Create(userNew); return(true); }
public ActionResult Create([FromBody] UserDataContract userParams) { User user = _db.Users.Add(userParams).Entity; _db.SaveChanges(); return(Ok()); }
public IEnumerable <UserDataContract> GetUsers() { //var list = m_idbe.GetUsers(); // all var sql = new SqlConnection("Data Source=localhost;Integrated Security=False;User ID=u0140060_dbhost; Password=Brq99q0^; Connect Timeout=15;Encrypt=False;Packet Size=4096"); var sel = new SqlCommand("select * from users", sql); var adapter = new SqlDataAdapter(sel); DataTable table = new DataTable("assortment"); adapter.Fill(table); sql.Close(); List <UserDataContract> listUDC = new List <UserDataContract>(); foreach (DataRow row in table.Rows) { UserDataContract udc = new UserDataContract { id = (int)row["id"], Name = (string)row["Name"], Email = (string)row["Email"], Login = (string)row["Login"], Password = (string)row["Password"], Role = (int)row["Role"], RegDateTime = (DateTime)row["RegDateTime"], ActiveStatus = (int)row["ActiveStatus"], }; listUDC.Add(udc); } return(listUDC); //List<UserDataContract> listUDC = new List<UserDataContract>(); //foreach (User u in list) //{ // UserDataContract udc = new UserDataContract // { // id = u.Id, // Name = u.Name, // Email = u.Email, // Login = u.Login, // Password = u.Password, // Role = u.Role, // RegDateTime = u.RegDateTime, // ActiveStatus = u.ActiveStatus // }; // listUDC.Add(udc); //} //return listUDC; //return m_mapper1.Map<IEnumerable<User>, List<UserDataContract>>(list); }
private void button1_Click(object sender, RoutedEventArgs e) { try { /*var jsonSerializer = new DataContractJsonSerializer(typeof (UserDataContract)); * var stream = new MemoryStream(); * var usr = new UserDataContract() {UserId = 1}; * jsonSerializer.WriteObject(stream, usr); * var data = Encoding.UTF8.GetString(stream.ToArray(), 0, (int)stream.Length); * var proxy = new WebClient(); * proxy.Headers["Content-type"] = "application/json"; * proxy.Encoding = Encoding.UTF8; * var res=proxy.UploadString("http://localhost:8732/PolicyProjectManagementService/UserService/GetSingleUser", "POST", data);*/ var jsonSerializer = new DataContractJsonSerializer(typeof(UserDataContract)); var data = string.Empty; using (var stream = new MemoryStream()) { var usr = new UserDataContract { UserId = 1 }; jsonSerializer.WriteObject(stream, usr); data = Encoding.UTF8.GetString(stream.ToArray(), 0, (int)stream.Length); } var request = (HttpWebRequest) WebRequest.Create("http://localhost:8732/PolicyProjectManagementService/UserService/GetUser"); request.Method = "POST"; request.ContentType = "application/json; charset=utf-8"; request.ContentLength = data.Length; using (var sw = new StreamWriter(request.GetRequestStream())) { sw.Write(data); } var response = (HttpWebResponse)request.GetResponse(); var responceStatus = response.StatusCode; if (responceStatus != HttpStatusCode.OK) { throw new Exception(response.StatusDescription); } using (var responseStream = response.GetResponseStream()) { var resContract = jsonSerializer.ReadObject(responseStream) as UserDataContract; } } catch (Exception ex) { MessageBox.Show(string.Concat("Ошибка во время загрузки2. ", ex.Message)); } }
public bool EditUser(UserDataContract user) { Mapper.Initialize(o => o.CreateMap <UserDataContract, User>() .ForMember("Group", op => op.Ignore())); var userNew = Mapper.Map <UserDataContract, User>(user); userNew.GroupId = _unitOfWork.GroupRepository.GetList().FirstOrDefault(u => u.Name == user.Group).Id; _unitOfWork.UserRepository.Update(userNew); return(true); }
public static User ToUser(this UserDataContract userDC) { return(new User() { Id = userDC.Id, FirstName = userDC.FirstName, LastName = userDC.LastName, DateBirth = userDC.DateOfBirth, Age = DateTime.Now.Year - userDC.DateOfBirth.Year, Gender = userDC.UserGender, Visa = userDC.UserVisa.ToVisa().ToArray() }); }
public IHttpActionResult GetUserInfo() { var identity = User.Identity as ClaimsIdentity; var user = new UserDataContract { UserName = identity.Name }; int userId = 0; int.TryParse(identity.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value, out userId); user.UserId = userId; return(Ok(user)); }
private void button2_Click(object sender, RoutedEventArgs e) { try { /*var proxy=new WebClient(); * var url = string.Format("http://localhost:8732/PolicyProjectManagementService/User/GetGet/{0}&{1}", 3, 5); * var bytes = proxy.DownloadData(url); * var stream = new MemoryStream(bytes); * var serializer=new DataContractJsonSerializer(typeof(string)); * txtRes.Text = (serializer.ReadObject(stream)).ToString(); */ var usr = new UserDataContract { UserId = 1 }; var serUsr = JsonConvert.SerializeObject(usr); var request = (HttpWebRequest) WebRequest.Create("http://localhost:8732/PolicyProjectManagementService/UserService/GetUser"); request.Method = "POST"; request.ContentType = "application/json; charset=utf-8"; request.ContentLength = serUsr.Length; using (var sw = new StreamWriter(request.GetRequestStream())) { sw.Write(serUsr); } var response = (HttpWebResponse)request.GetResponse(); var responceStatus = response.StatusCode; if (responceStatus != HttpStatusCode.OK) { throw new Exception(response.StatusDescription); } using (var responseStream = new StreamReader(response.GetResponseStream())) using (var jsonRdr = new JsonTextReader(responseStream)) { var serializer = new JsonSerializer(); var ress = serializer.Deserialize <Result <UserDataContract[]> >(jsonRdr); /*var jsonStr=serializer.Deserialize<string>(jsonRdr); * var resContract = JsonConvert.DeserializeObject<Result<UserDataContract[]>>(jsonStr); */ } } catch (Exception ex) { MessageBox.Show(string.Concat("Ошибка во время загрузки1. ", ex.Message)); } }
public UserDataContract GetActiveUser(string userID) { UserMethods um = new UserMethods(); try { int userIDInt = Int32.Parse(userID); return(um.GetActiveUser(userIDInt)); } catch (Exception e) { UserDataContract bad = new UserDataContract(); return(bad); } }
public async Task <UserDataContract> FindByUserNameorEmail(LoginDataContract logindataContract) { var user = new Member { Email = logindataContract.Email, PasswordHash = logindataContract.PasswordHash, }; var userResult = await _loginRepository.FindByUserNameOrEmail(user); var userDataContract = new UserDataContract { UserId = userResult.Id, UserName = userResult.UserName, Email = userResult.Email }; return(userDataContract); }
public ActionResult SaveUser(Models.User model) { bool bAdd = (model.id == 0); if (IsModelValid(new string[] { "Name", "Login", "Password", "Email" })) { using (var webDbService = new WebOrpalDbService.WebDbServiceClient()) { // mapping Models.User on UserDataContract UserDataContract udc = m_mapperSave.Map <UserDataContract>(model); if (bAdd) { udc.RegDateTime = DateTime.Now; if (!webDbService.AddUser(udc)) { ViewBag.errorEditMessage = $"Не удалось добавить пользователя {model}. Попробуйте сделать это чуть позже."; return(View("AddUser", model)); } } else // edit { if (!webDbService.EditUser(udc)) { ViewBag.errorEditMessage = $"Не удалось сохранить профайл для {model}. Попробуйте сделать это чуть позже."; return(View("EditUser", model)); } } } return(RedirectToAction("Index")); } ViewBag.CollectionRoles = Code.CommnonCollections.GetCollection(Code.CommnonCollections.Roles, Convert.ToInt32(model.Role)); ViewBag.CollectionStatuses = Code.CommnonCollections.GetCollection(Code.CommnonCollections.Statuses, Convert.ToInt32(model.ActiveStatus)); return((bAdd) ? View("AddUser", model) : View("EditUser", model)); }
public object BeforeSendRequest(ref Message request, IClientChannel channel) { // Shared object that stores the user object once it's created UserDataContract myUser = MySharedObjects.MyUser; if (myUser != null) { // Create the Message Header MessageHeader header = MessageHeader.CreateHeader("TokenHeader", "TokenNameSpace", myUser.Token); // Create buffered copy MessageBuffer buffer = request.CreateBufferedCopy(Int32.MaxValue); request = buffer.CreateMessage(); // Add the custom Message Header request.Headers.Add(header); //////// CUSTOM CODE FOR VIEWING THE MESSAGE ...just used to make sure that the actual request looks like you want it to //////// // Make a copy of the message for viewing Message msgCopy = buffer.CreateMessage(); msgCopy.Headers.Add(header); // Get the XML content var strMessage = msgCopy.ToString(); // Get the SOAP XML body content XmlDictionaryReader xrdr = msgCopy.GetReaderAtBodyContents(); string bodyData = xrdr.ReadOuterXml(); // Replace the body placeholder with the actual SOAP body. strMessage = strMessage.Replace("... stream ...", bodyData); } return(null); }
public UserDataContract Build(Credentials creds) { User userA = new DatabaseCredentialsValidator(_DbContext).IsValid(creds); if (null == userA) { throw new AuthenticationException(); } var token = BuildSecureToken(TokenSize); var user = _DbContext.Users.SingleOrDefault(u => u.Username.Equals(creds.User, StringComparison.CurrentCultureIgnoreCase)); _DbContext.Tokens.Add(new Token { TokenString = token, User = user, CreateDate = DateTime.Now }); _DbContext.SaveChanges(); UserDataContract jsonObject = new UserDataContract(); jsonObject.token = token; jsonObject.Role = userA.Role.Trim(); jsonObject.UserID = userA.Id; jsonObject.UserName = userA.Username; return(jsonObject); }
public void Delete(UserDataContract userDC) => master.Delete(userDC.ToUser());
public async Task <IActionResult> UpdateUser(string id, [FromBody] UserDataContract user) { ApplicationUser appUser = await _accountManager.GetUserByIdAsync(id); if (ModelState.IsValid) { if (user == null) { return(BadRequest($"{nameof(user)} cannot be null")); } if (!string.IsNullOrWhiteSpace(user.Id) && id != user.Id) { return(BadRequest("Conflicting user id in parameter and model data")); } if (appUser == null) { return(NotFound(id)); } bool isPasswordChanged = !string.IsNullOrWhiteSpace(user.NewPassword); bool isUserNameChanged = !appUser.UserName.Equals(user.UserName, StringComparison.OrdinalIgnoreCase); if (GetUserId(this.User) == id) { if (string.IsNullOrWhiteSpace(user.CurrentPassword)) { if (isPasswordChanged) { AddError("Current password is required when changing your own password", "Password"); } if (isUserNameChanged) { AddError("Current password is required when changing your own username", "Username"); } } else if (isPasswordChanged || isUserNameChanged) { if (!await _accountManager.CheckPasswordAsync(appUser, user.CurrentPassword)) { AddError("The username/password couple is invalid."); } } } if (ModelState.IsValid) { _mapper.Map(user, appUser); var result = await _accountManager.UpdateUserAsync(appUser, user.RoleIds); if (result.Succeeded) { if (isPasswordChanged) { if (!string.IsNullOrWhiteSpace(user.CurrentPassword)) { result = await _accountManager.UpdatePasswordAsync(appUser, user.CurrentPassword, user.NewPassword); } else { result = await _accountManager.ResetPasswordAsync(appUser, user.NewPassword); } } if (result.Succeeded) { return(NoContent()); } } AddError(result.Errors); } } return(BadRequest(ModelState)); }
public bool EditUser(UserDataContract user) { throw new NotImplementedException(); }
public bool Update(UserDataContract userDC) => master.Update(userDC.ToUser());
public bool EditUser(UserDataContract udc) { return(m_idbe.EditUser(m_mapper2.Map <User>(udc))); }
private void OnSaveMethod(bool IsAlive) { string fnameTemp = ContentPanel.GetFormControlFromPanel <TextBox>(FirstNameTextBox).Text; string snameTemp = ContentPanel.GetFormControlFromPanel <TextBox>(SecondNameTextBox).Text; string lnameTemp = ContentPanel.GetFormControlFromPanel <TextBox>(LastNameTextBox).Text; string contNumTemp = ContentPanel.GetFormControlFromPanel <MaskedTextBox>(ContactNumberMaskBox).Text; UserModel NewModel = new UserModel { UserInfo = new UserInfoModel() { FirstName = fnameTemp, SecondName = snameTemp, LastName = lnameTemp, ContactNumber = contNumTemp, } }; if (OldModel.IsNull()) { NewModel.UserInfo.ID = Guid.NewGuid(); } else { NewModel.UserInfo.ID = OldModel.UserInfo.ID; } NewModel.Position = positions .FirstOrDefault(p => p.Name.Equals(ContentPanel.GetFormControlFromPanel <ComboBoxEdit>(PositionComboBox).Text)); UserDataContract changes = new UserDataContract(); int selectedModel = baseControl.Models.IndexOf(OldModel); if (OldModel.IsNull()) { NewModel.ID = Guid.NewGuid(); NewModel.Login = ContentPanel.GetFormControlFromPanel <TextBox>(LoginTextBox).Text; NewModel.Password = ContentPanel.GetFormControlFromPanel <TextBox>(PasswordTextBox).Text; changes = UsersService.InsertUser(mapper.Map <UserModel, UserDataContract>(NewModel)).Result; baseControl.Models.Add(mapper.Map <UserDataContract, UserModel>(changes)); } else { NewModel.ID = baseControl.Models[selectedModel].ID; NewModel.Login = OldModel.Login; NewModel.Password = OldModel.Password; changes = UsersService.UpdateUser(mapper.Map <UserModel, UserDataContract>(NewModel)).Result; baseControl.Models[selectedModel] = mapper.Map <UserDataContract, UserModel>(changes); baseControl.CollectionView.Items[selectedModel].Selected = true; } if (IsAlive) { OldModel = selectedModel.Equals(-1) ? baseControl.Models[baseControl.Models.Count - 1] : baseControl.Models[selectedModel]; } else { CloseViewButton.PerformClick(); } }
public void Add(UserDataContract userDC) => master.Add(userDC.ToUser());
public bool AddUser(UserDataContract user) { return(_service.AddUser(user)); }
public bool Remove(UserDataContract user) { return(master.Remove(user.ToUser())); }
public IEnumerable <User> SearchByLastAndFirstName(UserDataContract userDC) => master.SearchByFirstAndLastName(userDC.ToUser());
public bool EditUser(UserDataContract user) { return(_service.EditUser(user)); }
public IEnumerable <User> SearchByName(UserDataContract userDC) => master.SearchByName(userDC.ToUser());