Exemple #1
0
 public async Task<bool> EditAspNetUser(AspNetUser aspNetUser, string newPassword)
 {
     db.Entry(aspNetUser).State = EntityState.Modified;
     db.Entry(aspNetUser).Property(prop => prop.CreateDate).IsModified = false;
     db.Entry(aspNetUser).Property(prop => prop.UpdateDate).IsModified = false;
     db.Entry(aspNetUser).Property(prop => prop.PasswordHash).IsModified = false;
     db.Entry(aspNetUser).Property(prop => prop.SecurityStamp).IsModified = false;
     aspNetUser.Id = aspNetUser.Id.Trim();
     aspNetUser.Email = aspNetUser.Email.Trim();
     aspNetUser.PhoneNumber = aspNetUser.PhoneNumber == null ? aspNetUser.PhoneNumber : aspNetUser.PhoneNumber.Trim();
     aspNetUser.UserName = aspNetUser.UserName.Trim();
     if (newPassword != null)
     {
         Microsoft.AspNet.Identity.PasswordHasher hash = new Microsoft.AspNet.Identity.PasswordHasher();
         aspNetUser.PasswordHash = hash.HashPassword(newPassword);
     }
     try
     {
         await db.SaveChangesAsync();
         return true;
     }
     catch (Exception ex)
     {
         string errorStr = ex.Message;
         return false;
     }
 }
        private static void GetUpdatedPersonFromVm(PersonDetailsVm model, AspNetUser user)
        {
            var person = user.UserPerson;

            SetUserProperties(model, user);
            SetPersonProperties(model, person);
        }
        private void CreateNewPersonFromVm(PersonDetailsVm model, AspNetUser user)
        {
            var person = _personRepository.NewObject();

            SetUserProperties(model, user);
            SetPersonProperties(model, person);

            user.UserPerson = person;
        }
Exemple #4
0
        protected void btnSendCode_Click(object sender, EventArgs e)
        {
            // declare variables
            string userId = txtInfo.Text;

            lblErrors.Text = "";

            // determine whether they entered a phone # or email address
            if (Regex.IsMatch(userId, @"^\d{10}$"))
            {
                // set bool isPhone to true
                isPhone = true;

                // check if a user exists with the entered phone number
                AspNetUser u = db.AspNetUsers.Where(p => p.PhoneNumber == userId)
                               .SingleOrDefault();

                if (u != null)
                {
                    if (u.PhoneNumberConfirmed == false)
                    {
                        lblErrors.Text = "You Have Entered the Correct Phone Number, but it hasn't been verified."
                                         + " Contact the Administrator to Reset your password.";
                    }
                    else
                    {
                        try
                        {
                            //declare variables
                            TwilioRestClient client =
                                new TwilioRestClient(ConfigurationManager.AppSettings["TwilioSID"],
                                                     ConfigurationManager.AppSettings["TwilioTOKEN"]);

                            string callerId = ConfigurationManager.AppSettings["TwilioID"];

                            // generate code
                            GenerateCode();

                            var result = client.SendMessage(callerId, userId, secCode);

                            if (result.RestException != null)
                            {
                                lblErrors.Text += result.RestException.Message;
                                LogFile.WriteToFile("AccountRecovery.aspx.cs", "btnSendCode_Click", result.RestException.Message, "Error when sending sms message", "HPSErrorLog.txt");
                            }
                        }
                        catch (NullReferenceException ex)
                        {
                            LogFile.WriteToFile("AccountRecovery.aspx.cs", "btnSendCode_Click", ex, "Sometimes throws a null reference exception", "HPSErrorLog.txt");
                        }

                        ScriptManager.RegisterStartupScript(this,
                                                            GetType(),
                                                            "slideDiv",
                                                            "$('#recPass').animate({"
                                                            + "left: '250px',"
                                                            + "opacity: '0',"
                                                            + "width: '384px'"
                                                            + "}, 300, function() {"
                                                            + "$(this).hide();"
                                                            + "$('#recCode').fadeIn(300);"
                                                            + "});"
                                                            , true);

                        lblSuccess.Text = "Your security code has been sent to your phone."
                                          + "<br/>It could take up to 5 minutes to receive.";
                    }
                }
                else
                {
                    lblErrors.Text += "Either you have not added a phone number to your account or you have entered it wrong."
                                      + " Try again and if the problem persists contact the administrator.";
                }
            }
            else // email
            {
                // isPhone bool is false by default

                // search database for a user with the entered email
                AspNetUser user = db.AspNetUsers.Where(m => m.Email == userId)
                                  .SingleOrDefault();

                if (user != null && user.EmailConfirmed)
                {
                    // Generate recovery code;
                    GenerateCode();

                    // Build mail message and Smtp Client
                    using (MailMessage mm =
                               new MailMessage(ConfigurationManager.AppSettings["Email"], userId))
                    {
                        mm.Subject    = "Password Recovery";
                        mm.Body       = "Here is your security code: " + secCode;
                        mm.IsBodyHtml = false;
                        SmtpClient smtp = new SmtpClient();
                        smtp.Host      = "smtp-mail.outlook.com";
                        smtp.EnableSsl = true;

                        NetworkCredential NetworkCred =
                            new NetworkCredential(ConfigurationManager.AppSettings["Email"],
                                                  ConfigurationManager.AppSettings["Password"]);

                        smtp.UseDefaultCredentials = true;
                        smtp.Credentials           = NetworkCred;
                        smtp.Port = 587;

                        try
                        {
                            // try sending email
                            smtp.Send(mm);

                            ScriptManager.RegisterStartupScript(this,
                                                                GetType(),
                                                                "slideDiv",
                                                                "$('#recPass').animate({"
                                                                + "left: '250px',"
                                                                + "opacity: '0',"
                                                                + "width: '384px'"
                                                                + "}, 300, function() {"
                                                                + "$(this).hide();"
                                                                + "$('#recCode').fadeIn(300);"
                                                                + "});"
                                                                , true);

                            lblErrors.Text  = "";
                            lblSuccess.Text = "Your security code has been sent to your email address."
                                              + "<br/>If you don't see the email, check your junk folder."
                                              + "<br/>It could take up to 5 minutes to receive.";
                        }
                        catch (SmtpException se)
                        {
                            lblErrors.Text += "Email failed to send try again. You may have reached your daily limit. "
                                              + "If the problem persists contact your administrator.";

                            LogFile.WriteToFile("AccountRecovery.aspx.cs", "btnSendCode_Click", se, "smtp exception when sending email", "HPSErrorLog.txt");
                        }
                        catch (Exception ex)
                        {
                            lblErrors.Text += " An error occured try again. If the problem persists contact your administrator.<br>";
                            LogFile.WriteToFile("AccountRecovery.aspx.cs", "btnSendCode_Click", ex, "Error trying to build and send email", "HPSErrorLog.txt");
                        }
                    }
                }
                else if (user.EmailConfirmed != true)
                {
                    lblSuccess.Text = "";
                    lblErrors.Text += "The email address you entered is associated with an HPS account"
                                      + " but it has not been Verified. "
                                      + "Please contact the administrator to Reset your Password.";
                }
                else // Invalid email address
                {
                    lblSuccess.Text = "";
                    lblErrors.Text += "The email address you entered is not associated with any of the HPS accounts."
                                      + " Please check that you have entered your email address properly, if you have done so already"
                                      + " contact the administrator.";
                }
            }
        }
Exemple #5
0
 public ActionResult Book(int RoomID, DateTime Date, TimeSpan Start, TimeSpan End)
 {
     try
     {
         Room room = db.Rooms.Find(RoomID);
         if (room == null)
         {
             throw new Exception("Not found.");
         }
         string role = Helpers.User.GetUserRoleId(User.Identity.Name);
         if (room.RoomRoles.Where(rr => rr.AspNetRoleID == role).Count() <= 0)
         {
             throw new Exception("Not available for the current user type.");
         }
         AspNetUser user = Helpers.User.GetUser(User.Identity.Name);
         if (!User.IsInRole("Administrator"))
         {
             if (room.BuildingID != user.BuildingID)
             {
                 throw new Exception("This room is in a different building than yours.");
             }
         }
         DateTime start = new DateTime(Date.Year, Date.Month, Date.Day, Start.Hours, Start.Minutes, Start.Seconds);
         DateTime end   = new DateTime(Date.Year, Date.Month, Date.Day, End.Hours, End.Minutes, End.Seconds);
         if (Start > End)
         {
             throw new Exception("The start time is after the end time!");
         }
         if (start < DateTime.Now)
         {
             throw new Exception("The start time is before the current time!");
         }
         if (Start == End)
         {
             throw new Exception("The start time is equal to the end time!");
         }
         if (room.Bookings.Where(b => b.EndDate >= start && b.StartDate <= end).Count() > 0)
         {
             throw new Exception("Room is not available for the selected period of time.");
         }
         if (room.Building.OpenHour != null)
         {
             if (room.Building.OpenHour > Start)
             {
                 throw new Exception("The building opens after the selected start time.");
             }
         }
         if (room.Building.CloseHour != null)
         {
             if (room.Building.CloseHour < End)
             {
                 throw new Exception("The building closes after the selected start time.");
             }
         }
         if (room.MaximumBookingHours < End - Start)
         {
             throw new Exception("The room accepts only bookings that are quicker than " + room.MaximumBookingHours + " hours.");
         }
         string bookref = "";
         Random r       = new Random();
         bookref = room.Building.BuildingCode + r.Next(10000, 99999).ToString() + room.Floor + Date.DayOfWeek.ToString().Substring(0, 1) + room.RoomCode;
         Booking booking = new Booking()
         {
             RoomID           = room.RoomID,
             BookingReference = bookref,
             AspNetUserID     = user.Id,
             CreatedDate      = DateTime.Now,
             StartDate        = start,
             EndDate          = end,
             BookingStatusID  = room.DefaultBookingStatusID
         };
         db.Bookings.Add(booking);
         db.SaveChanges();
         Helpers.BookingChanges.HandleChange(booking.BookingID, user.Id, "Created booking. Room: " + booking.Room.RoomCode + "; Start date: " + start.ToString() + "; End date: " + end.ToString() + "; Status: " + booking.BookingStatusID);
         return(RedirectToAction("Index", "Bookings"));
     }
     catch (Exception ex)
     {
         ViewBag.Log = LogHandler.Helpers.LogHandler.HandleLog(LogHandler.Helpers.LogType.Warning, "Rooms/BookPOST", ex.Message, (ex.InnerException != null ? ex.InnerException.Message : ""), Request.Params);
         return(View("Error"));
     }
 }
 public void UpdateUser(AspNetUser user)
 {
     new SecurityBusinessManager().UpdateUser(new AspNetUser[] { user });
 }
 public void AddUser(AspNetUser user)
 {
     new SecurityBusinessManager().AddUser(new AspNetUser[] { user });
 }
