Esempio n. 1
0
        public bool UpdateTime(UserHoursViewModel data)
        {
            var selectedUsers = data.Users.Where(x => x.IsSelected == true);

            if (data.AddHours == true)
            {
                foreach (var user in selectedUsers)
                {
                    var userFound = dbContext.Users.Include(x => x.Billing).SingleOrDefault(x => x.Id == user.UserId);

                    userFound.Billing.MinutesWorked += (data.MinutesToEdit + (data.HoursToEdit * 60));
                }
            }
            else
            {
                foreach (var user in selectedUsers)
                {
                    var userFound = dbContext.Users.Include(x => x.Billing).SingleOrDefault(x => x.Id == user.UserId);

                    var newTime = userFound.Billing.MinutesWorked -= (data.MinutesToEdit + (data.HoursToEdit * 60));

                    if (newTime < 0)
                    {
                        return(true);
                    }
                }
            }

            dbContext.SaveChanges();
            return(false);
        }
        public Customer AddCustomer([FromBody] Customer cust)
        {
            Customer newCust = new Customer {
                Name = cust.Name
            };

            db.Add(newCust);
            db.SaveChanges();
            return(newCust);
        }
Esempio n. 3
0
        public ActionResult Registration(UserViewModel model)
        {
            if (ModelState.IsValid)
            {
                var password          = model.Password;
                var encryptedPassword = CustomEncrypt.Encrypt(password);

                using (var context = new MvcDbContext())
                {
                    var userAlreadyExists = context.Users.Any(usr => usr.Email == model.Email);
                    if (userAlreadyExists)
                    {
                        return(RedirectToAction("Registration"));
                    }
                    Users user = context.Users.Create();
                    user.Email    = model.Email;
                    user.Password = encryptedPassword;
                    user.Name     = model.Name;
                    user.Country  = model.Country;

                    context.Users.Add(user);
                    context.SaveChanges();
                }
                return(RedirectToAction("Login", "Auth"));
            }

            ModelState.AddModelError("", "One or more fields are invalid");
            return(View());
        }
        public IActionResult Message(string text)
        {
            Message     message = new Message();
            LoginHelper lh      = new LoginHelper();

            Console.WriteLine(text);
            message.author_id = lh.getUserID();
            message.text      = text;
            message.pub_date  = (Int32)(DateTimeOffset.Now.ToUnixTimeSeconds());
            message.flagged   = 0;

            _context.message.Add(message);
            _context.SaveChanges();

            return(RedirectToAction("Timeline"));
        }
Esempio n. 5
0
        public static void Initialize(IServiceProvider serviceProvider)
        {
            using (var context = new MvcDbContext(
                       serviceProvider.GetRequiredService <
                           DbContextOptions <MvcDbContext> >()))
            {
                if (context.User.Any())
                {
                    return;   // DB has been seeded
                }

                context.User.AddRange(
                    new User
                {
                    FirstName     = "James",
                    LastName      = "Hemingway",
                    Email         = "*****@*****.**",
                    Address       = "Hopsavej 2",
                    Telephone     = "10101010",
                    Zipcode       = "1010",
                    AddAutismInfo = true
                },

                    new User
                {
                    FirstName     = "Billy",
                    LastName      = "Brighton",
                    Email         = "*****@*****.**",
                    Address       = "Wassupgade 7",
                    Telephone     = "93057193",
                    Zipcode       = "4362",
                    AddAutismInfo = false
                },

                    new User
                {
                    FirstName     = "Mike",
                    LastName      = "Scallywag",
                    Email         = "*****@*****.**",
                    Address       = "Nejstræde 10",
                    Telephone     = "49571383",
                    Zipcode       = "8452",
                    AddAutismInfo = true
                },

                    new User
                {
                    FirstName     = "Hans",
                    LastName      = "Carlos Alexandros",
                    Email         = "*****@*****.**",
                    Address       = "Kanon Alle 5",
                    Telephone     = "10859291",
                    Zipcode       = "1846",
                    AddAutismInfo = true
                }
                    );
                context.SaveChanges();
            }
        }
        /// <summary>
        /// Metoda dodajaca uzytkownika do listy i zapisujaca zmiany w bazie danych.
        /// W przypadku gdy dodawany jest nowy uzytkownik zostaje oddany on do bazy danych.
        /// W przypadku gdy uzytkownik istnieje zostaja zapisane nowe dane danego uzytkownika.
        /// </summary>
        /// <param name="entity">Obiekt przechowujacy dane uzytkownika</param>
        /// <returns>Jesli obiekt przekazany przez uzytkownika nie jest pusty, po operacjach metoda zwroci wartosc true,
        /// w przeciwnym wypadku zwroci false.</returns>

        public bool AddUpdate(UserModel entity)
        {
            if (entity != null)
            {
                if (entity.ID == 0)
                {
                    db.Users.Add(entity);
                }

                db.SaveChanges();
                return(true);
            }

            else
            {
                return(false);
            }
        }
