public ActionResult CreateGroup(Group group)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var loggedUser = User.Identity.GetUserId();
                    group.CreatorId = loggedUser;
                    group.CreatedAt = DateTime.Now;
                    db.Groups.Add(group);
                    GroupUsers joined = new GroupUsers();
                    joined.UserId  = loggedUser;
                    joined.GroupId = group.GroupId;
                    db.GroupUsers.Add(joined);
                    db.SaveChanges();
                    TempData["message"] = "You successfully created the group!";

                    return(RedirectToAction("Index"));
                }
                else
                {
                    return(View(group));
                }
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e.Source + e.Message);
                return(View(group));
            }
        }
示例#2
0
        public long CreateGroup(string groupName, string description, string loginName)
        {
            if (GroupUsersDao.ExistGroupName(groupName))
            {
                throw new GroupAlreadyExistsException(groupName);
            }

            UserProfile userProfile;
            GroupUsers  group;

            try { userProfile = UsersProfileDao.FindByLoginName(loginName); }
            catch (InstanceNotFoundException)
            {
                throw new UserNotFoundException(loginName);
            }

            group = new GroupUsers
            {
                gr_description = description,
                gr_name        = groupName,
                gr_owner       = userProfile.userId
            };

            GroupUsersDao.Create(group);

            AddUserToGroup(loginName, group.group_usersId);

            return(group.group_usersId);
        }
        public ActionResult JoinGroup(int id)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var        loggedUser = User.Identity.GetUserId();
                    GroupUsers grpusr     = new GroupUsers();
                    grpusr.GroupId = id;
                    grpusr.UserId  = loggedUser;
                    db.GroupUsers.Add(grpusr);
                    db.SaveChanges();
                    TempData["message"] = "You successfully joined the group!";

                    return(RedirectToAction("View", new { id }));
                }
                else
                {
                    return(RedirectToAction("View", new { id }));
                }
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e.Source + e.Message);
                return(RedirectToAction("View", new { id }));
            }
        }
