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")); }
/// <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" }); }