Esempio n. 7
0
        public ActionResult Create(Book book)
        {
            MvcDbContext db = new MvcDbContext();

            //db.Entry(book).State = System.Data.Entity.EntityState.Added;//状态跟踪
            db.Books.Add(book);
            db.SaveChanges();
            return(RedirectToAction(nameof(Index)));//nameof(Index) 当Index控制器重命名时跟着重命名
        }
Esempio n. 8
0
        public bool AddRole(RoleModel entity)
        {
            if (entity != null)
            {
                db.Roles.Add(entity);
                db.SaveChanges();

                return(true);
            }
            return(false);
        }
Esempio n. 9
0
        public void PopulateTestData(MvcDbContext dbContext)
        {
            user = new User {
                username = "******", pw_hash = "somehash", pw_hash2 = "somehash", email = "seed@seed"
            };
            dbContext.user.Add(user);
            message = new Message {
                author_id = 0, author = user, text = "seed message"
            };
            dbContext.message.Add(message);

            dbContext.SaveChanges();
        }
        public static void Initialize(IServiceProvider serviceProvider)
        {
            using (var context = new MvcDbContext(
                       serviceProvider.GetRequiredService <
                           DbContextOptions <MvcDbContext> >()))
            {
                if (context.Lecture.Any())
                {
                    return;   // DB has been seeded
                }

                context.Lecture.AddRange(
                    new Lecture
                {
                    Title       = "Autisme og mig",
                    StartTime   = DateTime.Parse("09:00"),
                    Speaker     = "Karl Bøje",
                    Description = "Min historie om autisme",
                    TimeFrame   = 2,
                },

                    new Lecture
                {
                    Title       = "Ro i sind",
                    StartTime   = DateTime.Parse("10:30"),
                    Speaker     = "Ove Larsen",
                    Description = "Metoder til at undgå stress",
                    TimeFrame   = 3,
                },

                    new Lecture
                {
                    Title       = "Stille barn",
                    StartTime   = DateTime.Parse("09:30"),
                    Speaker     = "Nadia Uldum",
                    Description = "Pædagogik i børnehaven",
                    TimeFrame   = 3,
                },

                    new Lecture
                {
                    Title       = "Autisme i samfundet",
                    StartTime   = DateTime.Parse("11:00"),
                    Speaker     = "Eva Marie Svendsen",
                    Description = "Viden i det danske samfund",
                    TimeFrame   = 2,
                }
                    );
                context.SaveChanges();
            }
        }
Esempio n. 11
0
        public IActionResult Register(RegisterUserBindingModel model)
        {
            var user = new User
            {
                Username = model.Username,
                Password = model.Password
            };

            using (var context = new MvcDbContext())
            {
                context.Users.Add(user);
                context.SaveChanges();
            }
            return(View());
        }
Esempio n. 12
0
        public ActionResult Delete(int id)
        {
            using (var dbContext = new MvcDbContext())
            {
                var model = dbContext.Lists.Find(id);
                if (model == null)
                {
                    return(HttpNotFound());
                }

                dbContext.Lists.Remove(model);
                dbContext.SaveChanges();
                return(RedirectToAction("Index"));
            }
        }
Esempio n. 13
0
        public IActionResult <UserPrifileViewModel> Profile(AddNoteBindingModel model)
        {
            using (var context = new MvcDbContext())
            {
                var user = context.Users.FirstOrDefault(x => x.iD == model.Id);

                var note = new Note
                {
                    Title   = model.Title,
                    Content = model.Content
                };
                user.Notes.Add(note);
                context.SaveChanges();

                return(Profile(model.Id));
            }
        }