Exemple #8
0
        /// <summary>
        /// Function will send email.
        /// </summary>
        /// <param name="senderEmail">sender email</param>
        /// <param name="senderPassword">sender password</param>
        /// <param name="receiver">receiver as LMS.Models.Employee Type is required</param>
        /// <param name="MessageType">"LeaveRequest" or "LeaveResponse"</param>
        /// <returns>return type is void</returns>
        /// <remarks>Text put here will not display in a Visual Studio summary box.
        /// It is meant to add in further detail for anyone who might read this
        /// code in the future </remarks>
        public static void SendEmailUsingLeavON(Leave leave1, string LeavON_Email, string LeavON_Password, AspNetUser sender, AspNetUser receiver, String MessageType)
        {
            MailMessage mail = new MailMessage();

            SmtpClient smtpServer = new SmtpClient("mail.smtp2go.com");

            // SmtpClient smtpServer = new SmtpClient("smtp.gmail.com");
            // SmtpClient smtpServer = new SmtpClient("smtp.gmail.com");
            // mail.smtp2go.com
            smtpServer.UseDefaultCredentials = false;

            smtpServer.Credentials = new System.Net.NetworkCredential(LeavON_Email, LeavON_Password);
            //smtpServer.Host = "smtp.gmail.com"; not neccesry now. as mention above
            smtpServer.Port      = 587; //465;//587; // Gmail works on this port
            smtpServer.EnableSsl = true;


            try
            {
                mail.From = new MailAddress(LeavON_Email);
                //mail.From = new MailAddress(sender.Email);
                mail.To.Add(new MailAddress(receiver.Email));
                mail.CC.Add(new MailAddress("*****@*****.**"));

                //KeyValuePair<string,string> keyValuePair = new KeyValuePair<string, string>();
                List <string> phoneList = System.IO.File.ReadAllLines(Path.Combine(HttpContext.Current.Server.MapPath("~/App_Data/Uploads"), FileName)).ToList <string>();

                //string path = HttpContext.Current.Server.MapPath("~/files/sample.html");
                //string content = System.IO.File.ReadAllText(path);

                switch (MessageType)
                {
                case "LeaveRequest":
                    mail.Subject = sender.UserName + " posted a Leave request";
                    mail.Body    = "Dear , " + receiver.UserName +
                                   Environment.NewLine + "I have sent you a leave request. kindly follow the link " +
                                   "https://lms.intechww.com:1001/?ReturnUrl=https://lms.intechww.com:1002/LeavesResponse/Edit/" + leave1.Id + " for detail." +
                                   Environment.NewLine + leave1.LeaveType.Name +
                                   Environment.NewLine + leave1.Reason +
                                   Environment.NewLine + leave1.StartDate +
                                   Environment.NewLine + leave1.EndDate +
                                   Environment.NewLine + "Best Regards " +
                                   Environment.NewLine +
                                   sender.UserName + //string.Format(body, model.FromName, model.FromEmail, model.Message);
                                   Environment.NewLine + "This is system generated email, don't reply it";

                    break;

                case "LeaveResponse":

                    mail.Subject = sender.UserName + " posted a Leave response";
                    mail.Body    = "Dear " + receiver.UserName + "," +
                                   Environment.NewLine + "I have just sent you feed back regarding your leave request. kindly follow the link " +
                                   //"http://lms.intechww.com:1002/LeavesRequest/Index" + " for detail." +
                                   //https://localhost:44339/?ReturnUrl=https://localhost:44380/LeavesResponse/Edit/60
                                   "https://lms.intechww.com:1001/?ReturnUrl=https://lms.intechww.com:1002/LeavesRequest/Edit/" + leave1.Id + " for detail." +
                                   Environment.NewLine + leave1.LeaveType.Name +

                                   Environment.NewLine + leave1.Reason +
                                   Environment.NewLine + leave1.StartDate +
                                   Environment.NewLine + leave1.EndDate +
                                   Environment.NewLine + "Best Regards " +
                                   Environment.NewLine +
                                   sender.UserName + //string.Format(body, model.FromName, model.FromEmail, model.Message);
                                   Environment.NewLine + "This is system generated email, don't reply it";



                    break;

                default:
                    //return quitely
                    break;
                }



                smtpServer.Send(mail);
            }
            catch (Exception ex)
            {
                switch (ex.HResult)
                {
                case -2146233088:    //sender email is wrong
                    //return quitely
                    break;

                default:
                    //return quitely
                    break;
                }
            }
        }
Exemple #9
0
        public async Task <IActionResult> SaveSong([FromBody] string songname)
        {
            try
            {
                AspNetUser user        = null;
                string     accessToken = await HttpContext.GetTokenAsync("access_token");

                HttpClient client = new HttpClient();
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

                // Récurération des données et convertion des données dans le bon type
                string content = await client.GetStringAsync(Configuration["URLAPI"] + "api/Account/getUserInfo");

                user = JsonConvert.DeserializeObject <AspNetUser>(content);

                string[] song  = songname.Split('-');
                Music    music = new Music();
                music.MusicName  = song[0];
                music.ArtistName = song[1];

                Music search = _context.Musics.Where(x => x.MusicName.Equals(music.MusicName)).SingleOrDefault();

                if (search == null)
                {
                    _context.Musics.Add(music);
                    _context.SaveChanges();
                }
                else
                {
                    music = search;
                }

                Preference p = _context.Preferences
                               .Include(p => p.PreferenceMusics)
                               .Include(p => p.PreferenceHairSizes)
                               .Include(p => p.PreferenceHairColors)
                               .Include(p => p.PreferenceCorpulences)
                               .Include(p => p.PreferenceReligions)
                               .Include(p => p.PreferenceStyles)
                               .Where(x => x.Id == user.Id)
                               .SingleOrDefault();

                if (p != null)
                {
                    PreferenceMusic pM = new PreferenceMusic();
                    pM.MusicId      = music.MusicId;
                    pM.PreferenceId = p.PreferenceId;
                    p.PreferenceMusics.Add(pM);

                    UserMusic userMusic = new UserMusic();
                    userMusic.Id      = user.Id;
                    userMusic.MusicId = music.MusicId;
                    _context.UserMusics.Add(userMusic);

                    _context.SaveChanges();
                    return(NoContent());
                }
                else
                {
                    return(NotFound());
                }
            }
            catch (Exception)
            {
                return(BadRequest());
            }
        }
