/// <summary> /// Reads a <c>DataTable</c>, returned by <c>Job.Execute</c>, containing /// the results requested by a previous call to /// <c>RequestCurrentUserInfo</c>. Returns an <c>LStoreUserInfo</c> /// object containing information about the user. If the user isn't /// already listed in LearningStore, a separate call to the database is /// made to add them. /// </summary> /// /// <param name="dataTable">A <c>DataTable</c> returned from /// <c>Job.Execute</c>.</param> /// protected LStoreUserInfo GetCurrentUserInfoResults(DataTable dataTable) { DataRowCollection results = dataTable.Rows; LearningStoreJob job = LStore.CreateJob(); UserItemIdentifier userId; string userName; if (results.Count == 0) { // the user isn't listed in the UserItem table -- add them... // set <userName> to the name of the user that SCORM will use #if false // the following code queries Active Directory for the full name // of the user (for example, "Karen Berg") -- this code assumes a // particular Active Directory configuration which may or may not // work in your situation string adsiPath = String.Format("WinNT://{0},user", UserIdentity.Name.Replace(@"\", "/")); using (DirectoryEntry de = new DirectoryEntry(adsiPath)) userName = (string)de.Properties["FullName"].Value; #else // the following code uses the "name" portion of the user's // "domain\name" network account name as the name of the user userName = UserName; int backslash = userName.IndexOf('\\'); if (backslash >= 0) { userName = userName.Substring(backslash + 1); } #endif // create the UserItem for this user in LearningStore; we use // AddOrUpdateItem() instead of AddItem() in case this learner // was added by another application between the check above and // the code below job = LStore.CreateJob(); Dictionary <string, object> uniqueValues = new Dictionary <string, object>(); uniqueValues[Schema.UserItem.Key] = UserKey; Dictionary <string, object> addValues = new Dictionary <string, object>(); addValues[Schema.UserItem.Name] = userName; job.AddOrUpdateItem(Schema.UserItem.ItemTypeName, uniqueValues, addValues, null, true); userId = new UserItemIdentifier(job.Execute <LearningStoreItemIdentifier>()); } else { userId = new UserItemIdentifier((LearningStoreItemIdentifier) results[0][Schema.Me.UserId]); userName = (string)results[0][Schema.Me.UserName]; } // return a LStoreUserInfo object return(new LStoreUserInfo(userId, userName)); }
/// <summary> /// Reads a <c>DataTable</c>, returned by <c>Job.Execute</c>, containing /// the results requested by a previous call to /// <c>RequestCurrentUserInfo</c>. Returns an <c>UserItemIdentifier</c> /// object containing identifier of user. If the user isn't /// already listed in LearningStore, a separate call to the database is /// made to add them. /// </summary> /// /// <param name="dataTable">A <c>DataTable</c> returned from /// <c>Job.Execute</c>.</param> /// private UserItemIdentifier CheckCurrentUserIdentifier(DataTable dataTable) { DataRowCollection results = dataTable.Rows; LearningStoreJob job = LStore.CreateJob(); UserItemIdentifier userId; string userName; if (results.Count == 0) { // the user isn't listed in the UserItem table -- add them... // set <userName> to the name of the user that SCORM will use userName = GetCurrentIudicoUser().Name; // create the UserItem for this user in LearningStore; we use // AddOrUpdateItem() instead of AddItem() in case this learner // was added by another application between the check above and // the code below job = LStore.CreateJob(); Dictionary <string, object> uniqueValues = new Dictionary <string, object>(); uniqueValues[Schema.UserItem.Key] = CurrentIudicoUserKey.ToString(); Dictionary <string, object> addValues = new Dictionary <string, object>(); addValues[Schema.UserItem.Name] = userName; job.AddOrUpdateItem(Schema.UserItem.ItemTypeName, uniqueValues, addValues, null, true); userId = new UserItemIdentifier(job.Execute <LearningStoreItemIdentifier>()); } else { userId = new UserItemIdentifier((LearningStoreItemIdentifier) results[0][Schema.Me.UserId]); } // return a UserItemIdentifier object return(userId); }
static void UpdateSlkSettings(string connectionString, Guid spSiteGuid, string settingsFileContents, string defaultSettingsFileContents) { // make sure we can access LearningStore; while we're at it, find out if there's a row // corresponding to this SPSite in the SiteSettingsItem table LearningStore learningStore = new LearningStore(connectionString, "", true); LearningStoreJob job = learningStore.CreateJob(); LearningStoreQuery query = learningStore.CreateQuery(Schema.SiteSettingsItem.ItemTypeName); query.AddColumn(Schema.SiteSettingsItem.SettingsXml); query.AddCondition(Schema.SiteSettingsItem.SiteGuid, LearningStoreConditionOperator.Equal, spSiteGuid); job.PerformQuery(query); DataRowCollection results = job.Execute <DataTable>().Rows; if (results.Count == 0) { // this SPSite isn't listed in the SiteSettingsItem table, so we need to add a row if (settingsFileContents == null) { settingsFileContents = defaultSettingsFileContents; } } else { object currentSettingsFileContents = results[0][Schema.SiteSettingsItem.SettingsXml]; if ((currentSettingsFileContents == null) || (currentSettingsFileContents is DBNull) || (((string)currentSettingsFileContents).Length == 0)) { // the SLK Settings for this SPSite are missing, so we need to add them if (settingsFileContents == null) { settingsFileContents = defaultSettingsFileContents; } } } // upload the SLK Settings file if needed if (settingsFileContents != null) { // load "SlkSettings.xsd" from a resource into <xmlSchema> XmlSchema xmlSchema; using (StringReader schemaStringReader = new StringReader(SlkCulture.GetDefaultResources().SlkSettingsSchema)) { xmlSchema = XmlSchema.Read(schemaStringReader, delegate(object sender2, ValidationEventArgs e2) { // ignore warnings (already displayed when SLK Settings file was uploaded) }); } // validate <settingsFileContents> using (StringReader stringReader = new StringReader(settingsFileContents)) { XmlReaderSettings xmlSettings = new XmlReaderSettings(); xmlSettings.Schemas.Add(xmlSchema); xmlSettings.ValidationType = ValidationType.Schema; using (XmlReader xmlReader = XmlReader.Create(stringReader, xmlSettings)) { try { SlkSettings settings = new SlkSettings(xmlReader, DateTime.MinValue); } catch (SlkSettingsException ex) { throw new SafeToDisplayException(LoadCulture(spSiteGuid).Resources.SlkSettingsFileError, ex.Message); } } } // store <settingsFileContents> in the database job = learningStore.CreateJob(); Dictionary <string, object> uniqueProperties = new Dictionary <string, object>(); uniqueProperties.Add(Schema.SiteSettingsItem.SiteGuid, spSiteGuid); Dictionary <string, object> updateProperties = new Dictionary <string, object>(); updateProperties.Add(Schema.SiteSettingsItem.SettingsXml, settingsFileContents); updateProperties.Add(Schema.SiteSettingsItem.SettingsXmlLastModified, DateTime.Now.ToUniversalTime()); job.AddOrUpdateItem(Schema.SiteSettingsItem.ItemTypeName, uniqueProperties, updateProperties); job.Execute(); } }
protected void BtnOk_Click(object sender, EventArgs e) { // the user clicked the OK button... // ensure the user is an administrator, then execute the remaining code within a // LearningStorePrivilegedScope (which grants full access to database views) if (!SPFarm.Local.CurrentUserIsAdministrator()) { throw new UnauthorizedAccessException( "Access is denied. Only adminstrators can access this page."); } using (new LearningStorePrivilegedScope()) { // if the user didn't select an "original instructor", do nothing if (OriginalInstructor.SelectedValue.Length == 0) { return; // real code would display an error message here } // if the user didn't enter any "new instructors", do nothing if (NewInstructors.Accounts.Count == 0) { return; // the <NewInstructors> control already displays a validation error } // set <originalInstructorId> to the SLK identifier of the selected "original // instructor" UserItemIdentifier originalInstructorId = new UserItemIdentifier( long.Parse(OriginalInstructor.SelectedValue, CultureInfo.InvariantCulture)); // execute the following code within the context of the current SharePoint Web site; // in fact, the operations below are actually done across the entire site *collection*, // but SlkStore.GetStore needs to be passed a Web site, so we use the current site using (SPWeb spWeb = SPControl.GetContextWeb(HttpContext.Current)) { // set <assignmentIds> to a list containing the IDs of the assignments for which // <originalInstructorId> is an instructor List <AssignmentItemIdentifier> assignmentIds = new List <AssignmentItemIdentifier>(); SlkStore slkStore = SlkStore.GetStore(spWeb); LearningStoreJob job = slkStore.LearningStore.CreateJob(); LearningStoreQuery query = slkStore.LearningStore.CreateQuery("AllAssignmentIds"); query.AddCondition("SPSiteGuid", LearningStoreConditionOperator.Equal, spWeb.Site.ID); query.AddCondition("InstructorId", LearningStoreConditionOperator.Equal, originalInstructorId); query.AddColumn("AssignmentId"); job.PerformQuery(query); DataRowCollection rows = job.Execute <DataTable>().Rows; OriginalInstructor.Items.Add(String.Empty); foreach (DataRow row in rows) { assignmentIds.Add(new AssignmentItemIdentifier( (LearningStoreItemIdentifier)row["AssignmentId"])); } // set <newInstructorIds> to a list of SLK numeric user IDs corresponding to the // users in the <NewInstructors> control List <UserItemIdentifier> newInstructorIds = new List <UserItemIdentifier>(); foreach (string loginName in NewInstructors.Accounts) { // set <spUser> to the SharePoint SPUser corresponding to <loginName> (which // was retrieved from the <NewInstructors> control>; quit with an error // message if that user isn't in "All People" for this site collection SPUser spUser; try { spUser = spWeb.AllUsers[loginName]; } catch (SPException) { NewInstructors.ErrorMessage = "User isn't in \"All People\": " + loginName; return; } // set <userKey> to the SLK "user key", which is a string used to identify a // user in the SLK database; SLK uses a user's security identifier (SID) if // they have one, or their login name if they don't (e.g. in the case of forms // authentication) string userKey = String.IsNullOrEmpty(spUser.Sid) ? spUser.LoginName : spUser.Sid; // set <userId> to the SLK UserItemIdentifier of the user <spUser> by // searching the SLK UserItem table; if the user isn't found in UserItem, // add them UserItemIdentifier userId; job = slkStore.LearningStore.CreateJob(); query = slkStore.LearningStore.CreateQuery("UserItem"); query.AddCondition("Key", LearningStoreConditionOperator.Equal, userKey); query.AddColumn("Id"); job.PerformQuery(query); rows = job.Execute <DataTable>().Rows; if (rows.Count != 0) { // found user in the SLK UserItem table userId = new UserItemIdentifier( (LearningStoreItemIdentifier)rows[0]["Id"]); } else { // user not found in SLK UserItem table -- add them; we use // LearningStoreJob.AddOrUpdateItem rather than LearningStoreJob.AddItem // to account for the rare case where the user may be added simultaneously // by another process job = slkStore.LearningStore.CreateJob(); Dictionary <string, object> findProperties = new Dictionary <string, object>(); findProperties["Key"] = userKey; Dictionary <string, object> setProperties = new Dictionary <string, object>(); setProperties["Name"] = spUser.Name; job.AddOrUpdateItem("UserItem", findProperties, setProperties, null, true); userId = new UserItemIdentifier( job.Execute <LearningStoreItemIdentifier>()); } // update <newInstructorIds> newInstructorIds.Add(userId); } // add each user in <newInstructorIds> as an instructor to each assignment in // <assignmentIds>; set <updatedAssignmentCount> to the number of assignments that // were updated (note that we don't update assignments for which the new // instructors are already instructors) Dictionary <UserItemIdentifier, bool> oldInstructors = new Dictionary <UserItemIdentifier, bool>(); int updatedAssignmentCount = 0; foreach (AssignmentItemIdentifier assignmentId in assignmentIds) { AssignmentProperties assignmentProperties = slkStore.GetAssignmentProperties(assignmentId, SlkRole.Instructor); oldInstructors.Clear(); foreach (SlkUser slkUser in assignmentProperties.Instructors) { oldInstructors[slkUser.UserId] = true; } int oldInstructorCount = oldInstructors.Count; foreach (UserItemIdentifier userId in newInstructorIds) { if (!oldInstructors.ContainsKey(userId)) { assignmentProperties.Instructors.Add(new SlkUser(userId)); } } if (assignmentProperties.Instructors.Count != oldInstructorCount) { slkStore.SetAssignmentProperties(assignmentId, assignmentProperties); updatedAssignmentCount++; } } // provide user feedback SuccessPanel.Visible = true; SuccessLabel.Text = String.Format("Found {0} assignment(s); updated {1} assignment(s).", assignmentIds.Count, updatedAssignmentCount); OriginalInstructorSection.Visible = false; NewInstructorsSection.Visible = false; ButtonSection.Visible = false; } } }