public bool sendMultiNotification(User usr, string subject, string msgBody)
        {
            try
            {
                String fromEmail = (from u in ContextDB.Users
                                    where u.Emp_ID == usr.Emp_ID
                                    select new { u.Email }).ToString();

                List<String> lstToEmail = (from u in ContextDB.Users
                                  join d in ContextDB.Departments on u.Dept_ID equals d.Dept_ID
                                  select u.Email).ToList<String>();

                MailMessage mailMessage = new MailMessage();
                mailMessage.To.Add(lstToEmail.First());
                mailMessage.From = new MailAddress(fromEmail);
                //mailMessage.CC.Add("*****@*****.**");
                mailMessage.Subject = subject;
                mailMessage.Body = msgBody;
                //  SmtpClient smtpClient = new SmtpClient("mail.singnet.com.sg");

                for (int i = 1; i < lstToEmail.Count; i++)
                {
                    mailMessage.CC.Add(lstToEmail[i]);
                }

                SmtpClient smtpClient = new SmtpClient("lynx.iss.nus.edu.sg");
                smtpClient.Send(mailMessage);

                return true;
            }
            catch (Exception e)
            {
                return false;
            }
        }
        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            User u = new DAL.User();

            u.UserID   = int.Parse(hdUserID.Value);
            u.RoleID   = int.Parse(ddlRoles.SelectedValue);
            u.FullName = txtFullName.Text;
            u.Username = txtUsername.Text;
            if (txtPassword.Text != "")
            {
                u.Password = uBLL.md5(txtPassword.Text);
            }
            else
            {
                u.Password = uBLL.GetUserById(int.Parse(hdUserID.Value)).Password;
            }
            u.Address     = txtAddress.Text;
            u.Phone       = txtPhone.Text;
            u.CreatedDate = DateTime.Now;
            u.Status      = ddlStatus.SelectedValue == "1" ? true : false;
            uBLL.Update(u);
            string message = "Cập nhật thành công!";
            string url     = "/AdminCP/ListUsers.aspx";
            string script  = "$(document).ready(function (e) {";

            script += "    bootbox.alert('" + message + "', function () {";
            script += "        window.location = '" + url + "';";
            script += "    });";
            script += "});";
            ClientScript.RegisterStartupScript(this.GetType(), "Redirect", script, true);
        }
        public ActionResult EditProfile(ProfileModel model)
        {
            var currentlyLoggedInUserId = (int)Session["UserId"];
            if (!ModelState.IsValid)
            {

                var user = UserRepository.GetUser(currentlyLoggedInUserId);
                model.StatusDropdown = getListForStatusDropdown(user.Status);
                return View(model);
            }
            var userModel = new User();
            userModel.LastName = model.LastName;
            userModel.FirstName = model.FirstName;
            userModel.About = model.About;
            userModel.City = model.City;
            userModel.Weight = model.Weight;
            userModel.Length = model.Length;
            userModel.Quote = model.Quote;
            userModel.Work = model.Work;
            userModel.Status = model.Status;

            UserRepository.UpdateUser(userModel, currentlyLoggedInUserId);

            return RedirectToAction("Profile", "Profile");
        }
        public MembershipUser CreateUser(string email, string password)
        {
            MembershipUser membershipUser = GetUser(email, false);

            if (membershipUser != null)
            {
                return null;
            }

            var user = new User
            {
                Email = email,
                Password = Crypto.HashPassword(password),
                CreationDate = DateTime.Now
            };

            var role = RoleRepository.GetAllRoles().FirstOrDefault(r => r.Name == "User");
            if (role != null)
            {
                user.RoleID = role.ID;
            }

            UserRepository.CreateUser(user);
            membershipUser = GetUser(email, false);
            return membershipUser;
        }
Exemplo n.º 5
0
        public ActionResult Edit(int?i)
        {
            if (Session["UserID"] != null && Session["UserType"].ToString().ToLower() == "admin")
            {
                if (i != null)
                {
                    DAL.User  u  = uRepo.GetByID((int)i);
                    UserModel um = new UserModel()
                    {
                        ID = u.ID, Mail = u.Mail, Name = u.Name, NrOrders = (int)u.NrOrders, Type = u.Type
                    };

                    if (u.DOB != null)
                    {
                        um.DOB = (DateTime)u.DOB;
                    }
                    else
                    {
                        um.DOB = new DateTime();
                    }

                    return(View(um));
                }
            }

            return(RedirectToAction("Login", "Home", new { area = "" }));
        }