Exemple #10
0
 public void Update(AspNetUser aspNetUser)
 {
     _adminRepository.Update(aspNetUser);
 }
        public override GNContact PopulateSelectLists(GNContact entity)
        {
            string[] selectedRoles = null;
            if (entity != null)
            {
                if (entity.GNContactRoles != null)
                {
                    selectedRoles = entity.GNContactRoles.Select(r => r.AspNetRoleId).ToArray();
                }
            }

            IQueryable <AspNetRole> aspNetRoles = null;

            int UserMinHierarchyOrder = UserContact.GetUserMinHierarchyOrder();

            if (UserContact.IsInRole("GN_ADMIN") || UserContact.IsInRole("ORG_MANAGER"))
            {
                aspNetRoles = this.identityDB.AspNetRoles.Where(r => r.Name != "GN_ADMIN" && !r.Name.Contains("GN_"));
            }
            else if (UserContact.IsInRole("TEAM_MANAGER"))
            {
                aspNetRoles = this.identityDB.AspNetRoles.Where(r => (!r.Name.Contains("GN_") && r.Name != "ORG_MANAGER") && r.HierarchyOrder > UserMinHierarchyOrder);
            }
            else
            {
                aspNetRoles = this.identityDB.AspNetRoles.Where(r => r.Name == "TEAM_MEMBER" && r.HierarchyOrder > UserMinHierarchyOrder);
            }

            ViewBag.AspNetRoleList = new MultiSelectList(aspNetRoles, "Id", "Name", selectedRoles);

            if (!string.IsNullOrEmpty(Request["organizationId"]) && entity != null)
            {
                entity.GNOrganization   = db.GNOrganizations.Find(Guid.Parse(Request["organizationId"]));
                entity.GNOrganizationId = entity.GNOrganization.Id;
            }
            else if (!string.IsNullOrEmpty(Request["teamId"]) && entity != null)
            {
                entity.GNOrganization   = db.GNTeams.Find(Guid.Parse(Request["teamId"])).Organization;
                entity.GNOrganizationId = entity.GNOrganization.Id;
            }
            else if (entity != null && entity.GNOrganizationId != Guid.Empty)
            {
                entity.GNOrganization = db.GNOrganizations.Find(entity.GNOrganizationId);
            }

            if (!string.IsNullOrEmpty(Request["aspNetUserId"]) && Guid.Parse(Request["aspNetUserId"]) != Guid.Empty)
            {
                if (entity == null)
                {
                    entity = new GNContact();
                }

                AspNetUser aspNetUser = identityDB.AspNetUsers.Find(Request["aspNetUserId"]);
                if (aspNetUser != null)
                {
                    entity.User         = aspNetUser;
                    entity.AspNetUserId = aspNetUser.Id;
                    entity.Email        = aspNetUser.Email;
                }
            }

            return(base.PopulateSelectLists(entity));
        }
        public Task <JsonResponse> EditProfile(EditProfile EditProfile)
        {
            return(Task.Run(() =>
            {
                using (MIUEntities db = new MIUEntities())
                {
                    try
                    {
                        User user = db.Users.Where(x => x.ID == EditProfile.ID).SingleOrDefault();
                        List <User> userList = db.Users.Where(x => x.IsDelete != true && x.EmailAccount == EditProfile.EmailAccount).ToList();

                        var list = userList.ToList();

                        var emailExists = userList.Where(x => x.ID != EditProfile.ID).ToList();

                        if (user == null)
                        {
                            return new JsonResponse()
                            {
                                Flag = true, Message = "User is not found"
                            };
                        }
                        else if (user != null && emailExists.Count() > 0)
                        {
                            return new JsonResponse()
                            {
                                Flag = true, Message = "Email already exists"
                            };
                        }
                        else
                        {
                            string ImageName = "";

                            if (!String.IsNullOrEmpty(EditProfile.FileName) && EditProfile.FileName != "\"\"" && EditProfile.FileName != "")
                            {
                                Guid guid = Guid.NewGuid();
                                ImageName = guid.ToString() + "_" + Path.GetFileName(EditProfile.FileName);
                                user.ProfilePicture = ImageName;

                                if (!string.IsNullOrEmpty(EditProfile.Base64Image) && EditProfile.Base64Image != "\"\"" && EditProfile.Base64Image != "")
                                {
                                    byte[] Base64Image = Convert.FromBase64String(EditProfile.Base64Image);
                                    MIUFileServer.SaveToFileServer("ProfileImages", ImageName, Base64Image);
                                }
                            }
                            //user.ID = EditProfile.ID;
                            //user.FullName = EditProfile.FullName;
                            //user.Address = EditProfile.Address;
                            //user.DOB = EditProfile.DOB.Date;
                            user.EmailAccount = EditProfile.EmailAccount;
                            user.ContactNumber = EditProfile.ContactNumber;
                            user.MobilePhoneNumber = EditProfile.ContactNumber;
                            user.ModifiedBy = EditProfile.ModifiedBy;
                            user.ModifiedDate = EditProfile.ModifiedDate;
                            user.OrderDatetime = DateTime.Now;

                            AspNetUser aspNetUser = db.AspNetUsers.Where(x => x.UserName == user.LoginName).SingleOrDefault();
                            aspNetUser.Email = EditProfile.EmailAccount;

                            db.SaveChanges();
                            return new JsonResponse()
                            {
                                Flag = true, Message = "Successfully Updated"
                            };
                        }
                    }
                    catch (Exception ex)
                    {
                        return new JsonResponse()
                        {
                            Flag = false, Message = ex.Message
                        };
                    }
                }
            }));
        }
        //gets game information
        public async Task <IHttpActionResult> GetGame(Guid id)
        {
            using (var context = new gamebase1Entities())
            {
                var identity = User.Identity as ClaimsIdentity;
                var claims   = from c in identity.Claims //extracting the username in var identity
                               select new
                {
                    subject = c.Subject.Name,
                    type    = c.Type,
                    value   = c.Value
                };
                double ratingAvg = (from r in context.Reviews
                                    where r.GameID == id
                                    select r.StarRating).DefaultIfEmpty(0).Average();
                ratingAvg = Math.Round(ratingAvg, 2);
                try
                {
                    var        userName = claims.ToList()[0].value.ToString(); //converting to string
                    AspNetUser user     = context.AspNetUsers.Where(u => u.UserName == userName).Single();

                    if (identity.IsAuthenticated)
                    {
                        Game     game     = context.Games.Where(p => p.GameID == id).Single();
                        Favorite favorite = context.Favorites.Where(u => u.GameID == game.GameID && u.UserID == user.Id).SingleOrDefault();


                        GameModel g = new GameModel
                        {
                            GameID       = game.GameID,
                            GameTitle    = game.GameTitle,
                            GameImageURL = game.GameImageURL,
                            GameReleased = game.GameReleased,
                            Developer    = game.Developer,
                            MatureRating = game.MatureRating,
                            Synopsis     = game.Synopsis,
                            isFavorite   = favorite != null ? true : false,
                            StarRating   = ratingAvg
                        };
                        if (g == null)
                        {
                            return(NotFound());
                        }
                        return(Ok(g));
                    }
                    else
                    {
                        IQueryable <Game> game = context.Games.Where(p => p.GameID == id);

                        Game      z = game.ToList()[0];
                        GameModel g = new GameModel
                        {
                            GameID       = z.GameID,
                            GameTitle    = z.GameTitle,
                            GameImageURL = z.GameImageURL,
                            GameReleased = z.GameReleased,
                            Developer    = z.Developer,
                            MatureRating = z.MatureRating,
                            Synopsis     = z.Synopsis,

                            StarRating = ratingAvg
                        };
                        if (g == null)
                        {
                            return(NotFound());
                        }
                        return(Ok(g));
                    }
                }
                catch (Exception err)
                {
                    IQueryable <Game> game = context.Games.Where(p => p.GameID == id);
                    Game      z            = game.ToList()[0];
                    GameModel g            = new GameModel
                    {
                        GameID       = z.GameID,
                        GameTitle    = z.GameTitle,
                        GameImageURL = z.GameImageURL,
                        GameReleased = z.GameReleased,
                        Developer    = z.Developer,
                        MatureRating = z.MatureRating,
                        Synopsis     = z.Synopsis,
                        StarRating   = ratingAvg
                    };
                    if (g == null)
                    {
                        return(NotFound());
                    }
                    return(Ok(g));
                }
                //if not authorized use this return
            }
        }
        private string CalculateDistance(GeoCoordinate userLocation, AspNetUser aspNetUser)
        {
            if (aspNetUser.Longitude.HasValue && aspNetUser.Latitude.HasValue)
            {
                var pairedLocation = new GeoCoordinate(aspNetUser.Latitude.Value, aspNetUser.Longitude.Value);
                var distance = userLocation.GetDistanceTo(pairedLocation) * 0.0016; // metres
                return string.Format("{0} miles from you", distance.ToString("N0"));
            }

            return string.Empty;
        }
Exemple #15
0
        public bool SaveUser(UserModel user, long tuserId, string phoneNumber, bool mobileConfirmed)
        {
            using (var dataModel = new Mibarim_plusEntities())
            {
                var au = dataModel.AspNetUsers.FirstOrDefault(x => x.UserName == phoneNumber);
                if (au != null)
                {
                    var tu = dataModel.TelegramUsers.FirstOrDefault(x => x.TuserId == user.TuserId);
                    tu.UserId         = au.Id;
                    tu.TelegramUserId = tuserId;
                    dataModel.SaveChanges();

                    var invo = dataModel.Invites.FirstOrDefault(x => x.UserId == au.Id);
                    if (invo != null)
                    {
                        return(true);
                    }
                    else
                    {
                        var inv = new Invite();
                        inv.UserId     = au.Id;
                        inv.CreateTime = DateTime.Now;
                        inv.InviteType = 3;
                        inv.InviteCode = InviteCodeGenerator();
                        dataModel.Invites.Add(inv);
                        dataModel.SaveChanges();
                    }
                }
                else
                {
                    var aspnetuser = new AspNetUser();
                    aspnetuser.Family         = user.Family;
                    aspnetuser.Gender         = 0;
                    aspnetuser.EmailConfirmed = false;
                    string salt;
                    var    pass = HashPassword("mibarimpass", out salt);
                    aspnetuser.PasswordHash    = pass;
                    aspnetuser.SecurityStamp   = salt;
                    aspnetuser.UserName        = phoneNumber;
                    aspnetuser.MobileConfirmed = mobileConfirmed;
                    dataModel.AspNetUsers.Add(aspnetuser);
                    dataModel.SaveChanges();
                    var ui = new UserInfo();
                    ui.UserId             = aspnetuser.Id;
                    ui.UserInfoCreateTime = DateTime.Now;
                    ui.UserInfoIsDeleted  = false;
                    dataModel.UserInfoes.Add(ui);
                    dataModel.SaveChanges();
                    var invi = new Invite();
                    invi.UserId     = aspnetuser.Id;
                    invi.CreateTime = DateTime.Now;
                    invi.InviteType = 3;
                    invi.InviteCode = InviteCodeGenerator();
                    dataModel.Invites.Add(invi);
                    dataModel.SaveChanges();
                    var tu = dataModel.TelegramUsers.FirstOrDefault(x => x.TuserId == user.TuserId);
                    tu.UserId         = aspnetuser.Id;
                    tu.TelegramUserId = tuserId;
                    dataModel.SaveChanges();
                    return(true);
                }
            }
            return(false);
        }
 public static AspNetUser CreateAspNetUser(global::System.Guid applicationId, global::System.Guid userId, string userName, string loweredUserName, bool isAnonymous, global::System.DateTime lastActivityDate)
 {
     AspNetUser aspNetUser = new AspNetUser();
     aspNetUser.ApplicationId = applicationId;
     aspNetUser.UserId = userId;
     aspNetUser.UserName = userName;
     aspNetUser.LoweredUserName = loweredUserName;
     aspNetUser.IsAnonymous = isAnonymous;
     aspNetUser.LastActivityDate = lastActivityDate;
     return aspNetUser;
 }
Exemple #17
0
        public JsonResult ProfileCompletionPercent(string userId)
        {
            AspNetUser User = db.AspNetUsers.Find(userId);
            int        count = 0, total = 9;
            bool       mandatoryFieldMissing = false;

            if (User.BloodGroup != null)
            {
                count++;
            }
            if (User.FullName != null)
            {
                count++;
            }
            if (User.Gender != null)
            {
                count++;
            }
            if (User.NId != null)
            {
                count++;
            }
            if (User.Profession != null)
            {
                count++;
            }

            if (User.ProfilePicUrl != null)
            {
                count++;
            }
            else
            {
                mandatoryFieldMissing = true;
            }
            if (User.PhoneNumber != null)
            {
                count++;
            }
            else
            {
                mandatoryFieldMissing = true;
            }
            if (User.PermanentAddress != null)
            {
                count++;
            }
            else
            {
                mandatoryFieldMissing = true;
            }
            if (User.PresentAddress != null)
            {
                count++;
            }
            else
            {
                mandatoryFieldMissing = true;
            }

            var  percent = (int)(count / (float)total * 100);
            bool valid   = percent > 60 && !mandatoryFieldMissing;
            var  result  = new
            {
                Valid   = valid,
                Percent = percent,
                MandatoryFieldMissing = mandatoryFieldMissing
            };

            return(Json(result, JsonRequestBehavior.AllowGet));
        }
Exemple #18
0
        public JsonResult GetAccessZones(AspNetUser user)
        {
            var accessZones = user.EmployeeAccessZoneMaps;

            return(Json(""));
        }
Exemple #19
0
 public SessionUser(AspNetUser user, List <LocationView> locations, ProfileImageView profileImage)
 {
     Details      = user;
     Locations    = locations;
     ProfileImage = profileImage;
 }
Exemple #20
0
        public static void SendLeaveRequestEmail(string senderEmail, string senderPassword, AspNetUser receiver)
        {
            MailMessage mail = new MailMessage();

            SmtpClient smtpServer = new SmtpClient("mail.smtp2go.com");

            //smtpServer.UseDefaultCredentials = false;
            smtpServer.Credentials = new System.Net.NetworkCredential(senderEmail, senderPassword);
            //smtpServer.Host = "smtp.gmail.com"; not neccesry now. as mention above
            smtpServer.Port      = 587; // Gmail works on this port
            smtpServer.EnableSsl = true;

            try
            {
                mail.From = new MailAddress(senderEmail);
                mail.To.Add(new MailAddress(receiver.Email));
                mail.Subject = "Email for Leave approval";
                mail.Body    = "Dear Sir, " + receiver.UserName + Environment.NewLine + "I have sent you a leave request. kindly login to LeaveON account " + "http://localhost:44380/LeavesResponse/Index" + " for detial." + Environment.NewLine + "best regards " + Environment.NewLine + senderEmail; //string.Format(body, model.FromName, model.FromEmail, model.Message);


                smtpServer.Send(mail);
            }
            catch (Exception ex)
            {
                switch (ex.HResult)
                {
                case -2146233088:    //sender email is wrong
                    //return quitely
                    break;

                default:
                    //return quitely
                    break;
                }
            }
        }//SendLeaveRequestEmail
