public ActionResult FileUpload(HttpPostedFileBase file)
        {
            if (file != null)
            {
                using (var dbContext = new YATContext())
                {
                    var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
                    var currentUser = manager.FindById(User.Identity.GetUserId());
                    var YATUser = dbContext.User.Where(p => p.Id.Equals(currentUser.Id)).FirstOrDefault();

                    string picName = System.IO.Path.GetFileName(file.FileName);
                    String photo = YATUser.Id + Path.GetExtension(picName);
                    file.SaveAs(Server.MapPath("~/Pics/" + photo));

                    YATUser.Photo = photo;
                    dbContext.SaveChanges();
                }

                using (MemoryStream ms = new MemoryStream())
                {
                    file.InputStream.CopyTo(ms);
                    byte[] array = ms.GetBuffer();
                }

            }
            return RedirectToAction("UserSettings", "UserProfile");
        }
 public ActionResult Read(int? id)
 {
     if (id == null)
     {
         return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
     }
     var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
     var currentUser = manager.FindById(User.Identity.GetUserId());
     User user;
     using (var dbContext = new YATContext())
     {
         user = dbContext.User.Where(p => p.Id.Contains(currentUser.Id)).FirstOrDefault();
     }
     string userid = user.Id;
     Message message = db.Messages.Find(id);
     Messaging msging = new Messaging();
     var messages = msging.getConversation(message.To.Id, message.From.Id).ToList();
     foreach (Message mess in messages)
     {
         if (mess.ToId.Equals(userid)) 
         { 
             msging.read(mess.To.Id, mess.Id);
         }
     }
     if (message == null)
     {
         return HttpNotFound();
     }
     return View(messages);
 }
        public ActionResult UserProfile(string userID = "")
        {
            var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
           
            string getID = userID == "" ? User.Identity.GetUserId() : userID;
            string currentUser = User.Identity.GetUserId();
            //var currentUser = manager.FindById(getID);
            var YATUser = new User();
            Connections conn = new Connections();
            using (var dbContext = new YATContext())
            {
               YATUser = dbContext.User.Where(p => p.Id.Contains(getID)).FirstOrDefault();
               conn=  dbContext.Connections.Where(o => o.FromId == currentUser && o.ToId == getID).FirstOrDefault();
            }

            //Disable hide and blocked buttons if already hidden or blocked
            


            if (conn !=null)
            {
                ViewBag.Blocked = conn.IsBlocked;
                ViewBag.Hidden = conn.IsRemoved;
            }
            else
            {
                ViewBag.Blocked = false;
                ViewBag.Hidden = false;
            }
            return View(YATUser); 
        }
        public User getCurrentUser(string userID)
        {
            using (var dbContext = new YATContext())
            {
                return dbContext.User.Where(p => p.Id.Equals(userID)).FirstOrDefault(); 
            }

        }
 public IList<Likes> getUserLikes(string userID)
 {
     IList<Likes> likes = null;
     using (var dbContext = new YATContext())
     {
         likes = dbContext.User.Where(p => p.Id.Equals(userID)).First().Likes.ToList();
     }
     return likes;
 }
        // GET: UserSettings
        public ActionResult UserSettings(string userID = "")
        {
            var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
            var currentUser = manager.FindById(User.Identity.GetUserId());
            var YATUser = new User();

            using (var dbContext = new YATContext())
            {
                YATUser = dbContext.User.Where(p => p.Id.Contains(currentUser.Id)).FirstOrDefault();
            }

            return View(YATUser); 
        }
        public void testNormalCase()
        {
            var bob = new User
            {
                Address = "11791",
                FirstName = "Bob",
                LastName = "ForApples",
                Age = 28,
                Gender = false,
                Photo = "APPLE.jpg",
                Deleted = false,
                InterestedIn = true,
                RegistrationDate = DateTime.Now,
                LastLoginDate = DateTime.Now,

            };
            var mark = new User
            {
                Address = "11791",
                FirstName = "Mark",
                LastName = "man",
                Age = 28,
                Gender = false,
                Photo = "MARK.jpg",
                Deleted = false,
                InterestedIn = true,
                RegistrationDate = DateTime.Now,
                LastLoginDate = DateTime.Now,

            };
            var msg = new Message
            {
                Text = "spaghetti",
                From = bob,
                To = mark,
                Date = DateTime.Now,
                Read = false
            };
            db.User.Add(mark);
            db.User.Add(bob);
            db.Messages.Add(msg);
            db.SaveChanges();

            msging.read(mark.Id, msg.Id);
            db = new YATContext();
            Message mess = db.Messages.Where(m => m.Id.Equals(msg.Id)).FirstOrDefault();
            Assert.IsTrue(mess.Read);

        }
 public IEnumerable<IntRow> ageRank()
 {
     using (var db = new YATContext())
     {
         var rows = from user in db.User
                    group user by user.Age into tempTable
                    select new IntRow { name = tempTable.Key, value = tempTable.Count() } 
                    into selection
                    orderby selection.value descending
                    select selection;
         foreach (var row in rows)
         {
             Console.WriteLine("Age: {0} {1}", row.name, row.value);
         }
         return rows.ToList();
     }
 }
 public IEnumerable<IntRow> registrationMonths()
 {
     using (var db = new YATContext())
     {
         var rows = from user in db.User
                    group user by user.RegistrationDate.Month into tempTable
                    select new IntRow { name = tempTable.Key, value = tempTable.Count() } 
                    into selection
                    orderby selection.name
                    select selection;
         foreach (var row in rows)
         {
             Console.WriteLine("Month: {0} {1}", DateTimeFormatInfo.CurrentInfo.GetAbbreviatedMonthName(row.name), row.value);
         }
         return rows.ToList();
     }
 }
        // GET: Messages
        public ActionResult Index()
        {
            
            var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
            var currentUser = manager.FindById(User.Identity.GetUserId());
            User user;
            using (var dbContext = new YATContext())
            {
                user = dbContext.User.Where(p => p.Id.Contains(currentUser.Id)).FirstOrDefault();
            }
            string userid = user.Id;
            if (userid == null)
            {
                var messages = db.Messages.Include(m => m.From).Include(m => m.To);
                return View(messages.ToList());
            }
            else
            {
                Messaging msg = new Messaging();
                var messages = msg.getInbox(userid).ToList();
                messages.Reverse();
                List<String> noDupes = new List<String>();
                List<Message> result = new List<Message>();
                foreach (Message message in messages){

                    if (noDupes.Contains(message.From.Id))
                    {
                        continue;
                    }
                    if (userid.Equals(message.From.Id))
                    {
                        if (!noDupes.Contains(message.To.Id))
                        {
                        noDupes.Add(message.To.Id);
                        result.Add(message);
                        }
                        continue;
                    }
                    noDupes.Add(message.From.Id);
                    result.Add(message);
                }

                return View(result.ToList());
            }
        }
        public IEnumerable<StringRow> movieRank()
        {
            using (var db = new YATContext())
            {
                var rows = (from movie in db.Likes
                           orderby movie.Users.Count
                           select new StringRow
                           {
                               name = movie.Movie.ToString(),
                               value = movie.Users.Count
                           } into selection
                           orderby selection.value descending
                           select selection).Take(30);
                foreach (var row in rows)
                {
                    Console.WriteLine("Movie: {0} {1}", row.name, row.value);
                }

                return rows.ToList();
            }
        }
        public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
        {
            if (User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Index", "Manage");
            }

            if (ModelState.IsValid)
            {
                // Get the information about the user from the external login provider
                var info = await AuthenticationManager.GetExternalLoginInfoAsync();
                if (info == null)
                {
                    return View("ExternalLoginFailure");
                }
                var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
                var result = await UserManager.CreateAsync(user);
                if (result.Succeeded)
                {
                    result = await UserManager.AddLoginAsync(user.Id, info.Login);
                    if (result.Succeeded)
                    {
                        await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
                        using (var dbContext = new YATContext())
                        {
                            var YATuser = new User
                            {
                                Id = user.Id,
                                FirstName = model.FirstName,
                                LastName = model.LastName,
                                Age = model.Age,
                                Gender = model.Gender,
                                Address = model.Address,
                                InterestedIn = model.InterestedIn,
                                Deleted = false,
                                Photo=(model.Gender==true)?"male.jpg":"female.jpg",
                                RegistrationDate = DateTime.Now,
                                LastLoginDate = DateTime.Now,
                            };
                            dbContext.User.Add(YATuser);
                            dbContext.SaveChanges();
                        }
                        return RedirectToLocal(returnUrl);
                    }
                }
                AddErrors(result);
            }

            ViewBag.ReturnUrl = returnUrl;
            return View(model);
        }
        public void userGenerator(int count)
        {
            using (var dbContext = new YATContext())
            {
                if (dbContext.User.Count() > 10)
                {
                    return;
                }

                List<String> maleNames = new List<string>{"Jacob", "Michael", "Joshua", "Matthew", "Andrew", "Ethan", "Joseph", "Daniel", "Christopher", "Anthony", "William", "Nicholas", "Ryan", "David", "Tyler", "Alexander", "John", "James", "Dylan", "Zachary", "Brandon", "Jonathan", "Samuel", "Benjamin", "Christian", "Justin", "Nathan", "Logan", "Jose", "Noah", "Kevin", "Austin", "Caleb", "Robert", "Thomas", "Elijah", "Jordan", "Aidan", "Cameron", "Hunter", "Jason", "Connor", "Evan", "Jack", "Luke", "Angel", "Isaac", "Isaiah", "Aaron", "Gavin", "Jackson", "Kyle", "Mason", "Juan", "Eric", "Charles", "Adam", "Brian"};
                List<String> femaleNames = new List<string> { "Mary", "Patricia", "Jennifer", "Elizabeth", "Linda", "Barbara", "Susan", "Margaret", "Jessica", "Dorothy", "Sarah", "Karen", "Nancy", "Betty", "Lisa", "Sandra", "Helen", "Ashley", "Donna", "Kimberly", "Carol", "Michelle", "Emily", "Amanda", "Melissa", "Deborah", "Laura", "Stephanie", "Rebecca", "Sharon", "Cynthia", "Kathleen", "Ruth", "Anna", "Shirley", "Amy", "Angela", "Virginia", "Brenda", "Pamela", "Catherine", "Katherine", "Nicole", "Christine" };
                List<String> address = new List<string> { "94104", "10022", "20005", "20036", "20001", "20006", "10019", "60611", "60614", "10021", "11733", "10024", "10023", "67201", "10075", "89109", "10065", "94111", "77024", "22101", "20007", "90067", "10128", "33480", "82922", "60045", "10106", "20004", "20008", "15222", "75205", "94301", "10028", "75219", "10017", "76102", "10011", "60093", "20003", "90210", "30327", "20815", "20854", "20910", "90049" };
                //List<String> address = new List<string> {"94104", "10022"};
                List<String> movies = new List<string> { "The Shawshank Redemption", "The Godfather", "The Godfather: Part II", "The Dark Knight", "Pulp Fiction", "Schindler's List", "12 Angry Men", "The Good, the Bad and the Ugly", "The Lord of the Rings: The Return of the King", "Fight Club", "The Lord of the Rings: The Fellowship of the Ring", "Star Wars: Episode V - The Empire Strikes Back", "Inception", "One Flew Over the Cuckoo's Nest", "The Lord of the Rings: The Two Towers", "Goodfellas", "The Matrix", "Star Wars: Episode IV - A New Hope", "Seven Samurai", "City of God", "Se7en", "The Usual Suspects", "The Silence of the Lambs", "Interstellar", "It's a Wonderful Life", "Léon: The Professional", "Life Is Beautiful", "Once Upon a Time in the West", "Casablanca", "American History X", "Saving Private Ryan", "Raiders of the Lost Ark", "Spirited Away", "City Lights", "Psycho", "Rear Window"};
                foreach(var eachMovie in movies){
                    dbContext.Likes.Add(new Likes { Movie = eachMovie });
                }
               
                for (int i = 1; i <= count; i++)
                {
                    Random rnd = new Random();
                    
                    string zip = address[rnd.Next(address.Count)];
                    bool gender = rnd.Next(100) < 50 ? true : false;
                    string firstName;
                    if (gender){
                        firstName = maleNames[rnd.Next(maleNames.Count)];
                    }
                    else{
                        firstName = femaleNames[rnd.Next(femaleNames.Count)];
                    }
                    string lastName = maleNames[rnd.Next(maleNames.Count)];
                    int age = rnd.Next(18, 100);
                    
                    bool interestedIn = !gender;
                    DateTime registarationDate = DateTime.Now.AddDays(rnd.Next(365));
                    DateTime lastLoginDate = DateTime.Now.AddDays(rnd.Next(365));
                    String photo = gender ? "male.jpg" : "female.jpg";
                    User u = new User
                    {
                        Address = zip,
                        FirstName = firstName,
                        LastName = lastName,
                        Age = age,
                        Gender = gender,
                        Photo = photo,
                        Deleted = false,
                        InterestedIn = interestedIn,
                        RegistrationDate = registarationDate,
                        LastLoginDate = lastLoginDate,
                    };
                    dbContext.User.Add(u);

                    string movie = movies[rnd.Next(movies.Count)];
                    Likes l = dbContext.Likes.Where(p => p.Movie.Contains(movie)).FirstOrDefault();
                    u.Likes.Add(l);

                    dbContext.SaveChanges();
                }
            }
        }
        public ActionResult Read(string text, int hidden)
        {
            var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
            var currentUser = manager.FindById(User.Identity.GetUserId());
            User user;
            using (var dbContext = new YATContext())
            {
                user = dbContext.User.Where(p => p.Id.Contains(currentUser.Id)).FirstOrDefault();
            }
            string userid = user.Id;

            Message message = db.Messages.Find(hidden);
            Messaging msging = new Messaging();
            var toID = message.ToId;
            if (toID.Equals(userid))
            {
                toID = message.FromId;
            }
            msging.sendMessage(toID, userid, text);
            return Redirect(HttpContext.Request.UrlReferrer.AbsoluteUri);
        }
        public void putData()
        {
            using (var dbContext = new YATContext())
            {
                User paul = dbContext.User.Where(p => p.FirstName.Contains("Paul")).FirstOrDefault();
                if (paul != null)
                {
                    return;
                }

                paul = new User
                {
                    Id = "1",
                    Address = "11791",
                    FirstName = "Paul",
                    LastName = "Sultan",
                    Age = 28,
                    Gender = true,
                    Deleted = false,
                    InterestedIn = false,
                    Photo = "male.jpg",
                    RegistrationDate = Convert.ToDateTime("01/11/2015"),
                    LastLoginDate = DateTime.Now,
                };
                var mike = new User
                {
                    Address = "11791",
                    FirstName = "Mike",
                    LastName = "Sultan",
                    Age = 28,
                    Gender = true,
                    Deleted = false,
                    InterestedIn = false,
                    Photo = "male.jpg",
                    RegistrationDate = Convert.ToDateTime("01/10/2015"),
                    LastLoginDate = DateTime.Now,
                };
                var sue = new User
                {
                    Address = "10010",
                    FirstName = "Sue",
                    LastName = "Flower",
                    Age = 28,
                    Gender = false,
                    Deleted = false,
                    InterestedIn = true,
                    Photo = "female.jpg",
                    RegistrationDate = Convert.ToDateTime("04/10/2015"),
                    LastLoginDate = DateTime.Now,
                };
                var Ariel = new User
                {
                    Id = "d",
                    Address = "94101",
                    FirstName = "Brad",
                    LastName = "Gabe",
                    Age = 30,
                    Gender = true,
                    Deleted = false,
                    InterestedIn = false,
                    Photo = "male.jpg",
                    RegistrationDate = Convert.ToDateTime("04/10/2015"),
                    LastLoginDate = DateTime.Now,
                };
                dbContext.User.Add(paul);
                dbContext.User.Add(mike);
                dbContext.User.Add(sue);
                dbContext.User.Add(Ariel);
            
                var gump = new Likes { Movie = "Forest Gump" };
                var nemo = new Likes { Movie = "Finding Nemo" };
                var avengers = new Likes { Movie = "Avengers" };
                mike.Likes.Add(nemo);
                mike.Likes.Add(gump);
                paul.Likes.Add(nemo);
                sue.Likes.Add(avengers);
                sue.Likes.Add(gump);

                Likes movie = dbContext.Likes.FirstOrDefault(L => L.Movie == "Avengers");
                Ariel.Likes.Add(movie);

                var sueConnection = new Connections { From = sue, To = mike, IsBlocked = true, IsRemoved=false };
                var sueConnection2 = new Connections { From = sue, To = paul, IsBlocked=false, IsRemoved = true };
                dbContext.Connections.Add(sueConnection);
                dbContext.Connections.Add(sueConnection2);
                
                var message = new Message
                {
                    Text = "Hi there",
                    From = mike,
                    To = sue,
                    Date = DateTime.Now,
                    Read = false
                };
                var reply = new Message
                {
                    Text = "Hello",
                    From = sue,
                    To = mike,
                    Date = DateTime.Now.AddMinutes(5),
                    Read = false
                };
                var repAgain = new Message
                {
                    Text = "wanna go program some tests??!?!!",
                    From = mike,
                    To = sue,
                    Date = DateTime.Now.AddMinutes(8),
                    Read = false
                };
                var anotherMessage = new Message
                {
                    Text = "something awesome",
                    From = Ariel,
                    To = sue,
                    Date = DateTime.Now,
                    Read = false
                };
                dbContext.Messages.Add(message);
                dbContext.Messages.Add(reply);
                dbContext.Messages.Add(repAgain);
                dbContext.SaveChanges();
            }
        }
        public List<User> queryUsers(int minAge, int maxAge, bool gender, bool InterestedIn, string address, string SearcherID, UserSort sortBy)
        {
            string qryStr;
            string excludeQry = "select ToID from dbo.Connections where FromID ='" + SearcherID + "' and (isRemoved=1 or isBlocked=1)";
            string filteredUsers =
                "SELECT u.ID from dbo.Users as u where u.Deleted=0 " +
                 " and u.ID!='" + SearcherID + "' and u.Age >=" + minAge + " and u.Age<=" + maxAge +
              " and u.Gender = " + Convert.ToInt32(gender) + " and u.InterestedIn= " + Convert.ToInt32(InterestedIn) +" and u.ID not in (" + excludeQry +")";

            if (address!="") filteredUsers = filteredUsers+ " and u.Address = '" + address + "'";



                 string  defaultStr = "Select * from dbo.Users WHERE dbo.Users.ID in (" + filteredUsers + ")";
            //get the user's likes list, count the likes match for every result, and sort by top match
            using (var dbContext = new YATContext())
            {
                switch (sortBy) // Sort according to criterion
                {
                   case UserSort.Match: //sort by most mutual likes
                        qryStr = "Select * from dbo.Users inner join " +
                                "(select filteredUsers.ID,count(filteredUsers.ID) as score from " +
                             " ( " + filteredUsers + ")" +
                              " as filteredUsers " +
                                      "left join" +
                             "(SELECT dbo.LikesUsers.user_ID, dbo.LikesUsers.Likes_Id from   dbo.LikesUsers where " +
                                    "dbo.LikesUsers.Likes_Id in " +
                                    "(SELECT dbo.LikesUsers.Likes_ID from   dbo.LikesUsers where " +
                                                                  " dbo.LikesUsers.User_ID='" + SearcherID  + "')) as movies " +
                                                                        " on filteredUsers.ID = movies.User_Id " +
                                                                              "GROUP by filteredUsers.ID) as results on results.ID=dbo.Users.ID order by score";
                    break;
                    case UserSort.LastLog:
                    qryStr = defaultStr + 
                              " order by LastLoginDate desc";
                    break;
                    case UserSort.LastJoin:  
                    qryStr = defaultStr + 
                              " order by RegistrationDate desc";
                    break;
                    default:
                    qryStr = defaultStr; 
                    break;
                }
            
           List<User> users = dbContext.User.SqlQuery(qryStr).ToList();
           return users;
            }
        }
 public ActionResult SendMessage(string text, string hidden)
 {
     var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
     var currentUser = manager.FindById(User.Identity.GetUserId());
     User fromUser;
     using (var dbContext = new YATContext())
     {
         fromUser = dbContext.User.Where(p => p.Id.Contains(currentUser.Id)).FirstOrDefault();
     }
     var user = db.User.Find(hidden);
     Messaging msging = new Messaging();
     msging.sendMessage(hidden, fromUser.Id, text);
     return Redirect(Url.Content("~/Messages"));
 }
 public void getData()
 {
     using (var db = new YATContext())
     {
         var users = from user in db.User select user;
         foreach (var user in users)
         {
             Debug.WriteLine(user.FirstName);
             Debug.WriteLine("-Address: " + user.Address);
             foreach (var likes in user.Likes)
             {
                 Debug.WriteLine("-MOVIE: " + likes.Movie);
             }
         }
     }
 }
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser { UserName = model.Email, Email = model.Email};                
                var result = await UserManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
                    
                    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                    using(var dbContext = new YATContext())
                    {
                        var YATuser = new User
                        {  
                            Id=user.Id,
                            FirstName = model.FirstName,
                            LastName = model.LastName,
                            Age = model.Age,
                            Gender = model.Gender,
                            Address = model.Address,
                            InterestedIn = model.InterestedIn,
                            Deleted = false,
                            Photo = (model.Gender == true) ? "male.jpg" : "female.jpg",
                            RegistrationDate = DateTime.Now,
                            LastLoginDate = DateTime.Now,
                            
                        };
                        dbContext.User.Add(YATuser);
                        dbContext.SaveChanges();
                    }

                    return RedirectToAction("Index", "Home");
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
 public IEnumerable<StringRow> stateCount()
 {
     using (var db = new YATContext())
     {
         var rows = from user in db.User
                    group user by user.Address into tempTable
                    select new { name = tempTable.Key, value = tempTable.Count() } 
                    into selection
                    orderby selection.value descending
                    select selection;               
         SortedDictionary<String, int> stateCount = new SortedDictionary<String, int>();
         foreach (var row in rows)
         {
             if (zipStates.Keys.Contains(row.name))
             {
                 if (stateCount.Keys.Contains(zipStates[row.name]))
                 {
                     stateCount[zipStates[row.name]] += row.value;
                 }
                 else
                 {
                     stateCount[zipStates[row.name]] = row.value;
                 }
             }
         }
         var newRows = from entry in stateCount 
                       select new StringRow {name = entry.Key, value = entry.Value}
                       into selection
                       orderby selection.value descending
                       select selection;
         foreach (var row in newRows)
         {
             Console.WriteLine("State: {0} {1}", row.name, row.value);
         }
         return newRows;
     }
 }