Exemplo n.º 6
0
 public List<User> ReadUser(string statement, SqlParameter[] parameters)
 {
     using (SqlConnection connection = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=HelloMVC;Integrated Security=SSPI;"))
     {
         connection.Open();
         using (SqlCommand command = new SqlCommand(statement, connection))
         {
             command.CommandType = System.Data.CommandType.StoredProcedure;
             if (parameters != null)
             {
                 command.Parameters.AddRange(parameters);
             }
             SqlDataReader data = command.ExecuteReader();
             List<User> users = new List<User>();
             while (data.Read())
             {
                 User user = new User();
                 user.ID = Convert.ToInt32(data["ID"]);
                 user.Email = data["Email"].ToString();
                 user.Password = data["Password"].ToString();
                 users.Add(user);
             }
             try
             {
                 return users;
             }
             catch
             {
                 return null;
             }
         }
     }
 }
Exemplo n.º 7
0
        public override void Execute()
        {
            using (AppDbContext db = new AppDbContext())
            {
                Program.Logger.Debug($"{GetType().Name}: Searching user with TelegramId: {Message.From.Id} in database");
                var user = db.GetUserByTelegramId(Message.From.Id);
                if (user == null)
                {
                    user = new User
                    {
                        TelegramUserId = Message.From.Id,
                        FirstName = Message.From.FirstName,
                        LastName = Message.From.LastName,
                        Username = Message.From.Username
                    };

                    Program.Logger.Info($"{GetType().Name}: {user} is new User");
                    Program.Logger.Debug($"{GetType().Name}: Adding user {user} to database");
                    db.Users.Add(user);
                }
                else
                {
                    Program.Logger.Debug($"{GetType().Name}: User {user} is already exist");
                }

                Program.Logger.Debug($"{GetType().Name}: Subscribing {user} to all shows");
                var subscriptions = user.Subscriptions.ToList();
                foreach (Show show in db.Shows)
                {
                    Subscription subscription = new Subscription
                    {
                        User = user,
                        Show = show,
                        SubscriptionDate = DateTime.Now
                    };

                    if (subscriptions.Any(s => Equals(s.Show, show)))
                    {
                        continue;
                    }

                    db.Subscriptions.Add(subscription);
                }

                Program.Logger.Debug($"{GetType().Name}: Saving changes to database");
                db.SaveChanges();
            }

            Program.Logger.Debug($"{GetType().Name}: Sending response to {Message.From}");
            try
            {
                TelegramApi.SendMessage(Message.From, "Вы, братишка, подписаны на все сериалы");
            }
            catch (Exception e)
            {
                throw new Exception($"{GetType().Name}: An error occurred while sending response to {Message.From}", e);
            }

            Status = true;
        }
Exemplo n.º 8
0
 public static bool Update(DAL.User update_user)
 {
     DAL.User old_user = db.Users.Where(u => u.mail == update_user.mail).FirstOrDefault();
     old_user = update_user;
     db.SaveChanges();
     return(true);
 }
Exemplo n.º 9
0
        public User getUser(User usr)
        {
            var q = from u in ContextDB.Users
                    where u.Emp_ID == usr.Emp_ID
                    select u;

            return q.First();
        }
 public void Add(User user)
 {
     using (var db = new BusinessCardScannerEntities())
     {
         db.Configuration.ProxyCreationEnabled = false;
         db.User.Add(user);
         db.SaveChanges();
     }
 }
Exemplo n.º 11
0
 //null פונקצית כניסה האם המשתמש קים ומחזירה את המשתמש שנמצא או
 public static DTO.UserDTO Login(string UserPhone)
 {
     DAL.User u1 = db.Users.FirstOrDefault(u => u.UserPhone == UserPhone);
     if (u1 != null)
     {
         return(BLL.Convertions.UserToDto(u1));
     }
     return(null);
 }
Exemplo n.º 12
0
        public void ShopAdo_PropertyChangedUser(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            User u = sender as User;

            DAL.User du = unitOfWork.User.Get(u.UserId);
            du.Login    = u.Login;
            du.Password = u.Password;
            du.RoleId   = u.RoleId;
        }
Exemplo n.º 13
0
 public void CreateUser(User user)
 {
     SqlParameter[] parameters = new SqlParameter[]
     {
         new SqlParameter("@Email", user.Email),
         new SqlParameter("@Password", user.Password)
     };
     Write("CreateUser", parameters);
 }
Exemplo n.º 14
0
        private BE.Models.User ToUser(DAL.User userEntity)
        {
            BE.Models.User newUser = new BE.Models.User();

            newUser.id       = userEntity.id;
            newUser.nombre   = userEntity.nombre;
            newUser.password = userEntity.password;
            newUser.email    = userEntity.email;
            newUser.apellido = userEntity.apellido;

            return(newUser);
        }
Exemplo n.º 15
0
        //הרשמה-בלי בדיקות ולידציה הכנסת משתמש חדש
        public static bool Register(DAL.User user)
        {
            var a = db.Users.Where(u => u.mail == user.mail).FirstOrDefault();

            if (a != null)
            {
                return(false);
            }
            db.Users.Add(user);
            db.SaveChanges();
            return(true);
        }
        public ActionResult Register(RegisterModel registerModel)
        {
            if (ModelState.IsValid)
                {
                    var checkUsername = RegisterRepository.CheckIfUsernameExists(registerModel.RegisterUsername);

                    if (checkUsername != null)
                    {
                        ModelState.AddModelError("NameTaken", "Användarnamnet finns redan");
                        return View();
                    }
                    var checkIfEmailExists = RegisterRepository.CheckIfEmailExists(registerModel.RegisterEmail);

                    if (checkIfEmailExists != null)
                    {
                        ModelState.AddModelError("EmailTaken", "Emailadressen finns redan registrerad");
                        return View();
                    }

                    //Encrypts the password
                    var crypto = new SimpleCrypto.PBKDF2();
                    var encryptedPassword = crypto.Compute(registerModel.Registerpassword);

                    //Creates an new usermodel and sets the values
                    var registerUser = new User
                    {
                        Password = encryptedPassword,
                        PasswordSalt = crypto.Salt,
                        Username = registerModel.RegisterUsername,
                        Email = registerModel.RegisterEmail,
                        Gender = registerModel.Gender,
                        Birthdate = registerModel.BirthDate
                    };

                    //registers the user
                    RegisterRepository.RegisterUser(registerUser);

                    //Sets the subject and the body for the confirmation email
                    string subject =  "Tack för registreringen hos SuperAtleten";
                    string mailbody= "Hej " + registerModel.RegisterUsername + "<br /> Tack för att du registrerat dig hos " +
                                      "oss , vi hoppas att du kommer att tycka om vår tjänst. <br /><hr />"+
                                      "Dina inloggningsuppgifter <br />" +
                                      "E-mail : " + registerModel.RegisterEmail + "<br />" +
                                       "Lösenord : " + registerModel.Registerpassword;
                    //sends the email
                    MailSender.sendMail(subject,mailbody,registerModel.RegisterEmail);

                    TempData["Message"] = "Registreringen lyckades , Du kan nu logga in med dina användaruppgifter.";
                    return RedirectToAction("Index", "Home");
                }
            ModelState.AddModelError("RegisterFail", " - Registreringen misslyckades!");
            return View();
        }
Exemplo n.º 17
0
 public bool Add(User user)
 {
     using (var dbContext = new TwitterEntities())
     {
         user.Password = Encryptdata(user.Password);
         dbContext.Users.Add(user);
         if (dbContext.SaveChanges() > 0)
             return true;
         else
             return false;
     }
 }
Exemplo n.º 18
0
    /*
     * Kiểm tra user dựa vào username và email
     */
    public bool CheckUserResetPassword(string userName, string email, ref string maDonVi)
    {
        DAL.User user    = dataContext.Users.Where(t => t.UserName == userName && t.Email == email).FirstOrDefault();
        bool     hasUser = user != null;

        if (hasUser)
        {
            //lấy mã đơn vị của người đăng nhập vào
            maDonVi = (from t in dataContext.DONVI_Users
                       where t.UserID == user.ID
                       select t.DonViID).FirstOrDefault();
        }
        return(hasUser);
    }
Exemplo n.º 19
0
 //פונקציה שמוסיפה משתמש או מוקדן
 public static DTO.UserDTO AddMokdanOrUser(DTO.UserDTO user)
 {
     DAL.User u1 = BLL.Convertions.UserDtoToDAL(user);
     if (Login(u1.UserPhone) == null)
     {
         //u1.RoleId = 3;
         db.Users.Add(u1);
         db.SaveChanges();
         return(BLL.Convertions.UserToDto(u1));
     }
     else
     {
         return(null);
     }
 }
Exemplo n.º 20
0
        public static UserDto ToDTO(DAL.User model)
        {
            if (model is null)
            {
                return(null);
            }
            return(new UserDto()
            {
                UserID = model.UserId,
                UserName = model.UserName,
                UserPassword = model.UserPassword,
                //  HostDto=Host.ToDTO(model.Host),
//TravelerDto=Traveler.ToDTO(model.Traveler)
            });
        }
Exemplo n.º 21
0
        public List<User> getEmp(User usr)
        {
            var q = from u in ContextDB.Users
                    where (u.Emp_ID == usr.Emp_ID || usr.Emp_ID == null)
                    && (u.Emp_Name == usr.Emp_Name || usr.Emp_Name == null)
                    && (u.Dept_ID == usr.Dept_ID || usr.Dept_ID == null)
                    && (u.Email == usr.Email || usr.Email == null)
                    && (u.Password == usr.Password || usr.Password == null)
                    && (u.Phone == usr.Phone || usr.Phone == null)
                    && (u.DOB == usr.DOB || usr.DOB == null)
                    && (u.Role == usr.Role || usr.Role == null)
                    select u;

            return q.ToList<User>();
        }
Exemplo n.º 22
0
        public static User_DTO getUser_DTO(DAL.User user)
        {
            User_DTO newUserDTO = new User_DTO();

            newUserDTO.id         = user.id;
            newUserDTO.mail       = user.mail;
            newUserDTO.password   = user.password;
            newUserDTO.overide    = user.overide;
            newUserDTO.attachment = user.attachment;
            List <string> newConcatList = new List <string>();

            newConcatList.AddRange(db.Contacts.Where(i => i.userId == user.id).Select(i => i.mailContact));
            newUserDTO.contact_list = newConcatList;
            return(newUserDTO);
        }
Exemplo n.º 23
0
        public void CreateUser(string fname, string lname, string uname, string email)
        {
            using (var db = new BalderDataContext())
            {
                User u = new User();

                u.FName = fname;
                u.LName = lname;
                u.UserName = uname;
                u.Email = email;

                db.Users.InsertOnSubmit(u);
                db.SubmitChanges();
            }
        }
Exemplo n.º 24
0
 //פונקציה ששומרת את השינויים על עריכת משתמש
 public static void UpdateEditUser(DTO.UserDTO user)
 {
     DAL.User u1 = BLL.Convertions.UserDtoToDAL(user);
     DAL.User u2 = db.Users.FirstOrDefault(u => u.UserId == u1.UserId);
     if (u2 != null)
     {
         u2.UserPassword      = u1.UserPassword;
         u2.UserPhone         = u1.UserPhone;
         u2.UserRecognizeName = u1.UserRecognizeName;
         u2.UserFullName      = u1.UserFullName;
         u2.UserEmail         = u1.UserEmail;
         u2.UserAddress       = u1.UserAddress;
         u2.RoleId            = u1.RoleId;
         db.SaveChanges();
     }
 }
Exemplo n.º 25
0
        private DAL.User ToUserEntity(BE.Models.User user)
        {
            DAL.User newUser = new DAL.User();

            newUser.id     = user.id;
            newUser.nombre = user.nombre;

            if (!string.IsNullOrEmpty(user.password))
            {
                newUser.password = EncryptHelper.Encrypt(user.password);
            }

            newUser.email    = user.email;
            newUser.apellido = user.apellido;

            return(newUser);
        }
Exemplo n.º 26
0
        public void Delete_UserExist_True()
        {
            //arrange
            User user = new User()
            {
                First_Name = "Ion",
                Last_Name = "Rosca",
                Password = "******",
                Email = "*****@*****.**"
            };
            UsersDal User = new UsersDal();
            //act
            User.Add(user);
            bool result = User.Delete(user.id_user);

            //assert
            Assert.AreEqual(true, result);
        }
Exemplo n.º 27
0
        public bool deleteEmp(User usr)
        {
            if (usr.Equals(null))
            {
                return false;
            }

            try
            {
                ContextDB.Users.DeleteObject(usr);
                ContextDB.SaveChanges();

                return true;
            }
            catch (Exception e)
            {
                return false;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            //Session["Emp_ID"] = "Emp17";
            UsersEnt supE = new UsersEnt();
            User usr = new User();

            usr.Emp_ID = (string)Session["Emp_ID"];
            usr = supE.getEmp(usr).First();

            NotificationMsg nm = new NotificationMsg();
            int cntMsg = nm.countMailBox((string)Session["Emp_ID"]);

            int cntInbox = cntMsg;
            //int cntInbox = 2;

            param1.Value = Convert.ToString(cntInbox);
            param_Emp.Value = usr.Emp_Name;
            param_Role.Value = usr.Role;
        }
Exemplo n.º 29
0
 public static DAL.User getUser_Dal(User_DTO user)
 {
     DAL.User newUserDAL = new DAL.User();
     newUserDAL.id         = user.id;
     newUserDAL.mail       = user.mail;
     newUserDAL.password   = user.password;
     newUserDAL.overide    = user.overide;
     newUserDAL.attachment = user.attachment;
     if (user.contact_list != null)
     {
         foreach (var item in user.contact_list)
         {
             DAL.Contact c = new DAL.Contact();
             c.userId      = user.id;
             c.mailContact = item;
             db.Contacts.Add(c);
         }
     }
     return(newUserDAL);
 }
Exemplo n.º 30
0
    public Estimate CreateEstimate()
    {
        Estimate temp = new Estimate();
        DateTime? nullDate = null;

        temp.JobName = this.currentProspect.Id;

        var giggles = DAL.User.GetUserFromLogin(Page.User.Identity.Name);

        temp.Estimator = giggles.Id;
        temp.EstimateNumber = Estimate.GetNextEstimateNumberForJob(currentProspect.Id);
        temp.Received = DateTime.Now;
        temp.Priority = Estimate.GetNextPriority();
        temp.ReadyForEstimating = true;
        temp.Received = DateTime.Now;
        temp.CurrentStatus = DateTime.Now.ToString("d") + " - Received by Estimating.";
        temp.EstimateSent = false;
        temp.EstimateSentDate = nullDate;
        temp.EstimatesDirectory = currentProspect.DirectoryPathExec;
        temp.ProspectDirectory = currentProspect.DirectoryPath;

        temp.Save();

        DAL.User estimator = new DAL.User(temp.Estimator);

        EstimateTimeline tempStep = new EstimateTimeline();
        tempStep.EstimateID = temp.Id;
        tempStep.WorkflowStepID = 131;
        tempStep.StepX = 0;
        tempStep.ResponsibleUserID = temp.Estimator;
        tempStep.DateTimeStamp = DateTime.Now;
        tempStep.DisplayText = DateTime.Now.ToString("d") + " - Received by Estimating.  Assigned to " + estimator.Name;

        tempStep.Save();

        CreateEstNumberDir(temp.EstimateNumber);

        BindControls(Estimate.Filter.Active);

        return temp;
    }
        public ActionResult Register()
        {
            ViewBag.Page = "Register";
            if (Request.Cookies["user"] == null)
            {
                return(View());
            }

            UserVM user   = new UserVM();
            User   myUser = new DAL.User();

            if (Session["user"] == null)
            {
                UserManager tmpUM = new UserManager();
                Int64       id;
                if (Int64.TryParse(Request.Cookies["user"]["ID"].ToString(), out id))
                {
                    myUser = tmpUM.GetUser(id);
                }
            }
            else
            {
                myUser = (User)Session["user"];
            }

            if (myUser == null)
            {
                return(View());
            }

            user.Birthdate = myUser.Birthdate;
            user.Email     = myUser.Email;
            user.FirstName = myUser.FirstName;
            user.LastName  = myUser.LastName;
            user.Password  = myUser.Password;
            user.UserName  = myUser.UserName;

            return(View(user));
        }
Exemplo n.º 32
0
        public ActionResult Edit(UserModel um)
        {
            if (Session["UserID"] != null && Session["UserType"].ToString().ToLower() == "admin")
            {
                if (um != null)
                {
                    DAL.User uU = uRepo.GetByID(um.ID);
                    uU.DOB       = um.DOB;
                    uU.ID        = um.ID;
                    uU.IsDeleted = false;
                    uU.Mail      = um.Mail;
                    uU.Name      = um.Name;
                    uU.NrOrders  = um.NrOrders;
                    uU.Type      = um.Type;

                    uRepo.Update(uU);
                    return(RedirectToAction("Index", "User"));
                }
            }

            return(RedirectToAction("Login", "Home", new { area = "" }));
        }
Exemplo n.º 33
0
        public IHttpActionResult PostUser(User user)
        {
            User model         = new DAL.User();
            var  salt          = CommonFunction.CreateSalt(64); //Generate a cryptographic random number.
            var  hashAlgorithm = new SHA512HashAlgorithm();

            model.PasswordSalt = salt;
            model.PasswordHash = hashAlgorithm.GenerateSaltedHash(CommonFunction.GetBytes(user.Password), salt);
            model.FirstName    = user.FirstName;
            model.MiddleName   = user.MiddleName;
            model.LastName     = user.LastName;
            model.IsVerified   = user.IsVerified;
            model.Password     = user.Password;
            model.Phone        = user.Phone;
            model.RoleID       = user.RoleID;
            model.BranchID     = user.BranchID;
            model.Email        = user.Email;
            model.IsActive     = true;
            model.CreatedOn    = System.DateTime.UtcNow;
            model.UpdatedOn    = System.DateTime.UtcNow;
            db.Users.Add(model);
            db.SaveChanges();
            return(Ok(true));
        }
Exemplo n.º 34
0
        private bool UserHasSubscriptions(User user)
        {
            if (user == null)
            {
                Program.Logger.Debug($"{GetType().Name}: User {Message.From} is not exists");
                return false;
            }

            bool userHasSubscriptions;
            using (AppDbContext db = new AppDbContext())
            {
                Program.Logger.Debug($"{GetType().Name}: Checking if user has subscriptions");
                try
                {
                    userHasSubscriptions = db.Subscriptions.Any(s => s.User.Id == user.Id);
                }
                catch (Exception e)
                {
                    throw new Exception($"{GetType().Name}: An error occurred while checking if user has subscriptions", e);
                }
            }
            return userHasSubscriptions;
        }
        public ActionResult Register(UserVM user)
        {
            UserManager userMan = new UserManager();
            bool        flag    = false;

            if (userMan.IsExist(user.UserName))
            {
                ModelState.AddModelError("UserName", "This username already exist!!");
                flag = true;
            }
            if (user.Password != user.PasswordValidation)
            {
                ModelState.AddModelError("password", "The password are not matching!");
                flag = true;
            }
            ViewBag.Page = "Register";
            if (flag)
            {
                return(View("Register"));
            }

            User tmp = new DAL.User()
            {
                FirstName = user.FirstName,
                LastName  = user.LastName,
                Birthdate = user.Birthdate,
                Email     = user.Email,
                UserName  = user.UserName,
                Password  = user.Password
            };

            if (Request.Cookies["user"] == null)
            {
                if (userMan.Add(tmp))
                {
                    Session["user"] = tmp;

                    HttpCookie cookie = new HttpCookie("user");
                    cookie.Values["userName"]  = tmp.UserName;
                    cookie.Values["firstName"] = tmp.FirstName;
                    cookie.Values["lastName"]  = tmp.LastName;
                    cookie.Values["ID"]        = tmp.ID.ToString();
                    cookie.Expires             = DateTime.Now.AddDays(30);
                    Response.Cookies.Add(cookie);

                    ViewBag.Page = "Index";
                    return(View("Index"));
                }
                ViewBag.Message = "Wrong Data";
                ViewBag.Page    = "Register";
                return(View("Register"));
            }
            else
            {
                var test = Request.Cookies["user"]["ID"];
                if (Int64.TryParse(Request.Cookies["user"]["ID"].ToString(), out Int64 ID))
                {
                    if (userMan.Update(ID, tmp))
                    {
                        Session["user"] = tmp;

                        Response.Cookies["user"]["userName"]  = tmp.UserName;
                        Response.Cookies["user"]["firstName"] = tmp.FirstName;
                        Response.Cookies["user"]["lastName"]  = tmp.LastName;
                        Response.Cookies["user"].Expires      = DateTime.Now.AddDays(30);

                        ViewBag.Page = "Index";
                        return(View("Index"));
                    }
                }
                ViewBag.Message = "Wrong Data";
                ViewBag.Page    = "Register";
                return(View("Register"));
            }
        }
Exemplo n.º 36
0
        public User VerifyLogin(string login, string passwd)
        {
            InitDB();
            User _verifieduser = new User();
            Boolean Verified = false;

            using (var session = documentStore.OpenSession())
            {
                var _usr = from x in session.Query<User>()
                           select x;
                foreach (User item in _usr)
                {
                    if (!Verified) _verifieduser = item;
                    if (item.Password == passwd && item.Loginid == login)
                    {
                        Verified = true;
                    }
                }
                if (Verified == true)
                {
                    Console.WriteLine(DateTime.Now.ToShortTimeString() + "  " + DateTime.Now.ToString() + "Login OK");
                    return _verifieduser;
                } else
                {
                    User _newuser = new User();
                    _newuser.Id = "99999";
                    _newuser.Fullname = "failed";
                    _newuser.Loginid = "sys";
                    _newuser.Password = "******";
                    _newuser.Groupid = "sys";
                    return _newuser;
                }
            }
            return null;
        }
Exemplo n.º 37
0
 public Boolean RemoveUser(User userName)
 {
     InitDB();
     using (var session = documentStore.OpenSession())
     {
         User deleteUser = new User();
         deleteUser = session.Load<User>(userName.Id);
         session.Delete(deleteUser);
         session.SaveChanges();
         return true;
     }
     return false;
 }
Exemplo n.º 38
0
 public Boolean InsertUser(User user)
 {
     InitDB();
     using (var session = documentStore.OpenSession())
     {
         User newUser = new User();
         newUser.Fullname = user.Fullname;
         newUser.Loginid = user.Loginid;
         newUser.Groupid = user.Groupid;
         newUser.Password = user.Password;
         session.Store(newUser);
         session.SaveChanges();
         return true;
     }
     return false;
 }
 /*public void Delete(int id)
 {
     using (var db = new BusinessCardScannerEntities())
     {
         User user = GetUser(id);
         user.IsDeleted = true;
         Update(user);
     }
 }*/
 public void Update(User user)
 {
     using (var db = new BusinessCardScannerEntities())
     {
         db.Configuration.ProxyCreationEnabled = false;
         db.Entry(user).State = EntityState.Modified;
         db.SaveChanges();
     }
 }
Exemplo n.º 40
0
        private string Unsubscribe(User user, Show show)
        {
            string response;
            using (AppDbContext db = new AppDbContext())
            {
                Subscription subscription;
                Program.Logger.Debug($"{GetType().Name}: Checking for subscription existence");
                try
                {
                    subscription = db.Subscriptions.FirstOrDefault(s => s.User.Id == user.Id && s.Show.Id == show.Id);
                }
                catch (Exception e)
                {
                    throw new Exception($"{GetType().Name}: An error occurred while checking for subscription existence", e);
                }
                if (subscription != null)
                {
                    Program.Logger.Debug($"{GetType().Name}: Deleting notifications for subscription");
                    try
                    {
                        db.Notifications.RemoveRange(db.Notifications.Where(n => n.Subscription.Id == subscription.Id));
                    }
                    catch (Exception e)
                    {
                        throw new Exception($"{GetType().Name}: An error occurred while deleting notifications for subscription", e);
                    }

                    Program.Logger.Debug($"{GetType().Name}: Deleting subscription");
                    try
                    {
                        db.Subscriptions.Remove(subscription);
                    }
                    catch (Exception e)
                    {
                        throw new Exception($"{GetType().Name}: An error occurred while deleting subscription", e);
                    }

                    try
                    {
                        db.SaveChanges();
                    }
                    catch (Exception e)
                    {
                        throw new Exception($"{GetType().Name}: An error occurred while saving changes to database", e);
                    }
                    response = $"Вы отписались от сериала \"{show.Title}\"";
                }
                else
                {
                    response = $"Вы, братишка, не подписаны на сериал \"{show.Title}\"";
                }
            }
            return response;
        }
        // send mail from employee to dept head
        public bool sendSingleNotification(User usr, string subject, string msgBody)
        {
            try
            {
                string fromEmail = (from u in ContextDB.Users
                              where u.Emp_ID == usr.Emp_ID
                              select u.Email).SingleOrDefault();

                String hID = (from u in ContextDB.Users
                        join d in ContextDB.Departments on u.Dept_ID equals d.Dept_ID
                        where u.Emp_ID == usr.Emp_ID
                        select d.Head_ID).SingleOrDefault();

                String toEmail = (from u in ContextDB.Users
                                  where u.Emp_ID == hID
                                  select u.Email).SingleOrDefault();

                return sendAuthUserNotification(fromEmail, toEmail, subject, msgBody);
            }
            catch (Exception e)
            {
                return false;
            }
        }
Exemplo n.º 42
0
 public Settings GetSettingsByUser(User user)
 {
     return Settings.FirstOrDefault(s => s.User.Id == user.Id);
 }
        public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
        {
            if (_userManager.GetUser(username) == null)
            {
                var user = new User() {UserName = username, Password = password, UserEmailAddress = email};
                _userManager.RegisterUser(user);
            }
            else
            {
                status = MembershipCreateStatus.DuplicateUserName;
                return null;
            }

            status = MembershipCreateStatus.Success;
            return GetUser(username, true);
        }
Exemplo n.º 44
0
        public void Update(int Id,string Name,string MobilePhone,string Email,string OfficePhone,string Username,string Position,string Status,bool? Synched)
        {
            User item = new User();
            item.MarkOld();
            item.IsLoaded = true;

            item.Id = Id;

            item.Name = Name;

            item.MobilePhone = MobilePhone;

            item.Email = Email;

            item.OfficePhone = OfficePhone;

            item.Username = Username;

            item.Position = Position;

            item.Status = Status;

            item.Synched = Synched;

            item.Save(UserName);
        }
Exemplo n.º 45
0
 public Boolean AddTestUser()
 {
     InitDB();
     User newUser = new User();
     using (var session = documentStore.OpenSession())
     {
         User u = new User();
         u.Fullname = "Administrator";
         u.Enabled = true;
         u.Loginid = "admin";
         u.Password = "******";
         u.Groupid = "Administrators";
         session.Store(u);
         session.SaveChanges();
     }
     return true;
 }
Exemplo n.º 46
0
        public void Insert(string Name,string MobilePhone,string Email,string OfficePhone,string Username,string Position,string Status,bool? Synched)
        {
            User item = new User();

            item.Name = Name;

            item.MobilePhone = MobilePhone;

            item.Email = Email;

            item.OfficePhone = OfficePhone;

            item.Username = Username;

            item.Position = Position;

            item.Status = Status;

            item.Synched = Synched;

            item.Save(UserName);
        }
Exemplo n.º 47
0
 public Boolean ChangeUser(User user)
 {
     InitDB();
     User newUser = new User();
     using (var session = documentStore.OpenSession())
     {
         newUser = session.Load<User>(user.Id);
         //newUser.LoadByPrimaryKey((long)user.Id);
         newUser.Fullname = user.Fullname;
         newUser.Loginid = user.Loginid;
         newUser.Groupid = user.Groupid;
         newUser.Password = user.Password;
         session.Store(newUser);
         session.SaveChanges();
         return true;
     }
     return false;
 }
Exemplo n.º 48
0
        public override void Execute()
        {
            Show show;
            string showTitle = string.Empty;
            bool subscribeById = ShowId != null;
            if (ShowId == null)
            {
                int messageSize;
                int.TryParse(Arguments, out messageSize);
                if (messageSize == 0)
                {
                    messageSize = MaxPageSize;
                }
                messageSize = Math.Min(messageSize, MaxPageSize);

                ShowId = RequestShow(out showTitle);
                if (ShowId == null)
                {
                    SendShowList(showTitle, messageSize);
                    Status = true;
                    return;
                }
            }

            string response;
            Program.Logger.Info($"{GetType().Name}: {Message.From} is trying to subscribe to '{(subscribeById ? $"Id = {ShowId}" : showTitle)}'");
            using (AppDbContext db = new AppDbContext())
            {
                show = db.GetShowById(ShowId.Value);
                if (show == null)
                {
                    Program.Logger.Info($"{GetType().Name}: Show '{(subscribeById ? $"Id = {ShowId}" : showTitle)}' was not found");
                    response = $"Сериал '{(subscribeById ? $"Id = {ShowId}" : showTitle)}' не найден";
                    Program.Logger.Debug($"{GetType().Name}: Sending response to {Message.From}");
                    try
                    {
                        TelegramApi.SendMessage(Message.From, response);
                    }
                    catch (Exception e)
                    {
                        throw new Exception($"{GetType().Name}: An error occurred while sending response to {Message.From}", e);
                    }
                    Status = true;
                    return;
                }

                Program.Logger.Debug($"{GetType().Name}: Searching user with TelegramId: {Message.From.Id} in database");
                User user;
                try
                {
                    user = db.GetUserByTelegramId(Message.From.Id);
                }
                catch (Exception e)
                {
                    throw new Exception($"{GetType().Name}: An error occurred while searching user in database", e);
                }
                bool newUser = false;
                if (user == null)
                {
                    user = new User
                    {
                        TelegramUserId = Message.From.Id,
                        FirstName = Message.From.FirstName,
                        LastName = Message.From.LastName,
                        Username = Message.From.Username
                    };
                    newUser = true;
                }

                if (newUser)
                {
                    Program.Logger.Info($"{GetType().Name}: {user} is new User");
                }
                else
                {
                    Program.Logger.Debug($"{GetType().Name}: User {user} is already exist");
                }

                bool subscriptionExists;
                Program.Logger.Debug($"{GetType().Name}: Checking for subscription existence");
                try
                {
                    subscriptionExists = user.Subscriptions.Any(s => s.Show.Id == show.Id);
                }
                catch (Exception e)
                {
                    throw new Exception($"{GetType().Name}: An error occurred while checking for subscription existence", e);
                }
                if (subscriptionExists)
                {
                    Program.Logger.Info($"{GetType().Name}: User {Message.From} is already subscribed to {show.OriginalTitle}");
                    response = $"Вы уже подписаны на сериал '{show.Title}'";
                }
                else
                {
                    Subscription subscription = new Subscription
                    {
                        User = user,
                        Show = show,
                        SubscriptionDate = DateTimeOffset.Now
                    };

                    if (newUser)
                    {
                        user.Subscriptions.Add(subscription);
                        db.Users.Add(user);
                    }
                    else
                    {
                        db.Subscriptions.Add(subscription);
                    }
                    response = $"Вы подписались на сериал '{show.Title}'";
                }

                Program.Logger.Debug($"{GetType().Name}: Saving changes to database");
                try
                {
                    db.SaveChanges();
                }
                catch (Exception e)
                {
                    throw new Exception($"{GetType().Name}: An error occurred while saving changes to database", e);
                }
            }

            Program.Logger.Debug($"{GetType().Name}: Sending response to {Message.From}");
            try
            {
                TelegramApi.SendMessage(Message.From, response);
            }
            catch (Exception e)
            {
                throw new Exception($"{GetType().Name}: An error occurred while sending response to {Message.From}", e);
            }

            Status = true;
        }
Exemplo n.º 49
0
        public static List <Inbox_DTO> DownLoad(string mail, string passward)
        {
            DAL.User user = new DAL.User();
            user = db.Users.Where(u => u.mail == mail).FirstOrDefault();
            using (var client = new ImapClient())
            {
                List <Inbox_DTO> mailMessages = new List <Inbox_DTO>();
                client.Connect("imap.gmail.com", 993, true);
                client.AuthenticationMechanisms.Remove("XOAUTH2");
                client.Authenticate(mail, passward);
                client.Inbox.Open(FolderAccess.ReadWrite);
                var uids     = client.Inbox.Search(SearchQuery.HasGMailLabel("unread"));
                var messages = client.Inbox.Fetch(uids, MessageSummaryItems.BodyStructure | MessageSummaryItems.UniqueId | MessageSummaryItems.Full);
                foreach (var messag in messages)
                {
                    int count   = 1;
                    var message = client.Inbox.GetMessage(messag.UniqueId);
                    //מעונין באנשי קשר מועדפים
                    if (user.preference == 1)
                    {
                        if (user.Contacts.First(i => i.mailContact == message.From.ToString()) == null)
                        {
                            continue;
                        }
                    }
                    else
                    {
                        //מעונין באנשי קשר דחויים
                        if (user.preference == 2)
                        {
                            if (user.Contacts.First(i => i.mailContact == message.From.ToString()) != null)
                            {
                                continue;
                            }
                        }
                    }

                    Inbox_DTO current_mail = new Inbox_DTO();
                    current_mail.Id      = (int)messag.UniqueId.Id;
                    current_mail.From    = message.From.ToString();
                    current_mail.To      = message.To.ToString();
                    current_mail.Subject = message.Subject.ToString();
                    current_mail.Body    = message.Body.ToString();
                    var text = message.TextBody;
                    if (user.attachment)
                    {
                        foreach (var attachment in messag.Attachments)
                        {
                            var mime     = (MimePart)client.Inbox.GetBodyPart(messag.UniqueId, attachment);
                            var fileName = mime.FileName;
                            if (string.IsNullOrEmpty(fileName))
                            {
                                fileName = string.Format("unnamed-{0}", count++);
                            }
                            current_mail.Attachment.Add(fileName);
                            using (var stream = File.Create(fileName))
                                mime.Content.DecodeTo(stream);
                        }
                    }
                    //לסמן מייל כנקרא
                    client.Inbox.AddFlags(uids, MessageFlags.Seen, true);
                    mailMessages.Add(current_mail);
                }
                client.Disconnect(true);
                return(mailMessages);
            }
        }