Exemple #21
0
        public string Purchase(FormCollection form)
        {
            int        GameID = Convert.ToInt32((form["GameID"]));
            AspNetUser user   = db.AspNetUsers.Where(x => x.UserName == User.Identity.Name).First();
            Member     member = db.Members.Where(m => m.ASPUserId == user.Id).First();


            MemberInGame mib = db.MemberInGames.Where(c => c.MemberID == member.MemberID && c.GameID == GameID).First();

            trackingTransactionManager.PausePaymentTrackingTransaction(GameID, member.MemberID);

            //Address billingAddress = db.Addresses.Where(a => a.MemberID == member.MemberID && a.AddressType.ToLower() == "billing").First();
            pig = mib.Game.ProductInGames.FirstOrDefault();



            /* Setcom Purchase */
            SetcomPaymentTransactionManager PayMan = new SetcomPaymentTransactionManager();
            PurchaseTransactionRequest      purchaseTransactionRequest = new PurchaseTransactionRequest();

            purchaseTransactionRequest.CCNumber            = form["PaymentsModel.CardNumber"]; //"4444444444444444";
            purchaseTransactionRequest.CCCVV               = form["PaymentsModel.CVCNumber"];
            purchaseTransactionRequest.ExYear              = (form["PaymentsModel.ExpiryDateY"].ToString().Trim().Length > 2) ? form["PaymentsModel.ExpiryDateY"] : "20" + form["PaymentsModel.ExpiryDateY"];
            purchaseTransactionRequest.ExMonth             = form["PaymentsModel.ExpiryDateM"];
            purchaseTransactionRequest.CCName              = form["PaymentsModel.NameOnCard"];
            purchaseTransactionRequest.MemberInGameID      = mib.MemberInGameID;
            purchaseTransactionRequest.EmailAddress        = mib.Member.EmailAddress;
            purchaseTransactionRequest.CC_Amount           = pig.PriceInGame.ToString();
            purchaseTransactionRequest.ip_address          = Request.ServerVariables["REMOTE_ADDR"];
            purchaseTransactionRequest.transactionDateTime = DateTime.Now;

            /* Additional Non-mandatory fields */
            purchaseTransactionRequest.bill_first_name = mib.Member.FirstName;
            purchaseTransactionRequest.bill_last_name  = mib.Member.LastName;

            purchaseTransactionRequest.bill_street1 = "";
            purchaseTransactionRequest.bill_street2 = "";
            purchaseTransactionRequest.bill_city    = "";
            purchaseTransactionRequest.bill_state   = "";
            purchaseTransactionRequest.bill_country = mib.Member.Country.CountryName;;
            purchaseTransactionRequest.bill_zip     = "";
            purchaseTransactionRequest.bill_phone   = "";
            purchaseTransactionRequest.bill_title   = "";



            PurchaseTransactionResponse ptRes = PayMan.PerformPaymentTransaction(purchaseTransactionRequest);

            ptRes.outcome = ptRes.outcome.ToUpper();
            if (ptRes.outcome.ToUpper() != "APPROVED")
            // Setcom change ends here
            {
                trackingTransactionManager.ResumePaymentTrackingTransaction(GameID, member.MemberID);
                ptRes.timeRemaining = trackingTransactionManager.GetTimeRemaining(GameID, member.MemberID).ToString();
            }
            else
            {
                trackingTransactionManager.CompletePaymentTrackingTransaction(GameID, member.MemberID);
                //Update paymentIndicator
                mib.PaymentIndicator = true;
                try
                {
                    db.SaveChanges();
                }
                catch (System.Data.Entity.Validation.DbEntityValidationException e)
                {
                    foreach (var eve in e.EntityValidationErrors)
                    {
                        Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                                          eve.Entry.Entity.GetType().Name, eve.Entry.State);
                        foreach (var ve in eve.ValidationErrors)
                        {
                            System.Diagnostics.Debug.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                                                               ve.PropertyName, ve.ErrorMessage);
                        }
                    }
                }


                // get winner address
                Address deliveryAddress = db.Addresses.FirstOrDefault(x => x.MemberID == member.MemberID && x.AddressType.ToLower() == "postal");

                // get quantity won - divide quantity from pig by number of winners ??? really??? ok then.....
                Game qtyGame = db.Games.Find(GameID);

                int winQuantity = 1; //pig.Quantity / qtyGame.NumberOfWinners;
                // send winner email
                this.sendWinnermail(member.FirstName + ' ' + member.LastName, member.EmailAddress, deliveryAddress, winQuantity);
            }

            JsonResult json = new JsonResult
            {
                Data = ptRes
            };

            string son = new JavaScriptSerializer().Serialize(json.Data);

            return(son);
        }
Exemple #22
0
        /// <summary>
        /// Validate function for all ContactService commands
        /// </summary>
        /// <param name="validationContext">System.ComponentModel.DataAnnotations.ValidationContext (Describes the context in which a validation check is performed.)</param>
        /// <param name="actionDBType">[ActionDBTypeEnum] (CSSPEnums.ActionDBTypeEnum.html) action type to validate</param>
        /// <param name="addContactType">[AddContactTypeEnum] (CSSPEnums.AddContactTypeEnum.html) use when adding a new contact</param>
        /// <returns>IEnumerable of ValidationResult (Where ValidationResult is a container for the results of a validation request.)</returns>
        private IEnumerable <ValidationResult> Validate(ValidationContext validationContext, ActionDBTypeEnum actionDBType, AddContactTypeEnum addContactType)
        {
            string  retStr  = "";
            Enums   enums   = new Enums(LanguageRequest);
            Contact contact = validationContext.ObjectInstance as Contact;

            contact.HasErrors = false;

            if (actionDBType == ActionDBTypeEnum.Update || actionDBType == ActionDBTypeEnum.Delete)
            {
                if (contact.ContactID == 0)
                {
                    contact.HasErrors = true;
                    yield return(new ValidationResult(string.Format(CSSPServicesRes._IsRequired, "ContactID"), new[] { "ContactID" }));
                }

                if (!(from c in db.Contacts select c).Where(c => c.ContactID == contact.ContactID).Any())
                {
                    contact.HasErrors = true;
                    yield return(new ValidationResult(string.Format(CSSPServicesRes.CouldNotFind_With_Equal_, "Contact", "ContactID", contact.ContactID.ToString()), new[] { "ContactID" }));
                }
            }

            if (string.IsNullOrWhiteSpace(contact.Id))
            {
                contact.HasErrors = true;
                yield return(new ValidationResult(string.Format(CSSPServicesRes._IsRequired, "Id"), new[] { "Id" }));
            }

            if (!string.IsNullOrWhiteSpace(contact.Id) && contact.Id.Length > 128)
            {
                contact.HasErrors = true;
                yield return(new ValidationResult(string.Format(CSSPServicesRes._MaxLengthIs_, "Id", "128"), new[] { "Id" }));
            }

            AspNetUser AspNetUserId = (from c in db.AspNetUsers where c.Id == contact.Id select c).FirstOrDefault();

            if (AspNetUserId == null)
            {
                contact.HasErrors = true;
                yield return(new ValidationResult(string.Format(CSSPServicesRes.CouldNotFind_With_Equal_, "AspNetUser", "Id", (contact.Id == null ? "" : contact.Id.ToString())), new[] { "Id" }));
            }

            TVItem TVItemContactTVItemID = (from c in db.TVItems where c.TVItemID == contact.ContactTVItemID select c).FirstOrDefault();

            if (TVItemContactTVItemID == null)
            {
                contact.HasErrors = true;
                yield return(new ValidationResult(string.Format(CSSPServicesRes.CouldNotFind_With_Equal_, "TVItem", "ContactTVItemID", contact.ContactTVItemID.ToString()), new[] { "ContactTVItemID" }));
            }
            else
            {
                List <TVTypeEnum> AllowableTVTypes = new List <TVTypeEnum>()
                {
                    TVTypeEnum.Contact,
                };
                if (!AllowableTVTypes.Contains(TVItemContactTVItemID.TVType))
                {
                    contact.HasErrors = true;
                    yield return(new ValidationResult(string.Format(CSSPServicesRes._IsNotOfType_, "ContactTVItemID", "Contact"), new[] { "ContactTVItemID" }));
                }
            }

            if (string.IsNullOrWhiteSpace(contact.LoginEmail))
            {
                contact.HasErrors = true;
                yield return(new ValidationResult(string.Format(CSSPServicesRes._IsRequired, "LoginEmail"), new[] { "LoginEmail" }));
            }

            if (!string.IsNullOrWhiteSpace(contact.LoginEmail) && (contact.LoginEmail.Length < 6 || contact.LoginEmail.Length > 255))
            {
                contact.HasErrors = true;
                yield return(new ValidationResult(string.Format(CSSPServicesRes._LengthShouldBeBetween_And_, "LoginEmail", "6", "255"), new[] { "LoginEmail" }));
            }

            if (!string.IsNullOrWhiteSpace(contact.LoginEmail))
            {
                Regex regex = new Regex(@"^([\w\!\#$\%\&\'*\+\-\/\=\?\^`{\|\}\~]+\.)*[\w\!\#$\%\&\'‌​*\+\-\/\=\?\^`{\|\}\~]+@((((([a-zA-Z0-9]{1}[a-zA-Z0-9\-]{0,62}[a-zA-Z0-9]{1})|[‌​a-zA-Z])\.)+[a-zA-Z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$");
                if (!regex.IsMatch(contact.LoginEmail))
                {
                    contact.HasErrors = true;
                    yield return(new ValidationResult(string.Format(CSSPServicesRes._IsNotAValidEmail, "LoginEmail"), new[] { "LoginEmail" }));
                }
            }

            if (string.IsNullOrWhiteSpace(contact.FirstName))
            {
                contact.HasErrors = true;
                yield return(new ValidationResult(string.Format(CSSPServicesRes._IsRequired, "FirstName"), new[] { "FirstName" }));
            }

            if (!string.IsNullOrWhiteSpace(contact.FirstName) && contact.FirstName.Length > 100)
            {
                contact.HasErrors = true;
                yield return(new ValidationResult(string.Format(CSSPServicesRes._MaxLengthIs_, "FirstName", "100"), new[] { "FirstName" }));
            }

            if (string.IsNullOrWhiteSpace(contact.LastName))
            {
                contact.HasErrors = true;
                yield return(new ValidationResult(string.Format(CSSPServicesRes._IsRequired, "LastName"), new[] { "LastName" }));
            }

            if (!string.IsNullOrWhiteSpace(contact.LastName) && contact.LastName.Length > 100)
            {
                contact.HasErrors = true;
                yield return(new ValidationResult(string.Format(CSSPServicesRes._MaxLengthIs_, "LastName", "100"), new[] { "LastName" }));
            }

            if (!string.IsNullOrWhiteSpace(contact.Initial) && contact.Initial.Length > 50)
            {
                contact.HasErrors = true;
                yield return(new ValidationResult(string.Format(CSSPServicesRes._MaxLengthIs_, "Initial", "50"), new[] { "Initial" }));
            }

            if (string.IsNullOrWhiteSpace(contact.WebName))
            {
                contact.HasErrors = true;
                yield return(new ValidationResult(string.Format(CSSPServicesRes._IsRequired, "WebName"), new[] { "WebName" }));
            }

            if (!string.IsNullOrWhiteSpace(contact.WebName) && contact.WebName.Length > 100)
            {
                contact.HasErrors = true;
                yield return(new ValidationResult(string.Format(CSSPServicesRes._MaxLengthIs_, "WebName", "100"), new[] { "WebName" }));
            }

            if (contact.ContactTitle != null)
            {
                retStr = enums.EnumTypeOK(typeof(ContactTitleEnum), (int?)contact.ContactTitle);
                if (contact.ContactTitle == null || !string.IsNullOrWhiteSpace(retStr))
                {
                    contact.HasErrors = true;
                    yield return(new ValidationResult(string.Format(CSSPServicesRes._IsRequired, "ContactTitle"), new[] { "ContactTitle" }));
                }
            }

            if (!string.IsNullOrWhiteSpace(contact.SamplingPlanner_ProvincesTVItemID) && contact.SamplingPlanner_ProvincesTVItemID.Length > 200)
            {
                contact.HasErrors = true;
                yield return(new ValidationResult(string.Format(CSSPServicesRes._MaxLengthIs_, "SamplingPlanner_ProvincesTVItemID", "200"), new[] { "SamplingPlanner_ProvincesTVItemID" }));
            }

            if (contact.LastUpdateDate_UTC.Year == 1)
            {
                contact.HasErrors = true;
                yield return(new ValidationResult(string.Format(CSSPServicesRes._IsRequired, "LastUpdateDate_UTC"), new[] { "LastUpdateDate_UTC" }));
            }
            else
            {
                if (contact.LastUpdateDate_UTC.Year < 1980)
                {
                    contact.HasErrors = true;
                    yield return(new ValidationResult(string.Format(CSSPServicesRes._YearShouldBeBiggerThan_, "LastUpdateDate_UTC", "1980"), new[] { "LastUpdateDate_UTC" }));
                }
            }

            TVItem TVItemLastUpdateContactTVItemID = (from c in db.TVItems where c.TVItemID == contact.LastUpdateContactTVItemID select c).FirstOrDefault();

            if (TVItemLastUpdateContactTVItemID == null)
            {
                contact.HasErrors = true;
                yield return(new ValidationResult(string.Format(CSSPServicesRes.CouldNotFind_With_Equal_, "TVItem", "LastUpdateContactTVItemID", contact.LastUpdateContactTVItemID.ToString()), new[] { "LastUpdateContactTVItemID" }));
            }
            else
            {
                List <TVTypeEnum> AllowableTVTypes = new List <TVTypeEnum>()
                {
                    TVTypeEnum.Contact,
                };
                if (!AllowableTVTypes.Contains(TVItemLastUpdateContactTVItemID.TVType))
                {
                    contact.HasErrors = true;
                    yield return(new ValidationResult(string.Format(CSSPServicesRes._IsNotOfType_, "LastUpdateContactTVItemID", "Contact"), new[] { "LastUpdateContactTVItemID" }));
                }
            }

            retStr = "";      // added to stop compiling CSSPError
            if (retStr != "") // will never be true
            {
                contact.HasErrors = true;
                yield return(new ValidationResult("AAA", new[] { "AAA" }));
            }
        }