示例#4
0
        public async Task <IActionResult> PutGroupUsers(int id, GroupUsers groupUsers)
        {
            if (id != groupUsers.GroupUserId)
            {
                return(BadRequest());
            }

            _context.Entry(groupUsers).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!GroupUsersExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
        public ActionResult DeleteMember(GroupUsers gu)
        {
            var currentUserId = User.Identity.GetUserId();

            if (GroupAuth.IsAdminOrCreator(gu.GroupId, currentUserId))
            {
                GroupUsers user = db.GroupUsers.Where(g => g.GroupId == gu.GroupId && g.UserId == gu.UserId).FirstOrDefault();
                if (user is null)
                {
                    return(Redirect("/Groups/Members/" + gu.GroupId));
                }
                else if (currentUserId != user.UserId && user.UserId != user.Group.UserId)
                {
                    string author    = user.User.Email;
                    string notifBody = "<p>Ne pare rau, </p>";
                    notifBody += "<p>Un administrator al grupului <b>" + user.Group.GroupName + "</b> v-a eliminat din grup :(</p>";
                    notifBody += "<br/> <p>Echipa <b>DAW-social-app</b>.</p>";
                    Email.SendEmailNotification(author, "Ati fost eliminat!", notifBody);

                    db.GroupUsers.Remove(user);
                    db.SaveChanges();
                    TempData["message"] = "Userul " + db.Users.Find(gu.UserId).UserName + " a fost sters";
                    return(Redirect("/Groups/Members/" + gu.GroupId));
                }
                else
                {
                    return(Redirect("/Groups/Members/" + gu.GroupId));
                }
            }
            else
            {
                return(Redirect("/Groups/Show/" + gu.GroupId));
            }
        }
示例#6
0
        public List <DTORecommendation> ShowGroupRecommendations(long groupId)
        {
            GroupUsers group = new GroupUsers();
            string     eventName;

            try { group = GroupUsersDao.Find(groupId); }
            catch (InstanceNotFoundException)
            {
                throw new GroupNotFoundException(groupId);
            }
            List <DTORecommendation> dtoRecommendations = new List <DTORecommendation>();

            try
            {
                List <Recommendation> recomendations = RecommendationDao.FindRecommendationsByGroupId(groupId);

                foreach (var recommedation in recomendations)
                {
                    try { eventName = recommedation.SportEvent.ev_name; }
                    catch (InstanceNotFoundException)
                    {
                        throw new SportEventNotFoundException(groupId);
                    }
                    UserProfile user = UsersProfileDao.Find(recommedation.userId);
                    dtoRecommendations.Add(new DTORecommendation(recommedation.recommendationId, eventName, user.loginName,
                                                                 recommedation.eventId, recommedation.recommendation_text));
                }
            }
            catch (InstanceNotFoundException)
            {
                throw new GroupNotFoundException(groupId);
            }
            return(dtoRecommendations);
        }
示例#7
0
        public async Task <ActionResult <GroupUsers> > PostGroupUsers(GroupUsers groupUsers)
        {
            _context.GroupUsers.Add(groupUsers);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetGroupUsers", new { id = groupUsers.GroupUserId }, groupUsers));
        }
示例#8
0
        public ActionResult Save(Group group)
        {
            if (!ModelState.IsValid)
            {
                var viewmodel = new GroupFormViewModel
                {
                    group      = group,
                    sourcePage = "Create your own group",
                    AdminId    = group.applicationUserId
                };
                return(View("GroupForm", viewmodel));
            }
            else
            {
                _context.Groups.Add(group);
                _context.SaveChanges();

                var GroupUser = new GroupUsers()
                {
                    applicationUserId = group.applicationUserId,
                    groupId           = group.Id
                };
                _context.GroupUsers.Add(GroupUser);
                _context.SaveChanges();


                return(RedirectToAction("Group", new RouteValueDictionary(
                                            new { controller = "Groups", action = "Group", id = group.Id })));
            }
        }
示例#9
0
        public async Task <bool> AddAdminGroupUsersAsync(GroupUsers groupUsers)
        {
            var response = await GetAdminUrl("/groups/add-users")
                           .PostJsonAsync(groupUsers)
                           .ConfigureAwait(false);

            return(await HandleResponseAsync(response).ConfigureAwait(false));
        }
示例#10
0
    public static void AddGroupAdmin(string groupId, string userId)
    {
        GroupUsers user = GroupUsers.Get(groupId, userId);
        if (user == null)
            user = new GroupUsers(groupId, userId, true);
        else
            user.IsAdmin = true;

        user.Save();
    }
示例#11
0
        public async Task <bool> UserIsGroup()
        {
            User user = await userManager.GetUserAsync(User);

            GroupUsers groupUsers = dataBaseContext.GroupUsers
                                    .Where(g => g.UserId == user.Id)
                                    .FirstOrDefault();

            return(groupUsers != null ? true : false);
        }
示例#12
0
        public void Initialize()
        {
            var mockDb = new MockDataContext();

            // Groups
            var g1 = new Group {
                Id = 1, UserId = "dabs"
            };

            mockDb.Groups.Add(g1);
            var g2 = new Group {
                Id = 1, UserId = "gummi"
            };

            mockDb.Groups.Add(g2);
            var g3 = new Group {
                Id = 1, UserId = "dabs"
            };

            mockDb.Groups.Add(g3);
            var g4 = new Group {
                Id = 1, UserId = "dabs"
            };

            mockDb.Groups.Add(g4);

            // GroupUsers
            var gu1 = new GroupUsers {
                Id = 1, GroupId = 1, UserId = "gummi"
            };

            mockDb.GroupUsers.Add(gu1);
            var gu2 = new GroupUsers {
                Id = 2, GroupId = 2, UserId = "dabs"
            };

            mockDb.GroupUsers.Add(gu2);
            var gu3 = new GroupUsers {
                Id = 3, GroupId = 1, UserId = "dabs"
            };

            mockDb.GroupUsers.Add(gu3);
            var gu4 = new GroupUsers {
                Id = 4, GroupId = 3, UserId = "gauja"
            };

            mockDb.GroupUsers.Add(gu4);
            var gu5 = new GroupUsers {
                Id = 5, GroupId = 1, UserId = "gauja"
            };

            mockDb.GroupUsers.Add(gu5);

            _service = new GroupService(mockDb);
        }
示例#13
0
        public async Task Create(string userId, int groupId)
        {
            GroupUsers groupUsers = new GroupUsers()
            {
                UserId   = userId,
                GroupsId = groupId
            };
            await dataBaseContext.GroupUsers.AddAsync(groupUsers);

            await dataBaseContext.SaveChangesAsync();
        }
        public ActionResult LeaveGroup(int id)
        {
            string     loggedUser = User.Identity.GetUserId();
            GroupUsers relation   = (from user in db.GroupUsers
                                     where user.UserId == loggedUser && user.GroupId == id
                                     select user).FirstOrDefault();

            db.GroupUsers.Remove(relation);
            db.SaveChanges();
            TempData["message"] = "You left the group!";
            return(RedirectToAction("View", new { id }));
        }
示例#15
0
        public ActionResult GrantAccessToGroup(int?requestId)
        {
            if (requestId.HasValue)
            {
                GroupUsers newUser = new GroupUsers();
                newUser.UserId  = _groupService.GetRequestUserId(requestId.Value);
                newUser.GroupId = _groupService.GetGroupRequestGroupId(requestId);
                _groupService.AcceptGroupRequest(newUser);
                _groupService.DeleteGroupRequest(requestId.Value);
                return(RedirectToAction("Reports", "User"));
            }

            return(RedirectToAction("Reports", "User"));
        }
        public IActionResult Create(CreateGroupViewModel model)
        {
            // Checks that the model is valid
            if (!ModelState.IsValid)
            {
                model.AccessTypes = DatabaseConnector.Get <AccessTypes>();
                model.Users       = DatabaseConnector.GetWhere <Users>("OrganisationID=" + OrganisationHelper.GetOrganisationID(HttpContext.Session));
                return(View(model));
            }

            // Creates the new group with the info
            Groups newGroup = new Groups()
            {
                Group_Name = model.GroupName,
                CreatedBy  = UserHelper.GetUserId(HttpContext.Session),
                AccessType = model.AccessType
            };

            // Saves the group to the database and gets it id.
            newGroup.GroupID = DatabaseConnector.AddGroup(newGroup);

            // Adds all the wanted users to the group.
            if (model.GroupUsers != null)
            {
                foreach (var usr in model.GroupUsers)
                {
                    // Now using check boxes we need to make sure they are selected.
                    if (usr.Selected)
                    {
                        GroupUsers user = new GroupUsers()
                        {
                            GroupID = newGroup.GroupID,
                            UserID  = usr.UserID
                        };
                        DatabaseConnector.AddGroupUser(user);
                    }
                }
                DatabaseConnector.PushChanges();
            }

            // Returns a serilaised object if the page is going to closed
            if (model.CloseAfter)
            {
                return(new JsonResult(newGroup.GroupID + ";" + newGroup.Group_Name));
            }

            // Redirects to the list of groups.
            return(RedirectToAction("Index", "Groups"));
        }
示例#17
0
 public Events RemoveUserFromGroup(GroupUsers groupUser, ClaimsPrincipal principal)
 {
     return(_repo.Create(new Events
     {
         Action = "REMOVE_USER_FROM_GROUP",
         Data = JsonConvert.SerializeObject(new
         {
             group_id = groupUser.GroupId,
             user_id = groupUser.UserId,
         }),
         Message = $"Admin remove {groupUser.User.UserName} from group \"{groupUser.Group.Name}\"",
         Time = DateTime.UtcNow,
         UserId = principal.Identity.Name
     }).Entity);
 }
示例#18
0
        public void AddGroup(Groups group, Accounts account)
        {
            //create and add the group to database
            databasecon.Groups.Add(group);

            //register the user, to the group he just made
            GroupUsers user = new GroupUsers();

            user.AccountId = account.id;
            user.FromGroup = group.GroupKey;
            databasecon.GroupUsers.Add(user);

            //save database changes
            databasecon.SaveChanges();
        }
示例#19
0
        public ValueTuple <GroupUsers, string> ChangeUserRoleInGroup(GroupUsers groupUser)
        {
            var      iDomain = _uow.GetService <IdentityDomain>();
            AppRoles role;

            if (groupUser.Role.Name.Equals("User"))
            {
                role = iDomain.GetRoleByName("Manager");
            }
            else
            {
                role = iDomain.GetRoleByName("User");
            }
            groupUser.RoleId = role.Id;
            return(ValueTuple.Create(groupUser, role.Name));
        }
示例#20
0
        public string RemoveMember(UserData memberToRemove, UserData executer)
        {
            bool isExecuterManager = GroupManagers.Any(member => member.UID == executer.UID);

            if (isExecuterManager)
            {
                var toRemove = GroupUsers.Where(member => member.UID == memberToRemove.UID).ToList().First();
                if (toRemove != null)
                {
                    GroupUsers.Remove(toRemove);
                    return($"{toRemove.Name} removed from group {Name}");
                }
                return($"User {toRemove.Name} is not in group {Name}");
            }
            return($"You are not a manager of {Name} group");
        }
示例#21
0
 public Events ChangeUserRoleInGroup(GroupUsers groupUsers, string roleName, ClaimsPrincipal principal)
 {
     return(_repo.Create(new Events
     {
         Action = "CHANGE_USER_ROLE_IN_GROUP",
         Data = JsonConvert.SerializeObject(new
         {
             group_id = groupUsers.GroupId,
             user_id = groupUsers.UserId,
             role_name = roleName
         }),
         Message = $"Admin change role of {groupUsers.User.UserName}" +
                   $" in group \"{groupUsers.Group.Name}\" to {roleName}",
         Time = DateTime.UtcNow,
         UserId = principal.Identity.Name
     }).Entity);
 }
示例#22
0
        private List <GroupUsers> GetCollectionGroupUsers(Guid uidReserva)
        {
            List <GroupUsers> retorno = new List <GroupUsers>();

            try {
                var collection = _iunitOfWork.InstalacionesReservasLiRepository.FindAllAsync(x => x.UID_Reserva == uidReserva).Result.OrderBy(x => x.Orden);

                foreach (var instalationLin in collection)
                {
                    if (instalationLin.UID_Person != null)
                    {
                        GroupUsers _dto = new GroupUsers();

                        if (instalationLin.UID_Recibo == null)
                        {
                            _dto.StatusBill = 0;
                        }
                        else
                        {
                            if (instalationLin.Pagado == false)
                            {
                                _dto.StatusBill = 1;
                            }
                            else
                            {
                                _dto.StatusBill = 2;
                            }
                        }
                        _dto.orden     = instalationLin.Orden;
                        _dto.uidPerson = instalationLin.UID_Person.Value;
                        _dto.unidades  = instalationLin.Unidades == null ? 0 : instalationLin.Unidades.Value;
                        _dto.nombre    = GetNombrePerson(instalationLin.UID_Person.Value);
                        retorno.Add(_dto);
                    }
                }
                return(retorno);
            }
            catch (CError e)
            {
                throw _errorManager.AddError("GetCollectionGroupUsers", "GetCollectionGroupUsers", e, MethodBase.GetCurrentMethod(), null);
            }
            catch (System.Exception ex)
            {
                throw _errorManager.AddError("Error Generico", "GetCollectionGroupUsers", ex, MethodBase.GetCurrentMethod(), null);
            }
        }
示例#23
0
        public ActionResult JoinOpenGroup(int?groupId, string ReturnUrl, string Title)
        {
            if (groupId.HasValue)
            {
                GroupUsers newUser = new GroupUsers();
                newUser.GroupId = groupId.Value;
                newUser.UserId  = User.Identity.GetUserId();
                _groupService.AcceptGroupRequest(newUser);
            }

            if (Title == "Leit")
            {
                return(RedirectToAction("Search", "User", new { prefix = ReturnUrl }));
            }
            else if (Title == "Hópar")
            {
                return(RedirectToAction("FriendsList", "User"));
            }
            return(RedirectToAction("Profile", "Group", new { groupId = groupId.Value }));
        }
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < GroupUsers.Items.Count; i++)
            {
                try
                {
                    object item = i;
                    GroupUsers.SelectedItem = item;
                    GroupUsers.ScrollIntoView(item);
                    break;
                }
                catch (Exception)
                { }
            }


            DataRowView dataRow = (DataRowView)GroupUsers.SelectedItem;

            if (dataRow == null)
            {
                return;
            }

            //int index = GroupUsers.CurrentCell.Column.DisplayIndex;

            string userNameStr = dataRow.Row.ItemArray[0].ToString();

            MessageBox.Show(userNameStr);

            if (_sqlBaseData.DeleteUserFromGroup(userNameStr, _groupNameStr))
            {
                MessageBox.Show("Пользователь " + userNameStr + " удален из группы " + _groupNameStr);
            }
            else
            {
                MessageBox.Show("Не удалось удалить пользователя " + userNameStr + " из группы " + _groupNameStr);
            }

            LoadUsersInGroup(_groupNameStr);
        }
        public ActionResult LeaveGroup(GroupUsers gu)
        {
            var        userId    = User.Identity.GetUserId();
            GroupUsers groupUser = db.GroupUsers.Where(u => u.GroupId == gu.GroupId && u.UserId == userId).FirstOrDefault();

            if (GroupAuth.IsUserOrAdminOrCreator(groupUser.GroupId, userId) && userId != groupUser.Group.UserId)
            {
                if (groupUser is null)
                {
                    return(RedirectToAction("Index"));
                }
                else
                {
                    db.GroupUsers.Remove(groupUser);
                    db.SaveChanges();
                    return(RedirectToAction("Index"));
                }
            }
            else
            {
                return(Redirect("/Groups/Show/" + gu.GroupId));
            }
        }
        public ActionResult MakeAdmin(GroupUsers gu)
        {
            var currentUserId = User.Identity.GetUserId();

            if (GroupAuth.IsCreator(gu.GroupId, currentUserId))
            {
                GroupUsers groupAdmin = db.GroupUsers.Where(u => u.GroupId == gu.GroupId && u.UserId == gu.UserId).FirstOrDefault();
                if (groupAdmin.Role.RoleName == "User")
                {
                    string author    = groupAdmin.User.Email;
                    string notifBody = "<p>Felicitari, </p>";
                    notifBody += "<p>Creatorul grupului <b>" + groupAdmin.Group.GroupName + "</b> v-a oferit dreptul de a fi admin :O</p>";
                    notifBody += "<br/> <p>Echipa <b>DAW-social-app</b>.</p>";
                    Email.SendEmailNotification(author, "Acum sunteti admin!", notifBody);

                    groupAdmin.RoleId = (from r in db.GroupRoles
                                         where r.RoleName == "Admin"
                                         select r.RoleId).FirstOrDefault();
                    db.SaveChanges();
                }
            }
            return(Redirect("/Groups/Members/" + gu.GroupId));
        }
