/// <summary> /// Parses xml nodes with user info into CS4User objects and returns them ina collection /// </summary> /// <param name="usersElements">user xml nodes</param> /// <returns>CS4UserCollection with the data from the xml</returns> private CS4UserCollection GetUsersFromXml(XmlNodeList usersElements) { CS4UserCollection users = new CS4UserCollection(); for (int curElementIndex = 0; curElementIndex < usersElements.Count; curElementIndex++) { string userLogin = usersElements[curElementIndex].Attributes["LoginName"].InnerText; string userDomain = usersElements[curElementIndex].Attributes["LoginNameDomain"].InnerText; string userName = usersElements[curElementIndex].Attributes["UserName"].InnerText; string userEmail = usersElements[curElementIndex].Attributes["Email"].InnerText; string userRole = usersElements[curElementIndex].Attributes["Role"].InnerText; bool userTransfer = (usersElements[curElementIndex].Attributes["Transfer"].InnerText == "1" ? true : false); int userId = 0; Int32.TryParse(usersElements[curElementIndex].Attributes["Id"].InnerText, out userId); CS4User user = new CS4User( userId, userDomain, userLogin, userName, userEmail, userTransfer, IsUserInTeacherRole(userRole)); users.Add(user); } return(users); }
/// <summary> /// Adds a user to specified roles on the website /// </summary> /// <param name="SiteWeb">site to which the user will be assigned</param> /// <param name="SiteUser">user to be added. Make sure its Roles collection contains some roles otherwise the user will not be added.</param> private void AddSiteUser(CS4User siteUser) { string siteUrl = System.String.Empty; SPSite site = null; SPWeb siteWeb = null; SPUser spUser = null; foreach (CS4User.UserPermission userPermission in siteUser.UserRoles) { if (siteUrl != userPermission.WebUrl) { siteUrl = userPermission.WebUrl; site = new SPSite(siteUrl); siteWeb = site.OpenWeb(); try { spUser = siteWeb.SiteUsers[siteUser.UserLoginWithDomain]; } catch { //user has not been added to this site yet siteWeb.Users.Add(siteUser.UserLoginWithDomain, siteUser.Email, siteUser.UserName, ""); spUser = siteWeb.SiteUsers[siteUser.UserLoginWithDomain]; } } //siteWeb.Roles[userPermission.Role].AddUser(siteUser.UserLoginWithDomain, siteUser.Email, siteUser.UserName, ""); SPRoleAssignment roleAssignment = new SPRoleAssignment(spUser); SPRoleDefinition roleDefinition = siteWeb.RoleDefinitions[userPermission.Role]; roleAssignment.RoleDefinitionBindings.Add(roleDefinition); siteWeb.RoleAssignments.Add(roleAssignment); } }
public CS4User GetByUserId(int userId) { CS4User returnUser = null; foreach (CS4User user in List) { if (user.UserId == userId) { returnUser = user; break; } } return(returnUser); }
/// <summary> /// Gets the list of users from Class Server database and checks /// if users belong to Active Directory. This is necessary as /// SLK sites base their permissions and membership on AD authentication /// </summary> /// <param name="ActiveDirectoryPath">LDAP path of the Active Directory</param> /// <param name="LogFileName">file name of the log file (will be created in the working directory)</param> /// <param name="worker">BackgroundWorker object, used to report progress</param> /// <param name="e">not used</param> /// <returns>"Completed" if successful, or exception message if there was an error.</returns> public string VerifyAgainstActiveDirectory(string activeDirectoryPath, string logFileName, BackgroundWorker worker, DoWorkEventArgs e) { try { CS4Database database = new CS4Database(SiteBuilder.Default.ClassServerDBConnectionString); DataTable usersTable = null; m_totalUsers = database.GetUsersList(ref usersTable); LogFile log = new LogFile(logFileName); log.WriteToLogFile("Verifying Class Server users against Active Directory at " + activeDirectoryPath); ADHelper helper = new ADHelper(); helper.DoADBinding(activeDirectoryPath); for (int userIndex = 0; userIndex < m_totalUsers; userIndex++) { CS4User user = new CS4User(usersTable.Rows[userIndex][0].ToString(), usersTable.Rows[userIndex][1].ToString(), System.String.Empty, System.String.Empty); if (!helper.UserExistsInActiveDirectory(user.UserDomain, user.UserLogin)) { log.WriteToLogFile(user.UserLoginWithDomain + " NOT FOUND"); m_usersNotInAD++; } else { log.WriteToLogFile(user.UserLoginWithDomain + " found"); } m_usersProcessed++; worker.ReportProgress(0, "Verified " + m_usersProcessed.ToString() + " of " + m_totalUsers.ToString() + " users."); } log.FinishLogging(); string sReport = "Completed."; return(sReport); } catch (System.Exception ex) { //catching any exception here as this will be executed in a separate thread return(ex.Message); } }
/// <summary> /// Adds SharePoint group to SharePoint v3 site /// </summary> /// <param name="SiteURL">SharePoint v3 site URL</param> /// <param name="GroupName">Group to be added</param> /// <param name="GroupOwner">Group owner. If the user does not belong to site it will be added.</param> /// <param name="DefaultUser">Default group user. If the user does not belong to site it will be added.</param> /// <param name="OverwriteIfExists">If set, the group will be removed and created again, if it exists.</param> /// <param name="ResultText">The method returns log of operations performed.</param> /// <returns>true if the group is successfully added.</returns> public bool CreateUsersGroup(string siteURL, string groupName, CS4User groupOwner, CS4User defaultUser, bool overwriteIfExists, ref string resultText) { bool result = false; resultText = String.Format(TextResources.AttemptingToCreateGroup, groupName) + Environment.NewLine; SPSite site = null; SPWeb siteWeb = null; SPGroupCollection groups = null; try { site = new SPSite(siteURL); siteWeb = site.OpenWeb(); groups = siteWeb.SiteGroups; } catch (System.Exception ex) { resultText += TextResources.CantCreateGroup + ex.Message + System.Environment.NewLine; return(result); } SPUser user = null; bool createDefaultUser = false; try { user = siteWeb.SiteUsers[defaultUser.UserLoginWithDomain]; } catch { //user does not exist createDefaultUser = true; } SPMember owner = null; bool createGroupOwner = false; try { owner = siteWeb.SiteUsers[groupOwner.UserLoginWithDomain]; } catch { createGroupOwner = true; } try { if (createDefaultUser) { AddSiteUser(defaultUser); user = siteWeb.SiteUsers[defaultUser.UserLoginWithDomain]; } if (createGroupOwner) { AddSiteUser(groupOwner); owner = siteWeb.SiteUsers[groupOwner.UserLoginWithDomain]; } } catch (System.Exception ex) { resultText += TextResources.NoGroupOwnerOrDefaultUser + ex.Message + Environment.NewLine; return(result); } SPGroup group = null; bool groupExists = false; try { group = groups[groupName]; groupExists = true; resultText += TextResources.GroupExists + Environment.NewLine; } catch { //group does not exist } try { if (groupExists) { if (overwriteIfExists) { SPUserCollection groupUsers = group.Users; //emptying group users collection foreach (SPUser groupUser in groupUsers) { group.RemoveUser(groupUser); } groups.Remove(groupName); } else { result = true; return(result); } } groups.Add(groupName, owner, user, String.Empty); resultText += TextResources.GroupCreated + System.Environment.NewLine; result = true; } catch (System.Exception ex) { resultText += ex.Message; } return(result); }
/// <summary> /// Methods for supporting CollectionBase interface /// </summary> public void Add(CS4User user) { List.Add(user); }
/// <summary> /// Does the actual work of creating an SLK site with groups and users. /// </summary> /// <param name="classData">Class to be created</param> /// <param name="processingLog">Method returns log of actions performed</param> private void ProcessClass(CS4Class classData, ref string processingLog) { string log = System.String.Empty; SharePointV3 SLKweb = new SharePointV3(); CS4UserCollection classUsers = new CS4UserCollection(); CS4UserCollection groupUsers = new CS4UserCollection(); bool classAdded = false; string classURL = String.Empty; string classCreateResult = String.Empty; CS4User groupsOwner = null; log += System.Environment.NewLine + TextResources.ProcessingClass + classData.ClassName + System.Environment.NewLine; if (classData.Transfer) { classAdded = SLKweb.CreateSite( SiteBuilder.Default.SLKSchoolWeb, classData.ClassWeb, classData.ClassName, String.Empty, classData.ClassLCID, classData.Overwrite, ref classURL, ref classCreateResult); log += classCreateResult; if (classAdded) { //adding site users for (int classUserIndex = 0; classUserIndex < classData.Users.Count; classUserIndex++) { CS4User user = classData.Users.Item(classUserIndex); if (user.Transfer) { user.UserRoles = this.DefineUserRoles(user.IsTeacher, classURL); classUsers.Add(user); //if the user is teacher, set it as group owner //we only take first teacher to be groups owner as we only need one if ((groupsOwner == null) && (user.IsTeacher)) { groupsOwner = user; } } else { log += string.Format(TextResources.UserNotForTransfer, user.UserLoginWithDomain) + System.Environment.NewLine; } } string addUsersLog = String.Empty; SLKweb.AssignUsersToSite(classURL, classUsers, ref addUsersLog); log += addUsersLog; //adding groups for (int groupIndex = 0; groupIndex < classData.Groups.Count; groupIndex++) { log += string.Format(TextResources.ProcessingGroup, classData.Groups.Item(groupIndex).WebName) + System.Environment.NewLine; if (classData.Groups.Item(groupIndex).Transfer) { //processing group users groupUsers = new CS4UserCollection(); for (int groupUserIndex = 0; groupUserIndex < classData.Groups.Item(groupIndex).GroupUsers.Count; groupUserIndex++) { CS4User groupUser = classData.Groups.Item(groupIndex).GroupUsers.Item(groupUserIndex); if (groupUser.Transfer) { groupUser.UserRoles = this.DefineUserRoles(groupUser.IsTeacher, classURL); groupUsers.Add(groupUser); } else { log += string.Format(TextResources.GroupUserNotForTransfer, groupUser.UserLoginWithDomain) + System.Environment.NewLine; } } //adding group //only if we have a group owner and at least one group user if ((groupUsers.Count > 0) && (groupsOwner != null)) { //taking first user as default user bool groupAdded = false; string groupCreateResult = string.Empty; groupAdded = SLKweb.CreateUsersGroup( classURL, classData.Groups.Item(groupIndex).WebName, groupsOwner, classData.Groups.Item(groupIndex).GroupUsers.Item(0), classData.Groups.Item(groupIndex).Overwrite, ref groupCreateResult); //adding group users log += groupCreateResult; if (groupAdded) { string addGroupUsersLog = String.Empty; SLKweb.AssignUsersToGroup(classURL, classData.Groups.Item(groupIndex).WebName, groupUsers, ref addGroupUsersLog); log += addGroupUsersLog; } } else { //not transferring this group log += TextResources.GroupOwnerOrDefaultUserProblem + System.Environment.NewLine; } } else { log += TextResources.GroupNotForTransfer + System.Environment.NewLine; } } } } else { log += TextResources.ClassNotForTransfer + System.Environment.NewLine; } log += String.Format(TextResources.FinishedProcessingClass, classData.ClassName) + System.Environment.NewLine; processingLog = log; }
/// <summary> /// For the class requested gets the assignments data from Class Server 4 database /// and transfers assignments and grading points and teacher comments using SLK API /// </summary> /// <param name="classData">class information from Class Server 4 classes config file</param> /// <param name="logText">returns log of operations performed</param> /// <param name="learningPackages">information about learning packages available on SLK school site</param> private void MoveAssignments(CS4Class classData, ref string logText, Hashtable learningPackages) { SharePointV3 assignmentSite = new SharePointV3(); string assignmentSiteUrl = assignmentSite.BuildSubSiteUrl(SiteBuilder.Default.SLKSchoolWeb, classData.ClassWeb); //for the getmemberships operation to succeed the current user has to be an SLK instructor on the web site //looping through all the class users to see if any of them are instructors //and trying to open the class web with and instructor's token SPWeb assignmentWeb = null; SPWeb assignmentWebUnderCurrentUser = assignmentSite.OpenWeb(assignmentSiteUrl); SPRoleDefinition instructorsRole = assignmentWebUnderCurrentUser.RoleDefinitions[SiteBuilder.Default.SLKInstructorSharePointRole]; bool foundInstructor = false; foreach (CS4User user in classData.Users) { if ((user.IsTeacher) && (user.Transfer)) { try { SPUser spUser = assignmentWebUnderCurrentUser.SiteUsers[user.UserLoginWithDomain]; SPUserToken token = spUser.UserToken; SPSite site = new SPSite(assignmentSiteUrl, token); assignmentWeb = site.OpenWeb(); if (assignmentWeb.AllRolesForCurrentUser.Contains(instructorsRole)) { foundInstructor = true; break; } } catch { //doing nothing, will try the next instructor } } } if (!foundInstructor) { logText += TextResources.AssignmentsTransferErrorNoClassInstructors + Environment.NewLine; return; } //open the Class SLK store //note we are using SPWeb opened with an instructor's SPUserToken Microsoft.SharePointLearningKit.SlkStore slkStore = SlkStore.GetStore(assignmentWeb); //get all learners and instructors for the class SlkMemberships memberships = slkStore.GetMemberships(assignmentWeb, null, null); Dictionary <string, SlkUser> allLearners = new Dictionary <string, SlkUser>( StringComparer.OrdinalIgnoreCase); foreach (SlkUser learner in memberships.Learners) { allLearners.Add(learner.SPUser.LoginName, learner); } Dictionary <string, SlkUser> allInstructors = new Dictionary <string, SlkUser>( StringComparer.OrdinalIgnoreCase); foreach (SlkUser instructor in memberships.Instructors) { allInstructors.Add(instructor.SPUser.LoginName, instructor); } //instructors list will always be the same for all assignments //because there is no link between assignments and teachers in CS4 SlkUserCollection classInstructors = new SlkUserCollection(); foreach (CS4User user in classData.Users) { if ((user.IsTeacher) && (user.Transfer)) { SlkUser slkUser; if (allInstructors.TryGetValue(user.UserLoginWithDomain, out slkUser)) { classInstructors.Add(slkUser); } else { //instructor not found on slk site, log logText += String.Format(TextResources.InstructorNotRegisteredWithSLKSite, user.UserLoginWithDomain, assignmentSiteUrl) + Environment.NewLine; } } } //get assignments for this class from the CS4 data base CS4Database database = new CS4Database(SiteBuilder.Default.ClassServerDBConnectionString); DataTable assignmentItems; DataTable userAssignments; int numAssignments = database.GetAssignments(classData.ClassId, out assignmentItems, out userAssignments); //loop through assignments list for (int assignmentIndex = 0; assignmentIndex < numAssignments; assignmentIndex++) { try { string packageIdent = (assignmentItems.Rows[assignmentIndex]["PackageIdentifier"] != System.DBNull.Value ? assignmentItems.Rows[assignmentIndex]["PackageIdentifier"].ToString() : String.Empty); int assignmentId = (assignmentItems.Rows[assignmentIndex]["AssignmentID"] != System.DBNull.Value ? System.Convert.ToInt32(assignmentItems.Rows[assignmentIndex]["AssignmentID"]) : 0); logText += String.Format(TextResources.TransferringAssignment, assignmentId.ToString()) + Environment.NewLine; //get assignment's package identifier string packageLocation = GetPackageLocation(packageIdent, learningPackages); if (packageLocation.Length == 0) { if (packageIdent.Length == 0) { //log: not importing assignment as the package cannot be identified logText += String.Format(TextResources.CantTransferAssignmentUnknownLearningResource, assignmentId) + Environment.NewLine; } else { //log - assignment cannot be imported as the package is not imported into slk logText += String.Format(TextResources.CantTransferAssignmentNoLearningResource, assignmentId) + Environment.NewLine; } //move on to the next assignment break; } //set assignment properties AssignmentProperties properties = ReadAssignmentPropertiesFromDataRow(assignmentItems.Rows[assignmentIndex]); Hashtable gradingPoints = new Hashtable(); Hashtable gradingComments = new Hashtable(); //set instructors list foreach (SlkUser classInstructor in classInstructors) { properties.Instructors.Add(classInstructor); } //set learners list for (int userAssignmentIndex = 0; userAssignmentIndex < userAssignments.Rows.Count; userAssignmentIndex++) { DataRow assignmentRow = userAssignments.Rows[userAssignmentIndex]; int userAssignmentTableID = (assignmentRow["AssignmentID"] == System.DBNull.Value) ? 0 : System.Convert.ToInt32(assignmentRow["AssignmentID"]); int userId = (assignmentRow["StudentID"] == System.DBNull.Value) ? 0 : System.Convert.ToInt32(assignmentRow["StudentID"]); bool isAssignmentGraded = (assignmentRow["HasTeacherGraded"].ToString().ToLower() == "true" ? true : false); float points = (assignmentRow["Points"] == System.DBNull.Value) ? 0 : System.Convert.ToSingle(assignmentRow["Points"]); string instructorComments = assignmentRow["TeacherComments"].ToString(); //to minimize sql queries the UserAssignments table contains all assignments for the class //so we need to check if this row is for the assignment currently being processed if (assignmentId == userAssignmentTableID) { //find this user in list of users from classes.xml CS4User user = classData.Users.GetByUserId(userId); if (user != null) { //see if this user is for transfer in classes.xml if (user.Transfer) { //see if this user is a learner member on SLK site SlkUser slkUser; if (allLearners.TryGetValue(user.UserLoginWithDomain, out slkUser)) { properties.Learners.Add(slkUser); //save grading info for this learner to be used later if (isAssignmentGraded) { gradingPoints.Add(slkUser.UserId, points); gradingComments.Add(slkUser.UserId, instructorComments); } } else { //user not found on slk site, log logText += String.Format(TextResources.UserNotRegisteredWithSLKSite, user.UserLoginWithDomain, assignmentSiteUrl, assignmentId) + Environment.NewLine; } } else { //user assignments will not be transferred as user is marked "not for transfer" logText += String.Format(TextResources.UserNotForTransfer, user.UserLoginWithDomain) + Environment.NewLine; } } else { //user is not found in xml file, log logText += String.Format(TextResources.UserNotFoundInXMLFile, userId, assignmentSiteUrl, SiteBuilder.Default.ClassStructureXML, assignmentId) + Environment.NewLine; } } //create the assignment AssignmentItemIdentifier assignmentIdSLK = slkStore.CreateAssignment(assignmentWeb, packageLocation, 0, SlkRole.Instructor, properties); //transfer the grading results for the assignments AssignmentProperties basicAssignmentProperties; ReadOnlyCollection <GradingProperties> gradingPropertiesList = slkStore.GetGradingProperties(assignmentIdSLK, out basicAssignmentProperties); for (int learnerIndex = 0; learnerIndex < gradingPropertiesList.Count; learnerIndex++) { // set <gradingProperties> to information about this learner assignment GradingProperties gradingProperties = gradingPropertiesList[learnerIndex]; if (gradingPoints.ContainsKey(gradingProperties.LearnerId)) { //assignment has been graded, transfer grade and comment to SLK gradingProperties.Status = LearnerAssignmentState.Final; gradingProperties.FinalPoints = (float)gradingPoints[gradingProperties.LearnerId]; gradingProperties.InstructorComments = gradingComments[gradingProperties.LearnerId].ToString(); } } //this call will not save the grade, but it will set the correct state and //put the teacher's comment. logText += slkStore.SetGradingProperties(assignmentIdSLK, gradingPropertiesList) + Environment.NewLine; //calling the second time to save grades for (int learnerIndex = 0; learnerIndex < gradingPropertiesList.Count; learnerIndex++) { gradingPropertiesList[learnerIndex].Status = null; } logText += slkStore.SetGradingProperties(assignmentIdSLK, gradingPropertiesList) + Environment.NewLine; logText += String.Format(TextResources.TransferredAssignment, assignmentId.ToString(), assignmentIdSLK.GetKey().ToString()) + Environment.NewLine; } } catch (System.Exception ex) { //exception when transferring an assignment logText += TextResources.AnError + ex.Message + Environment.NewLine; } } }