Exemple #23
0
        public ActionResult Update(String id)
        {
            AspNetUser user = db.AspNetUsers.Find(id);

            return(View(user));
        }
 public void RemoveUser(AspNetUser user)
 {
     new SecurityBusinessManager().RemoveUser(new AspNetUser[] { user });
 }
Exemple #25
0
        public async Task <ActionResult> Edit([Bind(Include = "Id,UserId,LeaveTypeId,Reason,StartDate,EndDate,TotalDays,EmergencyContact,ResponseDate1,ResponseDate2,IsAccepted1,IsAccepted2,LineManager1Id,LineManager2Id,Remarks1,Remarks2,DateCreated,DateModified,UserLeavePolicyId")] Leave leave, string IsLineManager1)
        {
            //assign values to variable as we will reassing these values to the object
            leave.IsQuotaRequest = false;
            Nullable <int> IsAccepted1 = null;
            Nullable <int> IsAccepted2 = null;
            string         Remarks1    = string.Empty;
            string         Remarks2    = string.Empty;

            if (IsLineManager1 == "True")
            {
                IsAccepted1 = leave.IsAccepted1;
                Remarks1    = leave.Remarks1;
            }
            else
            {
                IsAccepted2 = leave.IsAccepted2;
                Remarks2    = leave.Remarks2;
            }
            //--------------------------------------------------
            Leave leaveOld = db.Leaves.FirstOrDefault(x => x.Id == leave.Id);

            leave = leaveOld;

            if (IsLineManager1 == "True")
            {
                leave.IsAccepted1   = IsAccepted1;
                leave.Remarks1      = Remarks1;
                leave.ResponseDate1 = DateTime.Now;

                if (IsAccepted1 == 2)
                {
                    leave.Remarks1  = string.Empty;
                    leave.TotalDays = decimal.Parse(Remarks1);
                }

                if (leave.LineManager1Id == leave.LineManager2Id)
                {
                    leave.IsAccepted2   = IsAccepted1;
                    leave.Remarks2      = leave.Remarks1;
                    leave.ResponseDate2 = DateTime.Now;
                    if (leave.IsAccepted2 > 0)
                    {
                        CalculateAndChangeLeaveBalance(ref leave);
                    }
                }
            }
            else
            {
                leave.IsAccepted2   = IsAccepted2;
                leave.Remarks2      = Remarks2;
                leave.ResponseDate2 = DateTime.Now;
                if (IsAccepted2 == 2)
                {
                    leave.Remarks2  = string.Empty;
                    leave.TotalDays = decimal.Parse(Remarks2);
                }
                if (leave.IsAccepted2 > 0)
                {
                    CalculateAndChangeLeaveBalance(ref leave);
                }
            }

            if (ModelState.IsValid)
            {
                db.Entry(leave).State = EntityState.Modified;

                await db.SaveChangesAsync();

                if (IsLineManager1 == "True")
                {
                    AspNetUser admin = db.AspNetUsers.FirstOrDefault(x => x.Id == leave.LineManager1Id);
                    SendEmail.SendEmailUsingLeavON(SendEmail.LeavON_Email, SendEmail.LeavON_Password, admin, leave.AspNetUser, "LeaveResponse");

                    if (leave.LineManager1Id == leave.LineManager2Id)
                    {
                        admin = db.AspNetUsers.FirstOrDefault(x => x.Id == leave.LineManager2Id);
                        SendEmail.SendEmailUsingLeavON(SendEmail.LeavON_Email, SendEmail.LeavON_Password, admin, leave.AspNetUser, "LeaveResponse");
                    }
                }
                else
                {
                    AspNetUser admin = db.AspNetUsers.FirstOrDefault(x => x.Id == leave.LineManager2Id);
                    SendEmail.SendEmailUsingLeavON(SendEmail.LeavON_Email, SendEmail.LeavON_Password, admin, leave.AspNetUser, "LeaveResponse");
                }

                //AspNetUser admin2 = db.AspNetUsers.FirstOrDefault(x => x.Id == leave.LineManager2Id);
                //SendEmail.SendEmailUsingLeavON(SendEmail.LeavON_Email, SendEmail.LeavON_Password, leave.AspNetUser, admin2, "LeaveRequest");

                return(RedirectToAction("Index"));
            }
            ViewBag.LeaveTypeId = new SelectList(db.LeaveTypes, "Id", "Name", leave.LeaveTypeId);
            //ViewBag.UserLeavePolicyId = new SelectList(db.UserLeavePolicies, "Id", "UserId", leave.UserLeavePolicyId);
            return(View(leave));
        }
Exemple #26
0
        public ActionResult SearchPartial(string Country, int?BuildingID, string Floor, int?Capacity, DateTime?Date, TimeSpan?Start, TimeSpan?End, string Assets)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    string role   = Helpers.User.GetUserRoleId(User.Identity.Name);
                    var    result = db.Rooms.Where(r => r.RoomRoles.Where(rr => rr.AspNetRoleID == role).Count() > 0).ToList();
                    if (!User.IsInRole("Administrator"))
                    {
                        AspNetUser user = Helpers.User.GetUser(User.Identity.Name);
                        result = result.Where(r => r.BuildingID == user.BuildingID).ToList();
                    }
                    if (Country != null)
                    {
                        result = result.Where(r => r.Building.Country == Server.UrlDecode(Country)).ToList();
                    }
                    if (BuildingID.HasValue)
                    {
                        result = result.Where(r => r.BuildingID == BuildingID.Value).ToList();
                    }
                    if (Floor != null)
                    {
                        result = result.Where(r => r.Floor == Server.UrlDecode(Floor)).ToList();
                    }
                    if (Capacity.HasValue)
                    {
                        result = result.Where(r => r.Capacity >= Capacity.Value).ToList();
                    }
                    if (Assets != null)
                    {
                        var assets = System.Web.Helpers.Json.Decode <List <int> >(Assets);
                        foreach (int asset in assets)
                        {
                            result = result.Where(r => r.RoomAssets.Where(ra => ra.AssetID == asset).Count() > 0).ToList();
                        }
                    }
                    if (Date != null && Start != null && End != null)
                    {
                        if (Start > End)
                        {
                            return(Content("<center>The start time is after the end time!</center>"));
                        }
                        if (Start == End)
                        {
                            return(Content("<center>The start time is equal to the end time!</center>"));
                        }
                        DateTime start = new DateTime(Date.Value.Year, Date.Value.Month, Date.Value.Day, Start.Value.Hours, Start.Value.Minutes, Start.Value.Seconds);
                        DateTime end   = new DateTime(Date.Value.Year, Date.Value.Month, Date.Value.Day, End.Value.Hours, End.Value.Minutes, End.Value.Seconds);
                        if (start < DateTime.Now)
                        {
                            return(Content("<center>The start time is before the current time!</center>"));
                        }
                        result = result.Where(r => r.Bookings.Where(b => b.EndDate >= start && b.StartDate <= end).Count() == 0).ToList();
                        result = result.Where(r => r.Building.OpenHour == null || (r.Building.OpenHour != null && r.Building.OpenHour <= Start.Value)).Where(r => r.Building.CloseHour == null || (r.Building.CloseHour != null && r.Building.CloseHour >= End.Value)).ToList();
                        result = result.Where(r => r.MaximumBookingHours == null || (r.MaximumBookingHours != null && r.MaximumBookingHours >= End.Value - Start.Value)).ToList();
                    }

                    return(PartialView("PartialResults", result));
                }
                else
                {
                    return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
                }
            }
            catch (Exception ex)
            {
                ViewBag.Log = LogHandler.Helpers.LogHandler.HandleLog(LogHandler.Helpers.LogType.Warning, "Rooms/SearchPartial", ex.Message, (ex.InnerException != null ? ex.InnerException.Message : ""), Request.Params);
                return(View("Error"));
            }
        }