示例#27
0
        public ActionResult PasswordCheck(JoinViewModel viewModel)
        {
            var test = _context.Groups.Where(g => (g.Password.Equals(viewModel.password) && g.Id == viewModel.groupId)).SingleOrDefault();

            if (test == null)
            {
                return(RedirectToAction("Join", "Groups", new { UserId = viewModel.userId, GroupId = viewModel.groupId, Message = "Incorrect Password! Please Try Again" }));
            }
            else
            {
                GroupUsers groupUser = new GroupUsers
                {
                    applicationUserId = viewModel.userId,
                    groupId           = viewModel.groupId
                };
                _context.GroupUsers.Add(groupUser);
                _context.SaveChanges();

                // return RedirectToAction("Group", "Groups", new { id = viewModel.groupId});
                return(RedirectToAction("Group", new RouteValueDictionary(
                                            new { controller = "Groups", action = "Group", id = viewModel.groupId })));
            }
        }
        public void AddUserToGroupRole(string role, string name)
        {
            string userId = User.Identity.GetUserId();

            var newRoleId = (from gr in db.GroupRoles
                             where gr.RoleName == role
                             select new
                             { gr.RoleId }).FirstOrDefault();

            var newGroupId = (from g in db.Groups
                              where g.UserId == userId && g.GroupName == name
                              select new
                              { g.GroupId }).FirstOrDefault();

            GroupUsers groupUser = new GroupUsers();

            groupUser.RoleId  = newRoleId.RoleId;
            groupUser.GroupId = newGroupId.GroupId;
            groupUser.UserId  = userId;

            db.GroupUsers.Add(groupUser);
            db.SaveChanges();
        }
        public ActionResult AcceptJoinReq(GroupRequests req)
        {
            if (GroupAuth.IsAdminOrCreator(req.GroupId, User.Identity.GetUserId()))
            {
                GroupRequests request = db.GroupRequests.Where(r => r.GroupId == req.GroupId && r.UserId == req.UserId).FirstOrDefault();
                if (request is null)
                {
                    return(Redirect("/Groups/JoinRequests/" + req.GroupId));
                }
                else
                {
                    string author    = request.User.Email;
                    string notifBody = "<p>Bine ai venit in grupul <b>" + request.Group.GroupName + "</b>. </p><br/>";
                    notifBody += "<p>Cererea dumneavoastra pentru a face aparte din grupul <b>" + request.Group.GroupName + "</b> a fost acceptata</p>";
                    notifBody += "<br/> <p>Echipa <b>DAW-social-app.</b></p>";
                    Email.SendEmailNotification(author, "Cerere acceptata!", notifBody);

                    GroupUsers gu = new GroupUsers();
                    gu.GroupId = request.GroupId;
                    gu.UserId  = request.UserId;
                    gu.RoleId  = (from gr in db.GroupRoles
                                  where gr.RoleName == "User"
                                  select gr.RoleId).FirstOrDefault();
                    db.GroupUsers.Add(gu);

                    db.GroupRequests.Remove(request);

                    db.SaveChanges();
                    TempData["message"] = "Cererea userului " + db.Users.Find(req.UserId).UserName + " a fost acceptata";
                    return(Redirect("/Groups/JoinRequests/" + request.GroupId));
                }
            }
            else
            {
                return(RedirectToAction("Index"));
            }
        }
