private void saveButton(object sender, EventArgs e) { if (isValid()) { if (Project == null) { Project = new InvestProject(); } Project.nameProject = textBoxNameStage.Text; Project.numberProject = textBoxNumberProject.Text; Project.dateBegin = dateBeginPlan.Value; Project.dateEnd = dateEndPlan.Value; Project.dateBeginProg = dateBeginProg.Value; Project.dateEndProg = dateEndProg.Value; UserDAO daoUser = new UserDAO(); DepartmentDAO daoDepartment = new DepartmentDAO(); InvestProjectDAO projectDAO = new InvestProjectDAO(); Project.user = daoUser.getById(Convert.ToInt32(((KeyValuePair)comboBoxUser.SelectedItem).Key)); Project.department = daoDepartment.getById(Convert.ToInt32(((KeyValuePair)comboBoxDepartment.SelectedItem).Key)); if (Project.idProject != 0) { projectDAO.update(Project); } else { projectDAO.insert(Project); } this.Close(); } }
public void GivenThereIsAUserCalledVintem(string username) { _currentUser = new User(username); var userRepository = new UserDAO(); userRepository.Add(_currentUser); userRepository.Commit(); }
public void InitializationDataBox() { UserDAO daoUser = new UserDAO(); DepartmentDAO daoDepartment = new DepartmentDAO(); comboBoxUser.Items.AddRange(daoUser.getUserComboBox().ToArray()); comboBoxDepartment.Items.AddRange(daoDepartment.getComboBox().ToArray()); }
protected void btAcessar_OnClick(object sender, EventArgs e) { UserDAO objDao = new UserDAO(); string sError = string.Empty; string sLogin = RetirarCaracterInvalido(txtLogin.Text); string sSenha = RetirarCaracterInvalido(txtSenha.Text); string sMsg = string.Empty; List<User> sListUser = objDao.FindByWhere(" LOGIN = '******' AND SENHA = '" + sSenha + "'", out sError); if (sListUser.Count == 0 || sListUser.Count > 1) { sMsg = "Campo Login ou Senha errado!"; } else { Session["Usuario"] = sListUser[0]; Session["IdUsuario"] = sListUser[0].Id; GravarAcesso(sListUser[0], out sError); Response.Redirect("ListaContasAPagar.aspx"); } TrataMsgPrincipal(sMsg); }
/// <summary> /// functions which are run on page load. /// It checks that the user is login and sets the page title as /// well as filling in the group information for the group being managed /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Page_Load(object sender, EventArgs e) { base.CheckLoginSession(); _currentUser = Session["userDAO"] as UserDAO; PageTitle.Text = "Text2Share - Manage Group Plugins"; string errorMessageHTML = Request.QueryString["error"]; if (errorMessageHTML != null) { showErrorMessage = true; errorMessage.Text = errorMessageHTML; } string successMessageHTML = Request.QueryString["success"]; if (successMessageHTML != null) { showSuccessMessage = true; successMessage.Text = successMessageHTML; } GetGroupData(); if (!Page.IsPostBack) { SetGroupData(); } }
public void BeforeEachTest() { //create DAOs items = new ItemDAO(); users = new UserDAO(); comments = new CommentDAO(); categories = new CategoryDAO(); }
protected void btTour_OnClick(object sender, EventArgs e) { string sError = string.Empty; UserDAO objDao = new UserDAO(); List<User> sListUser = objDao.FindByWhere(" LOGIN = '******' AND SENHA = 'DEMO'", out sError); Session["Usuario"] = sListUser[0]; Session["IdUsuario"] = sListUser[0].Id; GravarAcesso(sListUser[0], out sError); Response.Redirect("ListaContasAPagar.aspx"); }
private void btnOk_Click(object sender, EventArgs e) { UserDAO userDao = new UserDAO(); User user = userDao.auth(textLogin.Text, textPassword.Text); if (user != null) { //new DialogGridForm().Show(); MainApplication.User = user; this.Close(); } else { MessageBox.Show("Логин или пароль неверны", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public void UserDAO_Test() { /*Context*/ AccountDAO acc_context = new AccountDAO(); UserDAO user_context = new UserDAO(); /*Insert*/ AccountDTO acc = new AccountDTO(); acc.userName = "******"; acc.password = "******"; acc.accountType = "administrator"; acc.status = "active"; acc_context.presist(acc); UserDTO user = new UserDTO(); user.basicEducation = true; user.citizenship = true; user.disabled = true; user.employed = true; user.employmentHistory = true; user.fullName = "Andre"; user.gender = "male"; user.higherEducation = true; user.id = "8630302930"; user.idType = "SA"; user.language = true; user.license = true; user.nickName = "WIlliem"; user.postalAddress = true; user.race = "white"; user.residentialAddress = true; user.surname = "Pretorious"; user.userName = "******"; // user_context.presist(user); //Assert.AreEqual(user.race, user_context.find("griddy","8630302930").race); ///*Update*/ //user.nickName = "willi"; //user_context.merge(user); //Assert.AreEqual(user.nickName, user_context.find("griddy", "8630302930").nickName); ///*Delete*/ //user_context.removeByUserId("griddy", "8630302930"); //Assert.AreEqual(user_context.isFound("griddy", "8630302930"), false); acc_context.removeByUserId("griddy"); }
public void AuditLogInterceptor_Records_Log_Entry_When_Item_Persisted() { // Save a user without audit logging UserDAO userDAO = new UserDAO(); User seller = new User("Christian", "Bauer", "turin", "abc123", "*****@*****.**"); userDAO.MakePersistent(seller); NHibernateHelper.CommitTransaction(); NHibernateHelper.CloseSession(); // Enable interceptor AuditLogInterceptor interceptor = new AuditLogInterceptor(); NHibernateHelper.RegisterInterceptor(interceptor); interceptor.Session = NHibernateHelper.Session; interceptor.UserId = seller.Id; // Save an item with audit logging enabled Item item = new Item( "Warfdale Nearfield Monitors", "Pair of 150W nearfield monitors for the home studio.", seller, new MonetaryAmount(1.99, "USD"), new MonetaryAmount(50.33, "USD"), DateTime.Now, DateTime.Now.AddDays(1) ); ItemDAO itemDAO = new ItemDAO(); itemDAO.MakePersistent(item); // Synchronize state to trigger interceptor NHibernateHelper.Session.Flush(); // Check audit log IQuery findAuditLogRecord = NHibernateHelper.Session.CreateQuery("from AuditLogRecord record where record.EntityId = :id"); findAuditLogRecord.SetParameter("id", item.Id); AuditLogRecord foundRecord = findAuditLogRecord.UniqueResult<AuditLogRecord>(); Assert.IsNotNull(foundRecord); Assert.AreEqual(foundRecord.UserId, seller.Id); NHibernateHelper.CommitTransaction(); NHibernateHelper.CloseSession(); // Deregister interceptor NHibernateHelper.RegisterInterceptor(null); }
protected void Page_Load(object sender, EventArgs e) { if (IsPostBack) return; string sErrorMessage = string.Empty; UserDAO objDao = new UserDAO(); User objUsuario = objDao.FindByPK(IdUserSession, out sErrorMessage); txtEmail.Text = objUsuario.Email; txtLogin.Text = objUsuario.Login; txtNome.Text = objUsuario.Name; txtSenha.Attributes["Value"] = objUsuario.Password; txtNome.Focus(); gvAcesso.DataSource = new AcessDAO(IdUserSession).FindByWhere(string.Empty, "5", out sErrorMessage); gvAcesso.DataBind(); }
// Use this for initialization void Start () { UserDAO userDAO = new UserDAO(); User userData = userDAO.LoadUserFromLocalMemory(); GameObject MusicObject = GameObject.FindGameObjectWithTag("MusicBackground"); if(!MusicObject){ GameObject musicClone = (GameObject)Instantiate(Music, Vector3.zero, Quaternion.identity); AudioSource audioMusic = musicClone.GetComponent<AudioSource>(); //Por defecto las variables de tipo bool son false Debug.Log("MusicGenerator:user.EnableMusic(): " + userData.EnableMusic); if(userData.EnableMusic){ audioMusic.Play(); }else{ audioMusic.Stop(); } } }
protected void btGravar_OnClick(object sender, EventArgs e) { string sErrorMessage = string.Empty; UserDAO objDao = new UserDAO(); User objUsuario = objDao.FindByPK(IdUserSession, out sErrorMessage); if (txtLogin.Text.Trim().Equals("DEMO")) { TrataMsgPrincipal("Usuário DEMO não tem acesso para alteração, crie seu próprio usuário! :)"); return; } objUsuario.Name = txtNome.Text; objUsuario.Email = txtEmail.Text; objUsuario.Password = txtSenha.Text; objDao.Save(objUsuario, out sErrorMessage); TrataMsgPrincipal(sErrorMessage); }
private void initializateData() { UserDAO dao = new UserDAO(); List<User> listAll = dao.getUsersResponsible(Utils.AdvanceUtil.stageStatus.ALL); BindingSource sourceAll = new BindingSource(); sourceAll.DataSource = listAll; gridAll.DataSource = sourceAll; List<User> listPlan = dao.getUsersResponsible(Utils.AdvanceUtil.stageStatus.PLAN); BindingSource sourcePlan = new BindingSource(); sourcePlan.DataSource = listPlan; gridNotComplete.DataSource = sourcePlan; List<User> listFact = dao.getUsersResponsible(Utils.AdvanceUtil.stageStatus.FACT); BindingSource sourceFact = new BindingSource(); sourceFact.DataSource = listFact; gridComplete.DataSource = sourceFact; //listStage.Select(user => user.User).ToList(); }
/// <summary> /// Checks if the given user is verified in the database. If they are not, they are redirected to the /// Verification page. Otherwise, they are sent to the Index page. Users are always sent to the /// Verification page on first registering with the application. /// </summary> /// <param name="currentUser">The user to check in the database.</param> /// <returns>true if the user is already verified</returns> /// <exception cref="SqlException">If there is an issue connecting to the database.</exception> public bool isVerified(UserDAO currentUser) { try { IDBController controller = new SqlController(); string val = controller.GetCurrentVerificationValueForUser(currentUser); return null == val; } catch (ArgumentNullException) { // Shouldn't happen } catch (CouldNotFindException) { // User was literally just created, shouldn't be a problem } // Let the other pages handle SqlExceptions, for displaying to users return false; }
static void Main(string[] args) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); new AuthForm().ShowDialog(); if (User != null) { if (User.TypeUser == (int)AdvanceUtil.typeUser.ADMIN) { Application.Run(new DialogGridForm()); } else { Application.Run(new UserStageForm()); } UserDAO dao = new UserDAO(); dao.insertLogInfo(2, User); } }
/// <summary> /// registers a user /// </summary> /// <param name="sender"></param> /// <param name="e"></param> /// <exception cref="ArgumentNullException">If the given string is null.</exception> /// <exception cref="EntryAlreadyExitsException">If the user for the given username already exits.</exception> /// <exception cref="SQLException">If an unknown databasae exception happends.</exception> /// <exception cref="InvalidCastException">If the phonecarrier string value can not be casted to a existing phoneCarrier.</exception> public void Register_Click(Object sender, EventArgs e) { String password = Request["passwordBox"]; String verifyPassword = Request["verifyPasswordBox"]; //verify password fields match if (!password.Equals(verifyPassword)) { invalidCredentials.Text = "The passwords you entered do not match. Please try again."; return; } SqlController controller = new SqlController(); String phoneNumber = Request["phoneNumberBox"].Replace("-", String.Empty); //create a new userDAO and set it fields UserDAO user = null; try { user = new UserDAO() { FirstName = Request["firstNameBox"], LastName = Request["lastNameBox"], UserName = Request["userNameBox"], PhoneNumber = phoneNumber, Carrier = (PhoneCarrier)(Request["carrierDropdown"]), PhoneEmail = phoneNumber + "@" + ((PhoneCarrier)(Request["carrierDropdown"])).GetEmail(), IsBanned = false, IsSuppressed = false }; } catch (InvalidCastException) { Response.Write("Could not find phone carrier! Please try again!"); } //check to see is needs to be hashed before try { if (!controller.CreateUser(user, password)) { Response.Write("The user was not created"); } } catch (EntryAlreadyExistsException) { invalidCredentials.Text = "A user with that name or phone number already exists. Please try again."; return; } catch (ArgumentNullException) { invalidCredentials.Text = "A field was left blank. Please make sure the form is fully completed."; return; } catch (SqlException ex) { Logger.LogMessage("Register.aspx: " + ex.Message, LoggerLevel.SEVERE); invalidCredentials.Text = "An unknown error occured. Please try again."; return; } //set the session the same as user login HttpContext.Current.Session["userDAO"] = user; Response.Redirect("Verification.aspx"); }
public static User UserDaoToUser(UserDAO userDAO) { User user = new User(userDAO.ID,userDAO.UserId); return user; }
List<User> LoadFriends() { userDao = new UserDAO(); User userData = userDao.LoadUserFriendsFromLocalMemory(); /*if(userData.Friends != null){ foreach(User userloop in userData.Friends){ Debug.Log("user.AvatarName: " +userloop.AvatarName); } }else{ Debug.Log("userData.Friends: NUULLL" ); }*/ return userData.Friends; }
public ActionResult Update(int id) { var user = new UserDAO().getUserByID(id); return(View(user)); }
public UserService(DataContext context) { _userDAO = new UserDAO(context); }
public void insertPendingUser(User usr) { UserDAO udao = new UserDAO(); udao.InsertPendingUser(usr); }
public static User Find(Guid?id = null, string login = null) { return(UserDAO.Find(id, login)); }
protected void Page_Load(object sender, EventArgs e) { base.ClearCache(); base.CheckLoginSession(); _currentUser = HttpContext.Current.Session["userDAO"] as UserDAO; PageTitle.Text = "Text2Share - Home"; retrieveGroups(); retrievePlugins(); string errorMessageHTML = Request.QueryString["error"]; if (errorMessageHTML != null) { showErrorMessage = true; errorMessage.Text = errorMessageHTML; } string successMessageHTML = Request.QueryString["success"]; if (successMessageHTML != null) { showSuccessMessage = true; successMessage.Text = successMessageHTML; } }
private AuthenticationService() { this.userDAO = new UserDAO(); }
// 确认支付的实现 protected void btn_Submit(object sender, EventArgs e) { string username = Session["name"].ToString(); string email = new UserDAO().getUser(username).Email; string paymethod = Request["pay_method"]; float amount = Convert.ToSingle(money); Session["charge_username"] = username; Session["charge_email"] = email; //生成支付成功码 string success_code1 = (new Random().Next(1000000, 10000000)).ToString(); string success_code2 = (new Random().Next(10000000, 100000000)).ToString(); string success_code3 = (new Random().Next(100000000, 1000000000)).ToString(); string success_code = success_code1 + success_code2 + success_code3; //将成功码插入到用户表中,支付成功是进行验证 new UserDAO().updateChargeCode(username, success_code, amount); Session["chargecode"] = success_code; if (paymethod == "pay_card") { String card_type = Request["card_type"]; if (card_type == "VISA Credit") { amount = amount + amount * 0.025f; amount = (float)Math.Round(amount, 2); } else if (card_type == "Mastercard Credit") { amount = amount + amount * 0.025f; amount = (float)Math.Round(amount, 2); } else if (card_type == "VISA Debit") { amount = amount + 0.40f; amount = (float)Math.Round(amount, 2); } else if (card_type == "UK Maestro") { amount = amount + 0.25f; amount = (float)Math.Round(amount, 2); } else if (card_type == "Non EU Cards") { amount = amount + amount * 0.35f; amount = (float)Math.Round(amount, 2); } Session["charge_amount"] = amount; Session["charge_method"] = card_type; Response.Write("<script language='javascript'>parent.location='../paycard-charge.aspx'</script>"); //Response.Redirect("paycard-charge.aspx"); } else if (paymethod.Equals("pay_paypal")) { amount = amount * 1.05f; amount = (float)Math.Round(amount, 2); Session["charge_amount"] = amount; Session["charge_method"] = "paypal"; Response.Write("<script language='javascript'>parent.location='../paypal-charge.aspx'</script>"); //Response.Redirect("paypal-charge.aspx"); } }
//Contructor that sets the connection string to variables for use throughout the controller. public UsersController() { string connection = ConfigurationManager.ConnectionStrings["dataSource"].ConnectionString; _dataAccess = new UserDAO(connection); }
public ActionResult Edit(int id) { var user = new UserDAO().ViewDetail(id); return(View(user)); }
protected void Page_Load(object sender, EventArgs e) { base.CheckLoginSession(); _currentUser = Session["userDAO"] as UserDAO; base.ClearCache(); PageTitle.Text = "Text2Share - Verification"; if (null != Request.QueryString["generateNew"]) { GetNumberToSendVerificationTo(); } else { GetCurrentVerificationCodeForUser(); } }
public UserBUS() { userDAO = new UserDAO(); }
public void updateUser(User usr) { UserDAO udao = new UserDAO(); udao.UpdateUser(usr); }
public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords) { MembershipUserCollection membershipUsers = new MembershipUserCollection(); totalRecords = new UserDAO().GetUsersCount(); if (totalRecords <= 0) { return membershipUsers; } IList<User> users = new UserDAO().GetAll(); int startIndex = pageSize * pageIndex; int endIndex = startIndex + pageSize - 1; for (int i = startIndex; i < users.Count && i < endIndex; ++i) { MembershipUser u = getMembershipUserFromDnUser(users[i]); membershipUsers.Add(u); } return membershipUsers; }
public ActionResult Login(LoginModel loginModel) { if (ModelState.IsValid) { var dao = new UserDAO(); var res = dao.Login(loginModel._Account.Email, Encryptor.MD5Hash(loginModel._Account.Password)); if (res == 1) { var user = dao.GetUserByEmail(loginModel._Account.Email); var userSession = new UserLogin(); userSession.Email = user.Email; userSession.UserID = user.UserID; Session.Add(CommonConstants.ADMIN_USER_SESSION, userSession); if (loginModel.RememberMe) { HttpCookie ckEmail = new HttpCookie("email"); ckEmail.Expires = DateTime.Now.AddDays(3600); ckEmail.Value = loginModel._Account.Email; Response.Cookies.Add(ckEmail); HttpCookie ckPassword = new HttpCookie("password"); ckPassword.Expires = DateTime.Now.AddDays(3600); ckPassword.Value = loginModel._Account.Password; Response.Cookies.Add(ckPassword); } return(RedirectToAction("Index", "Home")); } else if (res == 0) { ModelState.AddModelError("", "Tài khoản không tồn tại"); } else if (res == 2) { ModelState.AddModelError("", "Tài khoản của bạn đang bị khóa"); } else if (res == -1) { ModelState.AddModelError("", "Sai mật khẩu"); } else if (res == 3) { ModelState.AddModelError("", "Bạn không có quyền này"); } else if (res == -2) { return(RedirectToAction("Index", "Confirm")); } else { ModelState.AddModelError("", "Đăng nhập không thành công"); } } return(View("Index")); }
public override MembershipUser GetUser(string username, bool userIsOnline) { UserDAO userDao = new UserDAO(); CommandStatus status = new CommandStatus(); User user = userDao.GetByUserName(username, status); MembershipUser mUser =null; if(user.UserId != 0) { mUser = getMembershipUserFromDnUser(user); } return mUser; }
private void checkLogin() { RegistryKey key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("smartparking"); try { if (key != null) { if (key.GetValue("UserId") != null && key.GetValue("Password") != null) { string userId = (string)key.GetValue("UserId"); string password = (string)key.GetValue("Password"); UserDAO dao = new UserDAO(); bool result = dao.CheckLogin(userId, password); if (result == false) { loginForm mf = new loginForm(); mf.StartPosition = FormStartPosition.CenterScreen; mf.Show(); //hide this form this.Hide(); } else { mainform main = new mainform(userId); main.Show(); this.Hide(); } } else { loginForm mf = new loginForm(); mf.StartPosition = FormStartPosition.CenterScreen; mf.Show(); //hide this form this.Hide(); } } else { loginForm mf = new loginForm(); mf.StartPosition = FormStartPosition.CenterScreen; mf.Show(); //hide this form this.Hide(); } } finally { if (key != null) { key.Close(); } } }
public PrUserController(UserDAO t) { userDao = t; }
public UserService() { this.UserDAO = new UserDAO(); }
protected void btnAccep_Click(object sender, EventArgs e) { try { string macongty = Session["congty"].ToString(); string maphieu = Session["maphieu"].ToString(); string ngonngu = Session["languege"].ToString(); string manguoidung = Session["user"].ToString(); Busers2 KiemTraMatKhau = UserDAO.KiemTraMatKhauXetDuyetCuaNguoiDuyet(manguoidung, macongty, libraly.Encryption(txtSecure.Text)); if (KiemTraMatKhau == null) { if (ngonngu == "lbl_VN") { lbThongBao.Text = "Mật khẩu là không chính xác"; } else if (ngonngu == "lbl_TW") { lbThongBao.Text = "密码不正确"; } else if (ngonngu == "lbl_EN") { lbThongBao.Text = "The password is incorrect"; } } else { Busers2 user = UserBUS.TimNhanVienTheoMa(manguoidung, macongty); //string abc = libraly.Encryption(txtSecure.Text); if (user != null && libraly.Encryption(txtSecure.Text).Equals(user.Password2)) { bool duyet = (rdApproval.Checked) ? true : ((rdNotApproval.Checked) ? false : true); string ghichu = txtComment.Text; //Task temp = Task.Factory.StartNew(() => Until.XetDuyet(maphieu, Until.uNhanVien, duyet, ghichu)); //{ // if (temp != null) // { // lbThongBao.Text = "Approval success"; // } //} // temp.RunSynchronously(); //Task temp = Task.Factory.StartNew(() => Until.XetDuyet(maphieu, Until.uNhanVien, duyet, ghichu)); Until.XetDuyet(maphieu, user, duyet, ghichu, macongty); // kiem tra : lay chi tiet theo nguoi duyet neu nguoi.abresult==true di qua trang khac nguoc lai khong xet duyet Abcon chitietduyet = AbconBUS.LayChiTietXetDuyetTheoNhanVienDuyet(maphieu, manguoidung); if (chitietduyet == null) { return; } else { if (chitietduyet.abrult == true) { if (ngonngu == "lbl_VN") { lbThongBao.Text = "Bạn đã xét duyệt thành công"; } else if (ngonngu == "lbl_TW") { lbThongBao.Text = "审核成功"; } else if (ngonngu == "lbl_EN") { lbThongBao.Text = "Approval Success!"; } if (chitietduyet.abtype == "PDN2") { Response.Redirect("phieumuahangD.aspx"); } else { Response.Redirect("frmDetails2D.aspx"); } } else { if (chitietduyet.Yn == 2) { if (ngonngu == "lbl_VN") { lbThongBao.Text = "Bạn đã không xét duyệt phiếu này"; } else if (ngonngu == "lbl_TW") { lbThongBao.Text = "本单未审核"; } else if (ngonngu == "lbl_EN") { lbThongBao.Text = "Not Approval "; } if (chitietduyet.abtype == "PDN2") { Response.Redirect("phieumuahangD.aspx"); } else { Response.Redirect("frmDetails2D.aspx"); } } } } } } // Response.Redirect("frmDetails2.aspx"); } catch (Exception ex) { lbthongbaoLoi.Text = "loi" + ex.Message; } // Response.Redirect("frmDetails2.aspx"); }
protected void importuj(object sender, EventArgs e) { litResults.Text = ""; if (fuplImport.HasFile) { bool fileValid = Path.GetExtension(fuplImport.FileName).Equals(".csv"); if (!fileValid) { Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "wrongExt", "<script type=\"text/javascript\" language=\"javascript\">alert('Dozwolony jest import tylko z plików .csv !');</script>"); return; } else { // pobranie danych z csv try { string filePath = Server.MapPath(ConfigurationManager.AppSettings["katalogRoboczy"].ToString()) + "\\" + fuplImport.FileName; if (File.Exists(filePath)) { File.Delete(filePath); } fuplImport.SaveAs(filePath); string strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + Path.GetDirectoryName(filePath) + "; Extended Properties=\"Text;HDR=YES;FMT=Delimited(;)\""; OleDbConnection conText = new OleDbConnection(strConnectionString); OleDbDataAdapter odda = new OleDbDataAdapter("SELECT * FROM " + Path.GetFileName(filePath), conText); DataSet dsImport = new DataSet(); conText.Open(); odda.Fill(dsImport); conText.Close(); DataTable dtImport = dsImport.Tables[0]; foreach (DataRow row in dtImport.Rows) { UserDAO ud = new UserDAO(); string userLogin = Membership.GetUserNameByEmail(row["email"].ToString()); if (userLogin != null && userLogin.Equals(row["login"].ToString())) { litResults.Text += string.Format("<p>konto: {0} ju¿ istnieje</p>", row["login"].ToString()); } else { MembershipUser usr = Membership.CreateUser(row["login"].ToString(), row["haslo"].ToString(), row["email"].ToString()); ud.CreateEmployee(row["nazwisko"].ToString(), row["imie"].ToString(), (Guid)usr.ProviderUserKey, ""); litResults.Text += string.Format("<p>konto: {0} utworzone</p>", usr.UserName); ud.CreateOrganizationalUnit(row["wydzial"].ToString(), row["skrotwydzialu"].ToString(), true, 0); litResults.Text += string.Format("<p>konto: {0} przypisane do: {1}</p>", usr.UserName, row["wydzial"].ToString()); Roles.AddUserToRole(usr.UserName, row["wydzial"].ToString()); } } File.Delete(filePath); } catch (Exception ex) { litResults.Text += string.Format("<p> B³¹d importu danych:<br/>{0}<br/>{1}</p>", ex.Message, ex.Source); } } } }
public UserLogic() { userDAO = new UserDAO(); userTable = new UserDS.TabUserDataTable(); }
public ActionResult Signup(FormSignup signup) { string status; string UserName = signup.dkUserName; string Email = signup.dkEmail; string Name = signup.dkName; string Password1 = signup.dkPass1; string Password2 = signup.dkPass2; UserDAO userDAO = new UserDAO(); if (UserName == "" || Email == "" || Name == "" || Password1 == "" || Password2 == "") { status = "empty"; return(new JsonResult { Data = new { status = status } }); } else if (UserName.Length < 6) { status = "userlength"; return(new JsonResult { Data = new { status = status } }); } else if (userDAO.checkUsered(UserName)) { status = "user"; return(new JsonResult { Data = new { status = status } }); } else if (!Tools.IsValidEmail(Email)) { status = "email"; return(new JsonResult { Data = new { status = status } }); } else if (Password1.Length < 8) { status = "passlength"; return(new JsonResult { Data = new { status = status } }); } else if (!Password1.Equals(Password2)) { status = "pass"; return(new JsonResult { Data = new { status = status } }); } else { DBModel db1 = new DBModel(); account tmpAccount = new account(); tmpAccount.USERNAME = UserName; tmpAccount.HO_TEN = Name; tmpAccount.ID_ACCOUNT = userDAO.generateIDAccount(); tmpAccount.PASSWORD = Tools.MD5(Password1); tmpAccount.LEVEL = "5"; tmpAccount.ACTIVE = "1"; db1.accounts.Add(tmpAccount); db1.SaveChangesAsync(); DBModel db2 = new DBModel(); ct_account tmpCTAccount = new ct_account(); tmpCTAccount.ID_ACCOUNT = tmpAccount.ID_ACCOUNT; tmpCTAccount.EMAIL = Email; tmpCTAccount.SDT = null; tmpCTAccount.DIA_CHI = null; tmpCTAccount.GIOI_TINH = 1; tmpCTAccount.NGAY_SINH = null; db2.ct_account.Add(tmpCTAccount); db2.SaveChangesAsync(); User userVM = userDAO.getUser(userDAO.getID(UserName)); HttpContext.Session.Add("User", userVM); status = "success"; return(new JsonResult { Data = new { status = status } }); } }
protected void Page_Load(object sender, EventArgs e) { base.CheckLoginSession(); _currentUser = Session["userDAO"] as UserDAO; PageTitle.Text = "Text2Share - Add Plugin"; }
public static List <User> List(User filters = null) { return(UserDAO.List(filters)); }
public void AddUser(UserDAO user) { _users.Add(user); }
public static bool Delete(Guid id) { return(UserDAO.Delete(id)); }
private void RegisterButton_Click(object sender, RoutedEventArgs e) { if (string.IsNullOrEmpty(UsernameBox.Text.Trim()) || string.IsNullOrEmpty(PasswordBox.Password) || string.IsNullOrEmpty(NameBox.Text.Trim()) || string.IsNullOrEmpty(SurnameBox.Text.Trim()) || string.IsNullOrEmpty(StreetBox.Text.Trim()) || string.IsNullOrEmpty(ZipCodeBox.Text.Trim()) || string.IsNullOrEmpty(EmailBox.Text.Trim()) || string.IsNullOrEmpty(CountryBox.Text.Trim()) || string.IsNullOrEmpty(CityBox.Text.Trim()) || BirthDatePicker.SelectedDate == null || FunctionComboBox.SelectedItem == null) { NotificationLabel.ShowError("All fields required!"); } else { if (selectedFunction == User.Function.ADMIN || selectedFunction == User.Function.OPERATOR) { if (string.IsNullOrEmpty(AccessKeyBox.Password)) { NotificationLabel.ShowError("Please enter access key to register as " + selectedFunction + " !"); return; } if (!Encryption.GenerateSaltedHash(AccessKeyBox.Password).Equals(AccessKey)) { NotificationLabel.ShowError("Access key incorrect"); return; } } User user = new User() { Username = UsernameBox.Text, Password = Encryption.GenerateSaltedHash(PasswordBox.Password), Name = NameBox.Text, Surname = SurnameBox.Text, UserFunction = selectedFunction, }; UserDetails userDetails = new UserDetails() { City = CityBox.Text, Country = CountryBox.Text, Email = EmailBox.Text, Street = StreetBox.Text, ZipCode = ZipCodeBox.Text, BirthDate = BirthDatePicker.SelectedDate.Value, }; UserDAO userDAO = new UserDAO(); UserDetailsDAO userDetailsDAO = new UserDetailsDAO(); DebugLog.WriteLine(userDAO == null); try { userDAO.Insert(user); userDetails.UserId = user.Id; userDetailsDAO.Insert(userDetails); user.UserDetails = userDetails; userDAO.Update(user); NotificationLabel.ShowSuccess("Registration successful!"); } catch (Exception ex) { DebugLog.WriteLine(ex); NotificationLabel.ShowError("Username already taken!"); } } }
public bool Subscribe(string cpf, string email) { return(UserDAO.RegisterUser(new User(cpf, email))); }
public UserService(string context) { _userDAO = new UserDAO(context); }
public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status) { ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(username, password, true); OnValidatingPassword(args); if (args.Cancel) { status = MembershipCreateStatus.InvalidPassword; return null; } if (RequiresUniqueEmail && !String.IsNullOrEmpty(GetUserNameByEmail(email))) { status = MembershipCreateStatus.DuplicateEmail; return null; } MembershipUser u = GetUser(username, false); if (u == null) { DateTime createDate = DateTime.Now; if (providerUserKey == null) providerUserKey = Guid.NewGuid(); else if (!(providerUserKey is Guid)) { status = MembershipCreateStatus.InvalidProviderUserKey; return null; } User user = new User() { UserId = 0, CreateDate = DateTime.Now, Email = email, UserName = username, PasswordHash = CreatePasswordHash(password), AuthorizatonKey = (Guid)providerUserKey }; int userId = new UserDAO().Add(user); MembershipUser mUser = getMembershipUserFromDnUser(user); if (userId > 0) status = MembershipCreateStatus.Success; else status = MembershipCreateStatus.UserRejected; return mUser; } else { status = MembershipCreateStatus.DuplicateUserName; } return null; }
// GET: Admin/HomeAdmin public ActionResult Index() { var listProduct = new ProductDAO().ListNewAD(); var listPro = new ProductDAO().ListOf(); ViewBag.Model = listPro.Count(); List <ProductAdminModel> listP = new List <ProductAdminModel>(); foreach (var item in listProduct) { var newP = new ProductAdminModel(); newP.Id = item.id; newP.Name = item.name; newP.ManufacterId = item.id_CarManufacturer; newP.ManufacterName = item.CarManufacturer == null ? string.Empty : item.CarManufacturer.name; newP.Price = item.price; newP.Number = item.number; newP.Image = item.imagemain; listP.Add(newP); } ViewBag.Product = listP; var listAcc = new AccountDAO(); var acc = listAcc.ListAll(); ViewBag.Acc = acc; var listUsers = new UserDAO().ListAll(); ViewBag.User = listUsers; var listNews = new NewsDAO().ListNewAdmin(); ViewBag.News = listNews; var listContact = new ContactDAO().ListAll(); ViewBag.Contact = listContact; var iplAcc = new FeedbackDAO(); var fb = iplAcc.ListOf(); List <FeedbackAdminModel> listFB = new List <FeedbackAdminModel>(); foreach (var item in fb) { var newFb = new FeedbackAdminModel(); newFb.ID = item.id; newFb.User_ID = item.id_User; newFb.User_Name = item.User == null ? string.Empty : item.User.displayname; newFb.Product_ID = item.id_Product; newFb.Product_Image = item.Product == null ? string.Empty : item.Product.imagemain; newFb.Star = item.star; newFb.Note = item.note; listFB.Add(newFb); } ViewBag.Feedback = listFB; var order = new OrderDAO().ListOf(); ViewBag.Order = order.Count(); ViewBag.Price = order.Sum(x => x.amount).ToString("N0"); var car = new CarManufacturerDAO().ListOf(); ViewBag.Car = car.Count(); return(View()); }
void LoadData() { Debug.Log("FriendsController:LoadingData()....."); UserDAO userDAO = new UserDAO(); User userData = userDAO.LoadUserFromLocalMemory(); Debug.Log("userData.AvatarName: " + userData.AvatarName); }
public int AddNewUser() { UserDAO dao = new UserDAO(); return(dao.Insert(this)); }
void SaveData(List<User> UserFriends) { user = new User(); user.Friends = UserFriends; /*foreach(User userItem in UserFriends){ Debug.Log("user.AvatarName: " + userItem.AvatarName); }*/ userDao = new UserDAO(); userDao.SaveUserFriendsOnLocalMemory(user); }
public static void Exclude(int op) { Console.Clear(); PlanDAO p = new PlanDAO(); UserDAO u = new UserDAO(); PlanTypeDAO pt = new PlanTypeDAO(); PlanStatusDAO ps = new PlanStatusDAO(); string resp = ""; switch (op) { case 1: Console.WriteLine("\nDigite o nome do plano a ser excluído"); resp = Console.ReadLine(); planList = p.getPlans(); if (planList.Where(i => i.Name.Contains(resp)).Count() > 0) { foreach (var item in planList.Where(i => i.Name.Contains(resp))) { p.excludePlan(item.Id); } } else { Console.WriteLine("\nPlano nao existe!"); } break; case 2: Console.WriteLine("\nDigite o nome do usuario a ser excluído"); resp = Console.ReadLine(); userList = u.getUser(); if (userList.Where(i => i.Name.Contains(resp)).Count() > 0) { foreach (var item in userList.Where(i => i.Name.Contains(resp))) { u.excludeUser(item.Id); } } else { Console.WriteLine("\nUsuario nao existe!"); } break; case 3: Console.WriteLine("\nDigite o nome do Tipo de Plano a ser excluído"); resp = Console.ReadLine(); typeList = pt.getType(); if (typeList.Where(i => i.Name.Contains(resp)).Count() > 0) { foreach (var item in typeList.Where(i => i.Name.Contains(resp))) { pt.excludeType(item.Id); } } else { Console.WriteLine("\nTipo de Plano nao existe!"); } break; case 4: Console.WriteLine("\nDigite o nome do Status do Plano a ser excluído"); resp = Console.ReadLine(); statusList = ps.getStatus(); if (statusList.Where(i => i.Name.Contains(resp)).Count() > 0) { foreach (var item in statusList.Where(i => i.Name.Contains(resp))) { ps.excludeStatus(item.Id); } } else { Console.WriteLine("\nStatus de Plano nao existe!"); } break; } Submenu(op); }
private static User UserDaoToUserWithCheckingExistence(UserDAO userDAO) { UserKey userKey = userDAO.GetUserKey(); User user = GetExistingUser(userKey); if (user == null) { user = UserDaoToUser(userDAO); userCollection.Add(userKey, user); } return user; }
public static void Insert(int op) { Console.Clear(); PlanDAO p = new PlanDAO(); UserDAO u = new UserDAO(); PlanTypeDAO pt = new PlanTypeDAO(); PlanStatusDAO ps = new PlanStatusDAO(); string aux = ""; int confirm = 0; int exists = 0; switch (op) { case 1: planList = p.getPlans(); typeList = pt.getType(); userList = u.getUser(); statusList = ps.getStatus(); Console.WriteLine("\nInsira o nome do plano: "); string planResp = Console.ReadLine(); foreach (var item in planList) { if (item.Name.Contains(planResp)) { Console.WriteLine("\nJa existe um plano com esse nome"); exists = 1; break; } } if (exists == 1) { break; } Console.Clear(); Console.WriteLine("\nEscolha um tipo de plano: "); foreach (var item in typeList) { Console.WriteLine(item.Id + "-" + item.Name); } int typeId = Int32.Parse(Console.ReadLine()); Console.Clear(); Console.WriteLine("\nEscolha um responsavel: "); foreach (var item in userList) { Console.WriteLine(item.Id + "-" + item.Name); } int userId = Int32.Parse(Console.ReadLine()); Console.Clear(); Console.WriteLine("\nEscolha um status para o plano: "); foreach (var item in statusList) { Console.WriteLine(item.Id + "-" + item.Name); } int statusId = Int32.Parse(Console.ReadLine()); Console.Clear(); Console.WriteLine("\nInsira a data de inicio do plano: "); DateTime stDate = DateTime.Parse(Console.ReadLine()); Console.Clear(); Console.WriteLine("\nInsira a data de fim do plano: "); DateTime edDate = DateTime.Parse(Console.ReadLine()); Console.Clear(); Console.WriteLine("\nInsira uma descrição do projeto: "); string desc = Console.ReadLine(); Console.Clear(); Console.WriteLine("\nInsira o custo do plano: "); decimal ct = Decimal.Parse(Console.ReadLine()); Console.Clear(); Plan pInsert = new Plan(planResp, 0, pt.getOneType(typeId), u.getResponsible(userId), ps.getOneStatus(statusId), stDate, edDate, desc, ct); Console.WriteLine("\nConfirme seus dados: "); Console.WriteLine(pInsert); Console.WriteLine("\n1-Sim\n2-Nao"); confirm = Int32.Parse(Console.ReadLine()); if (confirm == 1) { p.insertPlan(pInsert); } else { Console.WriteLine("\nOperacao cancelada!"); } break; case 2: userList = u.getUser(); Console.WriteLine("\nInsira o nome do usuario: "); string userName = Console.ReadLine(); foreach (var item in userList) { if (item.Name.Contains(userName)) { Console.WriteLine("\nJa existe um usuario com esse nome"); exists = 1; break; } } if (exists == 1) { break; } Console.Clear(); Console.WriteLine("\nEscolha se o usuario pode criar planos: \n1-Sim\n2-Nao"); int auxUser = Int32.Parse(Console.ReadLine()); bool canCreate = false; if (auxUser == 1) { canCreate = true; } else { canCreate = false; } Console.Clear(); User uInsert = new User(userName, 0, DateTime.Now, DateTime.Now, canCreate, false); Console.WriteLine("\nConfirme seus dados: "); Console.WriteLine(uInsert); Console.WriteLine("\n1-Sim\n2-Nao"); confirm = Int32.Parse(Console.ReadLine()); if (confirm == 1) { u.insertUser(uInsert); } else { Console.WriteLine("\nOperacao cancelada!"); } break; case 3: typeList = pt.getType(); Console.WriteLine("\nInsira o nome do usuario: "); string typeName = Console.ReadLine(); foreach (var item in typeList) { if (item.Name.Contains(typeName)) { Console.WriteLine("\nJa existe um tipo de plano com esse nome"); exists = 1; break; } } if (exists == 1) { break; } Console.Clear(); PlanType typeInsert = new PlanType(typeName, 0); Console.WriteLine("\nConfirme seus dados: "); Console.WriteLine(typeInsert); Console.WriteLine("\n1-Sim\n2-Nao"); confirm = Int32.Parse(Console.ReadLine()); if (confirm == 1) { pt.insertType(typeInsert); } else { Console.WriteLine("\nOperacao cancelada!"); } break; case 4: statusList = ps.getStatus(); Console.WriteLine("\nInsira o nome do status: "); string statusName = Console.ReadLine(); foreach (var item in statusList) { if (item.Name.Contains(statusName)) { Console.WriteLine("\nJa existe um status de plano com esse nome"); exists = 1; break; } } if (exists == 1) { break; } Console.Clear(); PlanStatus stInsert = new PlanStatus(statusName, 0); Console.WriteLine("\nConfirme seus dados: "); Console.WriteLine(stInsert); Console.WriteLine("\n1-Sim\n2-Nao"); confirm = Int32.Parse(Console.ReadLine()); if (confirm == 1) { ps.insertStatus(stInsert); } else { Console.WriteLine("\nOperacao cancelada!"); } break; } Submenu(op); }
void SetInitialGameSettings() { GenerateColorBoard(); UserDAO userDAO = new UserDAO(); movesOverEmptyTiles = 0; isGameOver = false; backPress = false; PathPieces = new Stack<Piece>(); //(1)//currentPlayerPanel = GameObject.Find("CurrentPlayerPanel"); //(2)//remainingTimePlayer = currentPlayerPanel.transform.Find("RemainingTime").GetComponent<Text>(); //Use this call instead two GameObject.Find (1) and (2) as possible. remainingTimePlayer = GameObject.Find("CurrentPlayerPanel/RemainingTime").GetComponent<Text>(); remainingTimePlayer.text = formatTime; MovesBoardController.Instance.FindViewByID(); MovesBoardController.Instance.HideAllMessages(); GameApplication.Instance.Players = new List<User>(); User player; playersPanel = GameObject.Find("PlayersPanel"); for(int i = 1; i < numPlayers + 1; i++){ player = new User(); if(i==1){ player = userDAO.LoadUserFromLocalMemory(); GameObject Player1 = GameObject.Find("Player1"); RectTransform Player1Info = Player1.transform.Find("PlayerInfo").GetComponent<RectTransform>(); Text player1Text = Player1Info.transform.Find("TextName").GetComponent<Text>(); if((player.AvatarName == null || player.AvatarName.Length<1)){ player1Text.text = "Player1"; } else{ player1Text.text = player.AvatarName; } player.RemainingTime = timer; GameApplication.Instance.Players.Add(player); playerPanelP1 = playersPanel.transform.Find("Player1").GetComponent<RectTransform>(); gameButtonsP1 = playerPanelP1.transform.Find("GameButtons").GetComponent<CanvasGroup>(); gameButtonsP1.alpha = 1; } else{ GameObject playerN = GameObject.Find("Player" + i); RectTransform PlayerInfo = playerN.transform.Find("PlayerInfo").GetComponent<RectTransform>(); Text playerNText = PlayerInfo.transform.Find("TextName").GetComponent<Text>(); player.AvatarName = "Player" + i; playerNText.text = player.AvatarName; player.RemainingTime = timer; GameApplication.Instance.Players.Add(player); if(i == 2){ playerPanelP2 = playersPanel.transform.Find("Player" + i).GetComponent<RectTransform>(); gameButtonsP2 = playerPanelP2.transform.Find("GameButtons").GetComponent<CanvasGroup>(); gameButtonsP2.alpha = 0; } } } colorSelector = GameObject.Find("ColorSelector"); GameApplication.Instance.AvailableColors = new List<string>(); for(int i=0; i< MAX_COLORS ; i++) { Image selector = colorSelector.transform.GetChild(i).GetComponent<Image>(); if(i!=0){ selector.enabled = false; } } //currentPlayerName = currentPlayerPanel.transform.Find("CurrentPlayerName").GetComponent<Text>(); currentPlayerName = GameObject.Find("CurrentPlayerPanel/CurrentPlayerName").GetComponent<Text>(); if(currentPlayer == null){ currentPlayer = "Player1"; currentPlayerName.text = (GameApplication.Instance.Players[0].AvatarName == null || GameApplication.Instance.Players[0].AvatarName.Length < 1) ? currentPlayer : GameApplication.Instance.Players[0].AvatarName; } }
public static void Update(int op) { Console.Clear(); PlanDAO p = new PlanDAO(); UserDAO u = new UserDAO(); PlanTypeDAO pt = new PlanTypeDAO(); PlanStatusDAO ps = new PlanStatusDAO(); string aux = ""; int confirm = 0; int exists = 0; switch (op) { case 1: planList = p.getPlans(); typeList = pt.getType(); userList = u.getUser(); statusList = ps.getStatus(); Console.WriteLine("\nInsira o nome do plano a ser modificado: "); string planName = Console.ReadLine(); int idType; int idUser; int idStatus; DateTime sDate; DateTime eDate; string desc; decimal cost; Plan original = new Plan(); foreach (var item in planList) { if (item.Name.Contains(planName)) { original = item; exists = 1; break; } } if (exists == 0) { Console.WriteLine("\nNao existe um plano com esse nome"); break; } Console.Clear(); Console.WriteLine("\nQuer modificar o nome do plano?"); Console.WriteLine("\n1-Sim\n2-Nao"); confirm = Int32.Parse(Console.ReadLine()); if (confirm == 1) { Console.WriteLine("\nDigite o novo nome: "); planName = Console.ReadLine(); } else { planName = original.Name; } Console.Clear(); Console.WriteLine("\nQuer modificar o tipo do plano?"); Console.WriteLine("\n1-Sim\n2-Nao"); confirm = Int32.Parse(Console.ReadLine()); if (confirm == 1) { Console.WriteLine("\nEscolha o novo tipo: "); foreach (var item in typeList) { Console.WriteLine(item.Id + "-" + item.Name); } idType = Int32.Parse(Console.ReadLine()); } else { idType = original.Type.Id; } Console.Clear(); Console.WriteLine("\nQuer modificar o responsavel do plano?"); Console.WriteLine("\n1-Sim\n2-Nao"); confirm = Int32.Parse(Console.ReadLine()); if (confirm == 1) { Console.WriteLine("\nEscolha o novo responsavel: "); foreach (var item in userList) { Console.WriteLine(item.Id + "-" + item.Name); } idUser = Int32.Parse(Console.ReadLine()); } else { idUser = original.Responsible.Id; } Console.Clear(); Console.WriteLine("\nQuer modificar o status do plano?"); Console.WriteLine("\n1-Sim\n2-Nao"); confirm = Int32.Parse(Console.ReadLine()); if (confirm == 1) { Console.WriteLine("\nEscolha o novo status: "); foreach (var item in statusList) { Console.WriteLine(item.Id + "-" + item.Name); } idStatus = Int32.Parse(Console.ReadLine()); } else { idStatus = original.Status.Id; } Console.Clear(); Console.WriteLine("\nQuer modificar a data de inicio do plano?"); Console.WriteLine("\n1-Sim\n2-Nao"); confirm = Int32.Parse(Console.ReadLine()); if (confirm == 1) { Console.WriteLine("\nEscolha a nova data: "); sDate = DateTime.Parse(Console.ReadLine()); } else { sDate = original.StartDate; } Console.Clear(); Console.WriteLine("\nQuer modificar a data de fim do plano?"); Console.WriteLine("\n1-Sim\n2-Nao"); confirm = Int32.Parse(Console.ReadLine()); if (confirm == 1) { Console.WriteLine("\nEscolha a nova data: "); eDate = DateTime.Parse(Console.ReadLine()); } else { eDate = original.EndDate; } Console.Clear(); Console.WriteLine("\nQuer modificar a descricao do plano?"); Console.WriteLine("\n1-Sim\n2-Nao"); confirm = Int32.Parse(Console.ReadLine()); if (confirm == 1) { Console.WriteLine("\nDigite a nova descricao: "); desc = Console.ReadLine(); } else { desc = original.Description; } Console.Clear(); Console.WriteLine("\nQuer modificar o custo do plano?"); Console.WriteLine("\n1-Sim\n2-Nao"); confirm = Int32.Parse(Console.ReadLine()); if (confirm == 1) { Console.WriteLine("\nEscolha o novo custo: "); cost = Decimal.Parse(Console.ReadLine()); } else { cost = original.Cost; } Console.Clear(); Plan pInsert = new Plan(planName, original.Id, pt.getOneType(idType), u.getResponsible(idUser), ps.getOneStatus(idStatus), sDate, eDate, desc, cost); Console.WriteLine("\nConfirme seus dados: "); Console.WriteLine(pInsert); Console.WriteLine("\n1-Sim\n2-Nao"); confirm = Int32.Parse(Console.ReadLine()); if (confirm == 1) { p.updatePlan(pInsert); } else { Console.WriteLine("\nOperacao cancelada!"); } break; //--------------------------------------------------------------------------------------------------------------------------------------- case 2: userList = u.getUser(); Console.WriteLine("\nInsira o nome do usuario a ser modificado: "); string userName = Console.ReadLine(); User userOriginal = new User(); foreach (var item in userList) { if (item.Name.Contains(userName)) { userOriginal = item; exists = 1; break; } } if (exists == 0) { Console.WriteLine("\nNao existe um usuario com esse nome"); break; } Console.Clear(); Console.WriteLine("\nQuer modificar o nome do usuario?"); Console.WriteLine("\n1-Sim\n2-Nao"); confirm = Int32.Parse(Console.ReadLine()); if (confirm == 1) { Console.WriteLine("\nDigite o novo nome: "); userName = Console.ReadLine(); } else { userName = userOriginal.Name; } Console.Clear(); Console.WriteLine("\nQuer modificar se o usuario pode criar planos?"); Console.WriteLine("\n1-Sim\n2-Nao"); confirm = Int32.Parse(Console.ReadLine()); int auxUser = 0; bool canCreate = false; if (confirm == 1) { Console.WriteLine("\nEscolha se o usuario pode criar planos: \n1-Sim\n2-Nao"); auxUser = Int32.Parse(Console.ReadLine()); if (auxUser == 1) { canCreate = true; } else { canCreate = false; } } else { canCreate = userOriginal.CanCreatePlan; } Console.Clear(); Console.WriteLine("\nQuer modificar se o usuario vai ser removido?"); Console.WriteLine("\n1-Sim\n2-Nao"); confirm = Int32.Parse(Console.ReadLine()); int auxRemoved = 0; bool remo = false; if (confirm == 1) { Console.WriteLine("\nEscolha se o usuario vai ser removido: \n1-Sim\n2-Nao"); auxRemoved = Int32.Parse(Console.ReadLine()); if (auxRemoved == 1) { remo = true; } else { remo = false; } } else { remo = userOriginal.Removed; } Console.Clear(); User uInsert = new User(userName, userOriginal.Id, userOriginal.RegisterDate, DateTime.Now, canCreate, remo); Console.WriteLine("\nConfirme seus dados: "); Console.WriteLine(uInsert); Console.WriteLine("\n1-Sim\n2-Nao"); confirm = Int32.Parse(Console.ReadLine()); if (confirm == 1) { u.insertUser(uInsert); } else { Console.WriteLine("\nOperacao cancelada!"); } break; case 3: typeList = pt.getType(); Console.WriteLine("\nInsira o nome do usuario a ser modificado: "); string typeName = Console.ReadLine(); PlanType ptOriginal = new PlanType(); foreach (var item in typeList) { if (item.Name.Contains(typeName)) { ptOriginal = item; exists = 1; break; } } if (exists == 0) { Console.WriteLine("\nNao existe um tipo de plano com esse nome"); break; } Console.Clear(); Console.WriteLine("\nQuer modificar o nome do tipo de plano?"); Console.WriteLine("\n1-Sim\n2-Nao"); confirm = Int32.Parse(Console.ReadLine()); if (confirm == 1) { Console.WriteLine("\nDigite o novo nome do tipo de plano: "); typeName = Console.ReadLine(); } else { typeName = ptOriginal.Name; } Console.Clear(); PlanType typeInsert = new PlanType(typeName, ptOriginal.Id); Console.WriteLine("\nConfirme seus dados: "); Console.WriteLine(typeInsert); Console.WriteLine("\n1-Sim\n2-Nao"); confirm = Int32.Parse(Console.ReadLine()); if (confirm == 1) { pt.insertType(typeInsert); } else { Console.WriteLine("\nOperacao cancelada!"); } break; case 4: statusList = ps.getStatus(); Console.WriteLine("\nInsira o nome do status: "); string statusName = Console.ReadLine(); PlanStatus psOriginal = new PlanStatus(); foreach (var item in statusList) { if (item.Name.Contains(statusName)) { psOriginal = item; exists = 1; break; } } if (exists == 0) { Console.WriteLine("\nNao existe um status de plano com esse nome"); break; } Console.Clear(); Console.WriteLine("\nQuer modificar o nome do status?"); Console.WriteLine("\n1-Sim\n2-Nao"); confirm = Int32.Parse(Console.ReadLine()); if (confirm == 1) { Console.WriteLine("\nDigite o novo nome do status: "); statusName = Console.ReadLine(); } else { statusName = psOriginal.Name; } Console.Clear(); PlanStatus stInsert = new PlanStatus(statusName, psOriginal.Id); Console.WriteLine("\nConfirme seus dados: "); Console.WriteLine(stInsert); Console.WriteLine("\n1-Sim\n2-Nao"); confirm = Int32.Parse(Console.ReadLine()); if (confirm == 1) { ps.insertStatus(stInsert); } else { Console.WriteLine("\nOperacao cancelada!"); } break; } Submenu(op); }
private static UserDAO UserToUserDAO(User user) { UserKey userKey = user.GetUserKey(); UserDAO userDAO = GetExistingUserDAO(userKey); if (userDAO == null) { userDAO = new UserDAO(user.UserID ,user.UserLogin); userDaoCollection.Add(userKey, userDAO); } return userDAO; }
public User findUserById(string userId) { UserDAO udao = new UserDAO(); return(udao.FindByID(userId)); }