Exemple #27
0
        public async Task <ActionResult> EditCompensatoryQuotaResponse([Bind(Include = "Id,UserId,LeaveTypeId,Reason,StartDate,EndDate,TotalDays,EmergencyContact,ResponseDate1,ResponseDate2,IsAccepted1,IsAccepted2,LineManager1Id,LineManager2Id,Remarks1,Remarks2,DateCreated,DateModified,UserLeavePolicyId")] Leave leave, string IsLineManager1)
        {
            //----------------------------get new value----------------------------------------------
            //assign values to variable as we will reassing these values to the object
            //leave.IsQuotaRequest = true; no need to assing ture. when we get old leave few line ahead there is ture in IsQotaRequest
            Nullable <int> IsAccepted1 = null;
            Nullable <int> IsAccepted2 = null;
            string         Remarks1    = string.Empty;
            string         Remarks2    = string.Empty;
            DateTime       startDate   = leave.StartDate;
            DateTime       endDate     = leave.EndDate;
            decimal        totalDays;

            if (leave.TotalDays == null)
            {
                totalDays = (decimal)(endDate - startDate).TotalDays;
            }
            else
            {
                totalDays = leave.TotalDays.Value;
            }

            if (IsLineManager1 == "True")
            {
                IsAccepted1 = leave.IsAccepted1;
                if (IsAccepted1 == 2)
                {
                    Remarks1 = (leave.Remarks1 == null) ? string.Empty : leave.Remarks1.Trim();
                }
            }
            else
            {
                IsAccepted2 = leave.IsAccepted2;
                if (IsAccepted2 == 2)
                {
                    Remarks2 = (leave.Remarks2 == null) ? string.Empty : leave.Remarks2.Trim();
                }
            }
            //--------------------------get old leave and put new values to it------------------------
            Leave leaveOld = db.Leaves.FirstOrDefault(x => x.Id == leave.Id);

            leave = leaveOld;

            if (IsLineManager1 == "True")
            {
                leave.IsAccepted1 = IsAccepted1;
                leave.Remarks1    = Remarks1;
                //if (!(string.IsNullOrEmpty(Remarks1))) leave.TotalDays = decimal.Parse(Remarks1);
                leave.ResponseDate1 = DateTime.Now;
                if (IsAccepted1 == 2)
                {
                    //leave.Remarks1 = string.Empty;
                    //if (!(string.IsNullOrEmpty(Remarks1))) leave.TotalDays = decimal.Parse(Remarks1);
                    leave.StartDate = startDate;
                    leave.EndDate   = endDate;
                    leave.TotalDays = totalDays;
                }

                if (leave.LineManager1Id == leave.LineManager2Id)
                {
                    leave.IsAccepted2   = IsAccepted1;
                    leave.Remarks2      = leave.Remarks1;
                    leave.ResponseDate2 = DateTime.Now;
                    // calculatin will perform when linemanager 2 will aprove so it is in if condition
                    if (leave.IsAccepted2 > 0)
                    {
                        CalculateAndChangeLeaveBalanceQuota(ref leave);
                    }
                }
            }
            else
            {
                leave.IsAccepted2   = IsAccepted2;
                leave.Remarks2      = Remarks2;
                leave.ResponseDate2 = DateTime.Now;
                if (IsAccepted2 == 2)
                {
                    //leave.Remarks2 = string.Empty;
                    //if (!(string.IsNullOrEmpty(Remarks2))) leave.TotalDays = decimal.Parse(Remarks2);
                    leave.StartDate = startDate;
                    leave.EndDate   = endDate;
                    leave.TotalDays = totalDays;
                }
                if (leave.IsAccepted2 > 0)
                {
                    CalculateAndChangeLeaveBalanceQuota(ref leave);
                }
            }

            if (ModelState.IsValid)
            {
                db.Entry(leave).State = EntityState.Modified;

                await db.SaveChangesAsync();

                //------------------------------sending mail----------------------------------------------
                if (IsLineManager1 == "True")
                {
                    AspNetUser admin = db.AspNetUsers.FirstOrDefault(x => x.Id == leave.LineManager1Id);
                    SendEmail.SendEmailUsingLeavON(SendEmail.LeavON_Email, SendEmail.LeavON_Password, admin, leave.AspNetUser, "LeaveResponse");
                    if (leave.LineManager1Id == leave.LineManager2Id)
                    {
                        admin = db.AspNetUsers.FirstOrDefault(x => x.Id == leave.LineManager2Id);
                        SendEmail.SendEmailUsingLeavON(SendEmail.LeavON_Email, SendEmail.LeavON_Password, admin, leave.AspNetUser, "LeaveResponse");
                    }
                }
                else
                {
                    AspNetUser admin = db.AspNetUsers.FirstOrDefault(x => x.Id == leave.LineManager2Id);
                    SendEmail.SendEmailUsingLeavON(SendEmail.LeavON_Email, SendEmail.LeavON_Password, admin, leave.AspNetUser, "LeaveResponse");
                }

                //AspNetUser admin2 = db.AspNetUsers.FirstOrDefault(x => x.Id == leave.LineManager2Id);
                //SendEmail.SendEmailUsingLeavON(SendEmail.LeavON_Email, SendEmail.LeavON_Password, leave.AspNetUser, admin2, "LeaveRequest");

                return(RedirectToAction("QuotaResponseHistory"));
            }
            ViewBag.LeaveTypeId = new SelectList(db.LeaveTypes, "Id", "Name", leave.LeaveTypeId);
            //ViewBag.UserLeavePolicyId = new SelectList(db.UserLeavePolicies, "Id", "UserId", leave.UserLeavePolicyId);
            return(View(leave));
        }
Exemple #28
0
        protected void btnSavePass_Click(object sender, EventArgs e)
        {
            HelperMethods.ActivityTracker.Track("Saved a Password Reset", (int)UserActionEnum.Updated);
            try
            {
                if (isPhone)
                {
                    // Grab user with the phone entered
                    AspNetUser user = db.AspNetUsers.Where(u => u.PhoneNumber == txtInfo.Text).SingleOrDefault();

                    // no need to check if the user exists again

                    // Create UserManager
                    UserManager <IdentityUser> userManager =
                        new UserManager <IdentityUser>(new UserStore <IdentityUser>());

                    // Remove old pass and add new pass
                    userManager.RemovePassword(user.Id);
                    userManager.AddPassword(user.Id, txtPass.Text);

                    db.SaveChanges();

                    // Create a notification for the database
                    string[] role = { "Administrator" };
                    NotificationCreator.CreateNotification(role, "Password Reset:", user.UserName + " reset their password", DateTime.Now, "Info", null, null);

                    ScriptManager.RegisterStartupScript(this,
                                                        GetType(),
                                                        "slideDiv",
                                                        "$('#recReset').animate({"
                                                        + "left: '250px',"
                                                        + "opacity: '0',"
                                                        + "width: '384px'"
                                                        + "}, 300, function() {"
                                                        + "$(this).hide();"
                                                        + "$('#recComplete').fadeIn(300);"
                                                        + "});"
                                                        , true);
                }
                else // is Email
                {
                    // Grab user with the email entered
                    AspNetUser user = db.AspNetUsers.Where(u => u.Email == txtInfo.Text).SingleOrDefault();

                    // no need to check if the user exists again

                    // Create UserManager
                    UserManager <IdentityUser> userManager =
                        new UserManager <IdentityUser>(new UserStore <IdentityUser>());

                    // Remove old pass and add new pass
                    userManager.RemovePassword(user.Id);
                    userManager.AddPassword(user.Id, txtPass.Text);

                    db.SaveChanges();

                    // Create a notification for the database
                    string[] role = { "Administrator" };
                    NotificationCreator.CreateNotification(role, "Password Reset:", user.UserName + " reset their password", DateTime.Now, "Info", null, null);

                    ScriptManager.RegisterStartupScript(this,
                                                        GetType(),
                                                        "slideDiv",
                                                        "$('#recReset').animate({"
                                                        + "left: '250px',"
                                                        + "opacity: '0',"
                                                        + "width: '384px'"
                                                        + "}, 300, function() {"
                                                        + "$(this).hide();"
                                                        + "$('#recComplete').fadeIn(300);"
                                                        + "});"
                                                        , true);
                }
            }
            catch (DataException dx)
            {
                lblErrors.Text += "An error occured when saving the password. Contact your administrator.<br>";
                LogFile.WriteToFile("AccountRecovery.aspx.cs", "btnSavePass_Click", dx, "Data Error when updating password", "HPSErrorLog.txt");
            }
            catch (Exception ex)
            {
                lblErrors.Text += "An error occured when saving the password. Contact your administrator.<br>";
                LogFile.WriteToFile("AccountRecovery.aspx.cs", "btnSavePass_Click", ex, "Error when updating password.", "HPSErrorLog.txt");
            }
        }
        public IHttpActionResult PostAspNetUser(User user)
        {
            AspNetUser aspNetUser = new AspNetUser
            {
                FirstName    = user.FirstName,
                LastName     = user.LastName,
                Email        = user.Email,
                PasswordHash = user.Password,
                UserName     = user.Email,
                isAdmin      = user.IsAdmin,
                Departments  = new Collection <Department>(user.Permissions.Select(departmento => new Department
                {
                    DepartmentName = departmento.DepartmentName,
                    Computers      = new Collection <Computer>(departmento.Computers.Select(computadora => new Computer
                    {
                        ComputerName   = computadora.ComputerName,
                        DepartmentName = computadora.DepartmentName,
                        ComputerId     = computadora.ComputerId,
                        Credentials    = new Collection <Credential>(computadora.Credentials.Select(credencial => new Credential
                        {
                            UserName = credencial.UserName,
                            Password = credencial.Password,
                            Type     = credencial.Type
                        }).ToList())
                    }).ToList())
                }).ToList()),
                EmailConfirmed       = false,
                SecurityStamp        = Guid.NewGuid().ToString(),
                PhoneNumber          = null,
                PhoneNumberConfirmed = false,
                TwoFactorEnabled     = false,
                LockoutEndDateUtc    = null,
                LockoutEnabled       = false,
                AccessFailedCount    = 0
            };

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            db.AspNetUsers.Add(aspNetUser);

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateException)
            {
                if (AspNetUserExists(aspNetUser.Id))
                {
                    return(Conflict());
                }
                else
                {
                    throw;
                }
            }

            return(CreatedAtRoute("DefaultApi", new { id = aspNetUser.Id }, aspNetUser));
        }
        public ActionResult EditBO(UsersBoViewModel uBoViMo) // permet d'éditer les rôles
        {
            try
            {
                AspNetUser utilisateur             = repUser.TrouverChaine(uBoViMo.id);
                IEnumerable <AspNetRole> userRoles = utilisateur.AspNetRoles;
                string AdminRoleId       = repRole.Lister().Where(r => r.Name == "admin").First().Id;
                string AssistantRoleId   = repRole.Lister().Where(r => r.Name == "assistant").First().Id;
                string ResponsableRoleId = repRole.Lister().Where(r => r.Name == "responsable").First().Id;
                string ModerateurRoleId  = repRole.Lister().Where(r => r.Name == "moderateur").First().Id;

                if (uBoViMo.admin)
                {
                    if (userRoles.Where(r => r.Name == "admin").Count() == 0)
                    {
                        utilisateur.AspNetRoles.Add(repRole.TrouverChaine(AdminRoleId));
                    }
                }
                else
                {
                    if (userRoles.Where(r => r.Name == "admin").Count() != 0)
                    {
                        utilisateur.AspNetRoles.Remove(repRole.TrouverChaine(AdminRoleId));
                    }
                }

                if (uBoViMo.assistant)
                {
                    if (userRoles.Where(r => r.Name == "assistant").Count() == 0)
                    {
                        utilisateur.AspNetRoles.Add(repRole.TrouverChaine(AssistantRoleId));
                    }
                }
                else
                {
                    if (userRoles.Where(r => r.Name == "assistant").Count() != 0)
                    {
                        utilisateur.AspNetRoles.Remove(repRole.TrouverChaine(AssistantRoleId));
                    }
                }

                if (uBoViMo.responsable)
                {
                    if (userRoles.Where(r => r.Name == "responsable").Count() == 0)
                    {
                        utilisateur.AspNetRoles.Add(repRole.TrouverChaine(ResponsableRoleId));
                    }
                }
                else
                {
                    if (userRoles.Where(r => r.Name == "responsable").Count() != 0)
                    {
                        utilisateur.AspNetRoles.Remove(repRole.TrouverChaine(ResponsableRoleId));
                    }
                }

                if (uBoViMo.moderateur)
                {
                    if (userRoles.Where(r => r.Name == "moderateur").Count() == 0)
                    {
                        utilisateur.AspNetRoles.Add(repRole.TrouverChaine(ModerateurRoleId));
                    }
                }
                else
                {
                    if (userRoles.Where(r => r.Name == "moderateur").Count() != 0)
                    {
                        utilisateur.AspNetRoles.Remove(repRole.TrouverChaine(ModerateurRoleId));
                    }
                }

                return(RedirectToAction("IndexBO"));
            }
            catch
            {
                return(View());
            }
        }