Esempio n. 14
0
        public ActionResult Index(ListViewModel model)
        {
            if (ModelState.IsValid)
            {
                string timeToday = DateTime.Now.ToString("h:mm:ss tt");
                string dateToday = DateTime.Now.ToString("M/dd/yyyy");

                Claim  sessionEmail = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Email);
                string userEmail    = sessionEmail.Value;
                string text_details = Request.Form["text_details"];
                string check_public = Request.Form["check_public"];
                using (var dbContext = new MvcDbContext())
                {
                    Users user = dbContext.Users.FirstOrDefault(usr => usr.Email == userEmail);
                    Lists list = dbContext.Lists.Create();
                    list.Details     = text_details;
                    list.Date_Posted = dateToday;
                    list.Time_Posted = timeToday;
                    if (user != null)
                    {
                        list.User_Id = user.Id;
                        if (check_public != null)
                        {
                            list.Public = "YES";
                        }
                        else
                        {
                            list.Public = "NO";
                        }
                        dbContext.Lists.Add(list);
                        dbContext.SaveChanges();
                        ModelState.Clear();
                    }
                }
            }
            else
            {
                ModelState.AddModelError("", "One or more fields are having an incorrect format");
            }

            List <ListViewModel> listItems = GetListItems();

            return(View(listItems));
        }
Esempio n. 15
0
 public ActionResult Registration(UserViewModel uservm)
 {
     if (ModelState.IsValid)
     {
         var encryptedPassword = CustomEncrypt.Encrypt(uservm.Password);
         using (var context = new MvcDbContext())
         {
             var user = context.Users.Create();
             user.Email    = uservm.Email;
             user.Password = encryptedPassword;
             user.Country  = uservm.Country;
             user.Name     = uservm.Name;
             context.Users.Add(user);
             context.SaveChanges();
         }
     }
     else
     {
         ModelState.AddModelError("", "One or more fields are invalid");
     }
     return(View());
 }
        public static void Initialize(IServiceProvider serviceProvider)
        {
            using (var context = new MvcDbContext(
                       serviceProvider.GetRequiredService <
                           DbContextOptions <MvcDbContext> >()))
            {
                if (context.Room.Any())
                {
                    return;   // DB has been seeded
                }

                context.Room.AddRange(
                    new Room
                {
                    Name     = "A2.10",
                    Capacity = 20
                },

                    new Room
                {
                    Name     = "C1.07",
                    Capacity = 5
                },

                    new Room
                {
                    Name     = "B3.04",
                    Capacity = 25
                },

                    new Room
                {
                    Name     = "A1.05",
                    Capacity = 10
                }
                    );
                context.SaveChanges();
            }
        }
Esempio n. 17
0
        public ActionResult Edit(ListViewModel model)
        {
            string timeToday    = DateTime.Now.ToString("h:mm:ss tt");
            string dateToday    = DateTime.Now.ToString("M/dd/yyyy");
            string text_details = Request.Form["text_details"];
            string check_public = Request.Form["check_public"];

            if (ModelState.IsValid)
            {
                using (var dbContext = new MvcDbContext())
                {
                    Lists list = dbContext.Lists.Find(model.Id);
                    list.Time_Edited            = timeToday;
                    list.Date_Edited            = dateToday;
                    list.Details                = text_details;
                    list.Public                 = check_public != null ? "YES" : "NO";
                    dbContext.Entry(list).State = EntityState.Modified;
                    dbContext.SaveChanges();
                    return(RedirectToAction("Index"));
                }
            }
            return(View(model));
        }
Esempio n. 18
0
        public bool WithdrawMoney(WithdrawalViewModel data, string userId)
        {
            var user = dbContext.Users.Include(x => x.Billing).Include(x => x.AccountHistory)
                       .SingleOrDefault(x => x.Id == userId);

            var amount       = data.AmountToWithdraw;
            var balanceAfter = user.Billing.Balance -= amount;

            if (balanceAfter < 0)
            {
                return(true);
            }

            user.AccountHistory.Add(new AccountHistoryEntity
            {
                ActionType   = "wypłata",
                Amount       = (double)amount,
                BalanceAfter = (double)balanceAfter,
                Date         = DateTime.Now
            });

            dbContext.SaveChanges();
            return(false);
        }