示例#30
0
        /// <summary>
        /// This method parses either a CSV
        /// or a Excel(xls(x)) file into the database and is able to add
        /// new users based on the information within those files.
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        private List <string> ParseFile(KeyValuePair <int, FileInfo> item)
        {
            // Checks whether the gile is an Excel file
            if (item.Value.Extension.ToLower().Contains("xls"))
            {
                try
                {
                    //Using Excel convert and save the file as a csv
                    Microsoft.Office.Interop.Excel.Application app        = new Microsoft.Office.Interop.Excel.ApplicationClass();
                    Microsoft.Office.Interop.Excel.Workbook    wbWorkbook = app.Workbooks.Open(item.Value.FullName);
                    wbWorkbook.SaveAs(Path.Combine(_env.WebRootPath, "lib/Excel/" + item.Value.Name) + ".csv", Microsoft.Office.Interop.Excel.XlFileFormat.xlCSV);
                    wbWorkbook.Close();

                    // Save the CSV and replace the file info object.
                    item = new KeyValuePair <int, FileInfo>(item.Key, new FileInfo(Path.Combine(_env.WebRootPath, "lib/Excel/" + item.Value.Name) + ".csv"));
                }
                // Error would occur if the file was in an ureadable format or did not upload correctly.
                catch (Exception)
                {
                    // Tell the user what went wrong with this file.
                    return(new List <string>()
                    {
                        "Failed to convert workbook into CSV"
                    });
                }
            }

            // Check if the item is listed as a CSV
            if (item.Value.Extension.ToLower().Contains("csv"))
            {
                // Setup a list of possible error or information
                List <string> Information = new List <string>();

                //Open the file in steam.
                using (var stream = new StreamReader(new FileStream(item.Value.FullName, FileMode.Open)))
                {
                    int    userID = UserHelper.GetUserId(HttpContext.Session);
                    string line   = "";
                    // Read the fill until you get to the first line;
                    while (string.IsNullOrEmpty(line = stream.ReadLine()))
                    {
                    }
                    // find the positions of the headers by spliting.
                    string[] headers = line.ToLower().Split(',', StringSplitOptions.RemoveEmptyEntries);

                    // Find the positions of the headers in the list using my own extention method.
                    int uname    = headers.PositionOf("username"),
                        password = headers.PositionOf("password"),
                        fname    = headers.PositionOf("firstname"),
                        lname    = headers.PositionOf("lastname");

                    // Make sure that all the required headers exist.
                    bool error    = false;
                    var  errortxt = "Could not find column: ";
                    if (uname == -1)
                    {
                        errortxt += "username, ";
                        error     = true;
                    }
                    if (password == -1)
                    {
                        errortxt += "password, ";
                        error     = true;
                    }
                    if (fname == -1)
                    {
                        errortxt += "fname, ";
                        error     = true;
                    }
                    if (lname == -1)
                    {
                        errortxt += "lastname, ";
                        error     = true;
                    }

                    // Return if their was an error
                    if (error)
                    {
                        Information.Add(errortxt);
                        return(Information);
                    }

                    // Find the possible positions of the multiple headers.
                    var roles  = headers.PositionsOf("role");
                    var groups = headers.PositionsOf("group");
                    int i      = 1;
                    // Read each line to the end of the file.
                    while (!stream.EndOfStream)
                    {
                        // Get the new line and split it into components.
                        line = stream.ReadLine();
                        var items = line.Split(',');
                        try
                        {
                            // Try creating the user with the detials entered above.
                            string add = "";
                            var    usr = UserHelper.CreateNewUser(UserHelper.GetUserId(HttpContext.Session), items[uname], items[password], items[fname], items[lname]);
                            if (usr.Username == UserHelper.USER_ERROR)
                            {
                                // The the user that the user failed to be added.
                                Information.Add("Line: " + i + " User: "******" Failed to add user. Username probably not unique!");
                            }
                            else
                            {
                                // the user was added, tell them.
                                add = $"Added user: {items[fname]} {items[lname]}, Username: {items[uname]}";

                                // Go through each possible position of roles in this file.
                                foreach (int role in roles)
                                {
                                    try
                                    {
                                        // Check to see their is a role their
                                        if (!string.IsNullOrEmpty(items[role]))
                                        {
                                            // Try to give the user the requested role
                                            try
                                            {
                                                UserHelper.GiveRole(usr.UserID, items[role]);
                                                add += $" role: {items[role]}";
                                            }
                                            // The role was not found if this errors.
                                            catch (KeyNotFoundException)
                                            {
                                                Information.Add("Failed: Unable to find role of name: " + items[role]
                                                                + ". Please make sure the user is in one of the following roles - Teacher, Student, Admin - and that it is spelt correctly");
                                            }
                                            DatabaseConnector.PushChanges();
                                        }
                                    }
                                    catch (IndexOutOfRangeException)
                                    {
                                        // Couuld not file that role if there is an error
                                        Information.Add("Line: " + i + " User: "******" Failed to find role at position: " + role + ".");
                                    }
                                }
                                // go through all the groups that the user was requested to be added to.
                                foreach (var group in groups)
                                {
                                    // Check a group exists at that location.
                                    if (!string.IsNullOrEmpty(items[group]))
                                    {
                                        // Attempt to get the groupID of that group
                                        int GroupID = DatabaseConnector.GetGroup(items[group], OrganisationHelper.GetOrganisationID(HttpContext.Session));
                                        //If the group doesn't exist create a new one
                                        if (GroupID == -1)
                                        {
                                            // Creates the new groups which is accessible by everyone
                                            // and was created by the admin uploading the users.
                                            Groups newGroup = new Groups()
                                            {
                                                AccessType = 1,
                                                CreatedBy  = UserHelper.GetUserId(HttpContext.Session),
                                                Group_Name = items[group]
                                            };
                                            // Get the new ID of the group that the database returns
                                            newGroup.GroupID = DatabaseConnector.AddGroup(newGroup);
                                            // Push the group and user changes.
                                            DatabaseConnector.PushChanges();

                                            // Tell the user that you created a new group.
                                            Information.Add("Line: " + i + " User: "******"created new group: " + items[group] + ".");

                                            // Then add the user to the group you just created.
                                            GroupUsers usrAdd = new GroupUsers()
                                            {
                                                UserID  = usr.UserID,
                                                GroupID = newGroup.GroupID
                                            };
                                            DatabaseConnector.AddGroupUser(usrAdd);
                                        }
                                        // If the group already exists
                                        else
                                        {
                                            // Again add the user too that group
                                            GroupUsers usrAdd = new GroupUsers()
                                            {
                                                UserID  = usr.UserID,
                                                GroupID = GroupID
                                            };
                                            // add this to the database and tell the parser.
                                            DatabaseConnector.AddGroupUser(usrAdd);
                                            Information.Add("Line: " + i + " User: "******" added user to group: " + items[group] + ".");
                                        }
                                    }
                                    else
                                    {
                                        Information.Add("Line: " + i + " User: "******" group column blank: " + group + ".");
                                    }
                                }
                            }
                            Information.Add(add);
                        }
                        // Catches the eror that you cannot find the item. I.E. the person who created the CSV formatted it wrong.
                        catch (IndexOutOfRangeException)
                        {
                            Information.Add("Line: " + i + " Failed to find index of item");
                        }
                        i++;
                    }
                }
                // Return the information from the parse
                return(Information);
            }
            // Return if you were unable to read the inputted files as a CSV.
            return(new List <string>
            {
                "Could not be read as a CSV file"
            });
        }
示例#31
0
 /// <summary>
 /// Adds a user to the GroupUsers table
 /// </summary>
 /// <param name="groupUsers"></param>
 public void AcceptGroupRequest(GroupUsers groupUsers)
 {
     _dbContext.GroupUsers.Add(groupUsers);
     _dbContext.SaveChanges();
 }