Exemple #31
0
        public async Task <ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            // This doen't count login failures towards lockout only two factor authentication
            // To enable password failures to trigger lockout, change to shouldLockout: true

            AspNetUser user = await UserManager.FindByNameAsync(model.Email);

            if (user == null)
            {
                ModelState.AddModelError("", "Error! Invalid email.");
                return(View(model));
            }
            ClaimsIdentity identity = await user.GenerateUserIdentityAsync(UserManager, DefaultAuthenticationTypes.ApplicationCookie);

            AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
            if (user != null)
            {
                if (!await UserManager.IsEmailConfirmedAsync(user.Id))
                {
                    ModelState.AddModelError("", "Please confirm your email");
                    return(View());
                }
            }
            // This doen't count login failures towards lockout only two factor authentication
            // To enable password failures to trigger lockout, change to shouldLockout: true
            var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout : false);

            switch (result)
            {
            case SignInStatus.Success:
            {
                // Parse TimeZoneOffset.
                var timeZoneCookie      = Request.Cookies["_timeZoneOffset"];
                var timeZoneOffSetValue = TimeSpan.FromMinutes(0);
                if (timeZoneCookie != null)
                {
                    double offsetMinutes = 0;
                    if (double.TryParse(timeZoneCookie.Value, out offsetMinutes))
                    {
                        timeZoneOffSetValue = TimeSpan.FromMinutes(offsetMinutes);
                    }
                }
                claimsSecurityService.AddClaimsToIdentity(user.UserDomainKey, user.AspNetRoles.FirstOrDefault().Name, user.UserName, timeZoneOffSetValue,
                                                          identity);
                SetUserPermissions(user, identity);
                AuthenticationManager.SignIn(new AuthenticationProperties {
                        IsPersistent = true
                    }, identity);
                return(RedirectToLocal(returnUrl));
            }

            case SignInStatus.LockedOut:
            {
                return(View("Lockout"));
            }

            case SignInStatus.RequiresVerification:
            {
                return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl }));
            }

            case SignInStatus.Failure:

            default:
            {
                ModelState.AddModelError("", "Invalid login attempt.");
            }
                return(View(model));
            }
        }
        public ActionResult Index()
        {
            string                       UserID               = "";
            HomePageViewModel            vm                   = new HomePageViewModel();
            OnlinePermissionSlipEntities db                   = new OnlinePermissionSlipEntities();
            List <GuardianApproval>      guardianApprovals    = null;
            List <ClassRoom>             classRooms           = null;
            List <PermissionSlip>        ClassPermissionSlips = null;
            int ApprovedCount    = 0;
            int NotApprovedCount = 0;
            int NoApprovalCount  = 0;
            Dictionary <int, List <int> > PermissionSlipStudents = new Dictionary <int, List <int> >();
            AspNetUser guardian = null;

            if (User.Identity.IsAuthenticated)
            {
                UserID = User.Identity.GetUserId();
                if (User.IsInRole("Guardian"))
                {
                    guardian          = db.AspNetUsers.Where(u => u.Id == UserID).FirstOrDefault();
                    guardianApprovals = db.GuardianApprovals.Where(a => a.GuardianUserID == UserID).ToList();
                    foreach (GuardianApproval g in guardianApprovals)
                    {
                        vm.PermissionSlips.Add(new IndexPermissionSlip()
                        {
                            guardian         = g.AspNetUser,                     //Should guardian be shown if not the current user even though they are connected to the same student?
                            guardianApproval = g,
                            student          = g.Student,
                            permissionSlip   = g.PermissionSlip,
                            GuardianApproved = g.Approved
                        });

                        if (PermissionSlipStudents.ContainsKey(g.PermissionSlipID))
                        {
                            PermissionSlipStudents[g.PermissionSlipID].Add(g.Student.ID);
                        }
                        else
                        {
                            PermissionSlipStudents.Add(g.PermissionSlipID, new List <int>()
                            {
                                g.Student.ID
                            });
                        }
                    }

                    //Get Each Guardian's Student, Then ClassRoom, then permission Slip
                    foreach (Student s in db.Students.Where(s => s.Guardians.Any(g => g.Id == UserID)).ToList())
                    {
                        foreach (PermissionSlip p in s.ClassRoom.PermissionSlips)
                        {
                            if (!PermissionSlipStudents.ContainsKey(p.ID) || !PermissionSlipStudents[p.ID].Contains(s.ID))
                            {
                                vm.PermissionSlips.Add(new IndexPermissionSlip()
                                {
                                    guardian         = guardian,
                                    guardianApproval = null,
                                    student          = s,
                                    permissionSlip   = p,
                                    GuardianApproved = null
                                });

                                if (PermissionSlipStudents.ContainsKey(p.ID))
                                {
                                    PermissionSlipStudents[p.ID].Add(s.ID);
                                }
                                else
                                {
                                    PermissionSlipStudents.Add(p.ID, new List <int>()
                                    {
                                        s.ID
                                    });
                                }
                            }
                        }
                    }
                }
                else if (User.IsInRole("Teacher"))
                {
                    classRooms = db.ClassRooms.Where(c => c.TeacherUserID == UserID).ToList();
                    DateTime StartDate = DateTime.Now.Date;
                    DateTime EndDate   = DateTime.Now.Date;

                    if (DateTime.Now.Month >= 8)
                    {
                        StartDate = new DateTime(DateTime.Now.Year, 8, 1);
                        EndDate   = new DateTime(DateTime.Now.Year + 1, 6, 30);
                    }
                    else
                    {
                        StartDate = new DateTime(DateTime.Now.Year - 1, 8, 1);
                        EndDate   = new DateTime(DateTime.Now.Year, 6, 30);
                    }

                    foreach (ClassRoom c in classRooms)
                    {
                        ClassPermissionSlips = c.PermissionSlips.Where(p => (p.StartDateTime >= StartDate && p.StartDateTime <= EndDate) ||
                                                                       (p.EndDateTime >= EndDate && p.EndDateTime >= StartDate)
                                                                       ).ToList();

                        foreach (PermissionSlip p in ClassPermissionSlips)
                        {
                            ApprovedCount    = db.GuardianApprovals.Where(a => a.PermissionSlipID == p.ID && a.Approved == true).Count();
                            NotApprovedCount = db.GuardianApprovals.Where(a => a.PermissionSlipID == p.ID && a.Approved == false).Count();
                            NoApprovalCount  = p.ClassRoom.Students.Count - ApprovedCount - NotApprovedCount;

                            vm.PermissionSlips.Add(new IndexPermissionSlip()
                            {
                                permissionSlip   = p,
                                ApprovedCount    = ApprovedCount,
                                NotApprovedCount = NotApprovedCount,
                                NoApprovalCount  = NoApprovalCount
                            });
                        }
                    }
                }
                else if (User.IsInRole("School Admin"))
                {
                    classRooms = Common.GetClassRooms(db, User);
                    DateTime StartDate = DateTime.Now.Date;
                    DateTime EndDate   = DateTime.Now.Date;

                    if (DateTime.Now.Month >= 8)
                    {
                        StartDate = new DateTime(DateTime.Now.Year, 8, 1);
                        EndDate   = new DateTime(DateTime.Now.Year + 1, 6, 30);
                    }
                    else
                    {
                        StartDate = new DateTime(DateTime.Now.Year - 1, 8, 1);
                        EndDate   = new DateTime(DateTime.Now.Year, 6, 30);
                    }

                    foreach (ClassRoom c in classRooms)
                    {
                        ClassPermissionSlips = c.PermissionSlips.Where(p => (p.StartDateTime >= StartDate && p.StartDateTime <= EndDate) ||
                                                                       (p.EndDateTime >= EndDate && p.EndDateTime >= StartDate)
                                                                       ).ToList();

                        foreach (PermissionSlip p in ClassPermissionSlips)
                        {
                            ApprovedCount    = db.GuardianApprovals.Where(a => a.PermissionSlipID == p.ID && a.Approved == true).Count();
                            NotApprovedCount = db.GuardianApprovals.Where(a => a.PermissionSlipID == p.ID && a.Approved == false).Count();
                            NoApprovalCount  = p.ClassRoom.Students.Count - ApprovedCount - NotApprovedCount;

                            vm.PermissionSlips.Add(new IndexPermissionSlip()
                            {
                                permissionSlip   = p,
                                ApprovedCount    = ApprovedCount,
                                NotApprovedCount = NotApprovedCount,
                                NoApprovalCount  = NoApprovalCount
                            });
                        }
                    }
                }
            }

            vm.PermissionSlips = vm.PermissionSlips.OrderByDescending(p => p.permissionSlip.StartDateTime.Date).ThenBy(p => p.GuardianApproved).ToList();
            return(View(vm));
        }
        [OpenApiIgnore]//Not applicable for broker api, hence hiding it from swagger
        public async Task <IActionResult> ApproveAnswer([FromBody] ApproveAnswerModel model)
        {
            var method = $"{nameof(OrderController)}.{nameof(ApproveAnswer)}";

            _logger.LogDebug($"{method} was called");
            if (model == null)
            {
                return(ReturnError(ErrorCodes.IncomingPayloadIsMissing, method));
            }
            if (!_tolkBaseOptions.EnableCustomerApi)
            {
                _logger.LogWarning($"{model.CallingUser} called {method}, but CustomerApi is not enabled!");
                return(BadRequest(new ValidationProblemDetails {
                    Title = "CustomerApi is not enabled!"
                }));
            }
            if (string.IsNullOrEmpty(model.CallingUser))
            {
                return(ReturnError(ErrorCodes.CallingUserMissing, method));
            }
            _logger.LogInformation($"{model.CallingUser} is approving request answer on {model.OrderNumber} from {model.BrokerIdentifier} ");
            if (ModelState.IsValid)
            {
                try
                {
                    AspNetUser apiUser = await _dbContext.Users.GetUserWithCustomerOrganisationById(User.UserId());

                    var request = await _apiOrderService.GetRequestFromOrderAndBrokerIdentifier(model.OrderNumber, model.BrokerIdentifier);

                    if (request == null || request.Order.CustomerOrganisationId != apiUser.CustomerOrganisationId)
                    {
                        return(ReturnError(ErrorCodes.OrderNotFound, method));
                    }
                    if (!request.CanApprove)
                    {
                        return(ReturnError(ErrorCodes.OrderNotInCorrectState, method));
                    }
                    var user = await _apiUserService.GetCustomerUser(model.CallingUser, apiUser.CustomerOrganisationId);

                    if (user == null)
                    {
                        return(ReturnError(ErrorCodes.CallingUserMissing, method));
                    }

                    _orderService.ApproveRequestAnswer(request, user.Id, apiUser.Id);
                    await _dbContext.SaveChangesAsync();

                    _logger.LogInformation($"{request.RequestId} was approved");
                    return(Ok(new ResponseBase()));
                }
                catch (InvalidOperationException ex)
                {
                    return(ReturnError(ErrorCodes.OrderNotValid, method, ex.Message));
                }
                catch (ArgumentNullException ex)
                {
                    return(ReturnError(ErrorCodes.OrderNotValid, method, ex.Message));
                }
            }
            return(ReturnError(ErrorCodes.OrderNotValid, method));
        }
 public void AddToAspNetUsers(AspNetUser aspNetUser)
 {
     base.AddObject("AspNetUsers", aspNetUser);
 }
        public async Task <ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            rshar102DataBaseEntities db = new rshar102DataBaseEntities();
            var user = await UserManager.FindAsync(model.Email, model.Password);

            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, change to shouldLockout: true
            var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout : false);

            switch (result)
            {
            case SignInStatus.Success:
                AspNetUser logged = db.AspNetUsers.SingleOrDefault(u => u.UserName == model.Email);
                if (logged.Status == null)
                {
                    logged.Status = 1;
                }
                else if (logged.Status == 0)
                {
                    AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
                    Session.Clear();
                    Session.Abandon();
                    Session.RemoveAll();
                    FormsAuthentication.SignOut();
                    this.Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
                    this.Response.Cache.SetCacheability(HttpCacheability.NoCache);
                    this.Response.Cache.SetNoStore();
                    return(View("Lockout"));
                }
                Session["LastLogin"]   = logged.LastLogin;
                Session["UserId"]      = logged.Id;
                logged.LastLogin       = DateTime.Now;
                db.Entry(logged).State = EntityState.Modified;
                db.SaveChanges();
                if (UserManager.IsInRole(user.Id, "Admin"))
                {
                    Session["UserRole"] = "Admin";
                    return(RedirectToAction("ShowUsers", "Home"));
                }
                else
                {
                    Session["UserRole"] = "User";
                    return(RedirectToAction("ShowApps", "Home"));
                }

            case SignInStatus.LockedOut:
                return(View("Lockout"));

            case SignInStatus.RequiresVerification:
                return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }));

            case SignInStatus.Failure:
            default:
                ModelState.AddModelError("", "Invalid login attempt.");
                return(View(model));
            }
        }
 private static void SetUserProperties(PersonDetailsVm model, AspNetUser user)
 {
     user.FirstName = model.FirstName;
     user.LastName = model.LastName;
     user.PhoneNumber = model.Phone;
 }