Esempio n. 19
0
        public IActionResult Follow(string username, int no_followers = 100)
        {
            var verb   = _accessor.HttpContext.Request.Method.ToString();
            var json   = _accessor.HttpContext.Request.ReadFromJsonAsync <ApiDataFollow>();
            int userid = GetUserId(username);

            UpdateLatest();
            if (userid == -1)
            {
                _logger.LogWarning("No user exist for {Username}.", username);
                return(BadRequest("error"));
            }

            if (verb == "POST" && json.Result.follow != null)
            {
                string userToFollow   = json.Result.follow;
                int    userToFollowId = GetUserId(userToFollow); //find the id of user to follow
                if (userToFollowId == -1)
                {
                    return(NotFound());
                }

                var followersOfUserId = _context.follower.Where(f => f.who_id == userid).ToList();

                if (followersOfUserId.Where(f => f.whom_id == userToFollowId).Any())
                {
                    //_logger.LogInformation("{whoID}, already follows {whomID}.", userid.ToString(), userToFollowId.ToString());
                    return(BadRequest(username + " already follows " + userToFollow));
                }

                Follower follower = new Follower();
                follower.who_id  = userid;
                follower.whom_id = userToFollowId;
                _context.Add(follower);
                _context.SaveChanges();
                //_logger.LogInformation("{whoID}, now follows {whomID}.", userid.ToString(), userToFollowId.ToString());
                return(NoContent());
            }
            else if (verb == "POST" && json.Result.unfollow != null)
            {
                string userToUnfollow   = json.Result.unfollow;
                int    userToUnfollowId = GetUserId(userToUnfollow);
                if (userToUnfollowId == -1)
                {
                    return(NotFound());
                }

                var followersOfUserId = _context.follower.AsNoTracking().Where(f => f.who_id == userid).ToList();

                if (!followersOfUserId.Where(f => f.whom_id == userToUnfollowId).Any())
                {
                    //_logger.LogInformation("{whoID}, is not currently following {whomID}.", userid.ToString(), userToUnfollowId.ToString());
                    return(BadRequest(username + " isn't following " + userToUnfollow + " to begin with"));
                }

                Follower follower = new Follower();
                follower.who_id  = userid;
                follower.whom_id = userToUnfollowId;
                _context.Remove(follower);
                _context.SaveChanges();
                //_logger.LogInformation("{whoID}, is not following {whomID} anymore.", userid.ToString(), userToUnfollowId.ToString());
                return(NoContent());
            }
            else if (verb == "GET")   //needs refactoring to use ORM instead of query
            {
                var query = (from f in _context.follower

                             join u in _context.user on f.whom_id equals u.user_id
                             where f.who_id == userid
                             select
                             new { u.username })
                            .Take(no_followers).ToList();
                List <string> Follows = new List <string>();
                foreach (var item in query)
                {
                    Follows.Add(item.username);
                }
                ApiDataFollows returnfollows = new ApiDataFollows {
                    follows = Follows
                };
                var jsonreturn = JsonSerializer.Serialize(returnfollows);
                //_logger.LogInformation("Fetched follower list for {whoID}", userid.ToString());
                return(Ok(jsonreturn));
            }
            return(Ok("other"));
        }
 public ActionResult SaveUser(User user)
 {
     applicationContex.Users.Add(user);
     applicationContex.SaveChanges();
     return(RedirectToAction("UserList", "Users"));
 }
        public static void Initialize(IServiceProvider serviceProvider)
        {
            using (var context = new MvcDbContext(
                       serviceProvider.GetRequiredService <
                           DbContextOptions <MvcDbContext> >()))
            {
                if (context.Booking.Any())
                {
                    return;   // DB has been seeded
                }

                context.Booking.AddRange(
                    new Booking
                {
                    UserId    = 1,
                    LectureId = 1
                },

                    new Booking
                {
                    UserId    = 2,
                    LectureId = 1
                },

                    new Booking
                {
                    UserId    = 1,
                    LectureId = 3
                },

                    new Booking
                {
                    UserId    = 4,
                    LectureId = 4
                },

                    new Booking
                {
                    UserId    = 1,
                    LectureId = 2
                },

                    new Booking
                {
                    UserId    = 2,
                    LectureId = 2
                },

                    new Booking
                {
                    UserId    = 2,
                    LectureId = 4
                },

                    new Booking
                {
                    UserId    = 3,
                    LectureId = 4
                }
                    );
                context.SaveChanges();
            }
        }