Exemple #37
0
        public ActionResult Register(RegisteredUserVM newUser)
        {
            var userStore = new UserStore <IdentityUser>();
            UserManager <IdentityUser> manager = new UserManager <IdentityUser>(userStore)
            {
                UserLockoutEnabledByDefault          = true,
                DefaultAccountLockoutTimeSpan        = new TimeSpan(0, 10, 0),
                MaxFailedAccessAttemptsBeforeLockout = 5
            };
            var identityUser = new IdentityUser()
            {
                UserName = newUser.UserName,
                Email    = newUser.Email
            };

            if (ModelState.IsValid)
            {
                CaptchaHelper     captchaHelper   = new CaptchaHelper();
                OneListCAEntities context         = new OneListCAEntities();
                string            captchaResponse = captchaHelper.CheckRecaptcha();
                if (captchaResponse == "Valid")
                {
                    if (manager.FindByEmail(newUser.Email) == null)
                    {
                        ViewBag.CaptchaResponse = captchaResponse;
                        IdentityResult result = manager.Create(identityUser, newUser.Password);
                        if (result.Succeeded)
                        {
                            AspNetUser user = context.AspNetUsers
                                              .Where(u => u.UserName == newUser.UserName).FirstOrDefault();
                            AspNetRole role = new AspNetRole();
                            role.Id   = "User";
                            role.Name = "User";

                            user.AspNetRoles.Add(context.AspNetRoles.Find(role.Id));
                            context.SaveChanges();
                            //add information of user and password to table users in core
                            CreateTokenProvider(manager, EMAIL_CONFIRMATION);

                            var code        = manager.GenerateEmailConfirmationToken(identityUser.Id);
                            var callbackUrl = Url.Action("ConfirmEmail", "Home",
                                                         new { userId = identityUser.Id, code = code },
                                                         protocol: Request.Url.Scheme);

                            //string email = "Please confirm your account by clicking this link: <a href=\""
                            //                + callbackUrl + "\">Confirm Registration</a>";
                            SendGrid.sendEmail(newUser, callbackUrl);
                            ViewBag.Result = "Please check your email to activate your account!";
                        }
                        else
                        {
                            ViewBag.Result = "User already exist!";
                        }
                    }
                    else
                    {
                        ViewBag.Result = "User already exist!";
                    }
                }
                else
                {
                    ViewBag.Result = "Registration failed!";
                }
            }

            return(View());
        }
        public static void Seed(MedSimDbContext context)
        {
#if !DEBUG
            throw new NotImplementedException("this should not be being used in a production environment - security changes required");
            
#endif
            try
            {
                if (!context.Roles.Any())
                {
                    //not in production
                    //context.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction,
                    //    "alter database [" + context.Database.Connection.Database + "] set single_user with rollback immediate");
                    //
                    var roleStore = new RoleStore<AspNetRole, Guid, AspNetUserRole>(context);
                    var roleManager = new RoleManager<AspNetRole, Guid>(roleStore);
                    var role = new AspNetRole
                    {
                        Id = Guid.NewGuid(),
                        Name = RoleConstants.Admin
                    };
                    roleManager.Create(role);
                }

                if (!context.Users.Any())
                {
                    var userStore = new CustomUserStore(context);
                    var userManager = new ApplicationUserManager(userStore);

                    var user = new AspNetUser
                    {
                        Email = "*****@*****.**",
                        UserName = "******"
                    };
                    var result = userManager.Create(user, password: "******");
                    if (result.Succeeded)
                    {
                        userManager.AddToRole(user.Id, RoleConstants.Admin);
                    }
                    else
                    {
                        throw new DbSeedException(result.Errors);
                    }
                }
            }
            catch (DbEntityValidationException ex)
            {
                // Retrieve the error messages as a list of strings.
                var errorMessages = ex.EntityValidationErrors
                        .SelectMany(x => x.ValidationErrors)
                        .Select(x => x.ErrorMessage);

                // Join the list to a single string.
                var fullErrorMessage = string.Join("; ", errorMessages);

                // Combine the original exception message with the new one.
                var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);

                // Throw a new DbEntityValidationException with the improved exception message.
                throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);
            }
        }
Exemple #39
0
 public async Task<bool> CreateAspNetUser(AspNetUser aspNetUser)
 {
     aspNetUser.CreateDate = DateTime.UtcNow;
     aspNetUser.UpdateDate = DateTime.UtcNow;
     aspNetUser.Id = Guid.NewGuid().ToString();
     Microsoft.AspNet.Identity.PasswordHasher hash = new Microsoft.AspNet.Identity.PasswordHasher();
     aspNetUser.PasswordHash = hash.HashPassword(aspNetUser.PasswordHash.Trim());
     aspNetUser.SecurityStamp = Guid.NewGuid().ToString();
     db.AspNetUsers.Add(aspNetUser);
     try
     {
         await db.SaveChangesAsync();
         return true;
     }
     catch (Exception ex)
     {
         return false;
     }
 }