/// <summary> /// Converts a value returned from a LearningStore query to a <c>UserItemIdentifier</c>, /// or <c>null</c> if the value is <c>DBNull</c>. /// </summary> /// /// <param name="value">A value from a <c>DataRow</c> within a <c>DataTable</c> /// returned from a LearningStore query.</param> /// /// <param name="result">Where to store the result.</param> /// public static void Cast(object value, out UserItemIdentifier result) { LearningStoreItemIdentifier id; Cast(value, out id); result = (id == null) ? null : new UserItemIdentifier(id); }
/// <summary> /// Converts a value returned from a LearningStore query to a /// <c>UserItemIdentifier</c>. Throws an exception if the value is <c>DBNull</c>. /// </summary> /// /// <param name="value">A value from a <c>DataRow</c> within a <c>DataTable</c> /// returned from a LearningStore query.</param> /// /// <param name="result">Where to store the result.</param> /// public static void CastNonNull(object value, out UserItemIdentifier result) { LearningStoreItemIdentifier id; CastNonNull(value, out id); result = new UserItemIdentifier(id); }
/// <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; UserItemIdentifier userId; 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 string userName = this.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 var job = this.LStore.CreateJob(); var uniqueValues = new Dictionary <string, object>(); uniqueValues[Schema.UserItem.Key] = this.CurrentIudicoUserKey.ToString(); var 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); }
/* * /// <summary>Initializes an instance of this class, given a <c>UserItemIdentifier</c>.</summary> * /// <remarks>When this constructor is used, the <c>SPUser</c> and <c>Name</c> properties are <c>null</c>.</remarks> * /// <param name="userId">The SharePoint Learning Kit <c>UserItemIdentifier</c> of the user.</param> * /// <param name="spUserId">The id of the SPUser.</param> * /// <param name="spSiteGuid">The site the SPUser is from.</param> * public SlkUser(UserItemIdentifier userId, int spUserId, Guid spSiteGuid) : this (userId) * { * this.spUserId = spUserId; * this.spSiteGuid = spSiteGuid; * } */ /// <summary>Initializes a new instance of <see cref="SlkUser"/>.</summary> /// <summary>Initializes an instance of <see cref="SlkUser"/>, given a <c>UserItemIdentifier</c>.</summary> /// <param name="userId">The SharePoint Learning Kit <c>UserItemIdentifier</c> of the user.</param> /// <param name="spUser">The <see cref="SPUser"/> of the user.</param> public SlkUser(UserItemIdentifier userId, SPUser spUser) : this(userId) { SPUser = spUser; if (SPUser != null) { Name = SPUser.Name; } }
internal SlkUser(UserItemIdentifier userId, string name, string key, SPUser user) : this(userId, user) { if (string.IsNullOrEmpty(Name)) { Name = name; } this.key = key; }
/// <summary> /// Returns an <c>AssignmentProperties</c> object populated with default information for /// a new assignment based on a given e-learning package or non-e-learning document. /// This method doesn't actually create the assignment -- it just returns information that /// can be used as defaults for a form that a user would fill in to create a new assignment. /// </summary> /// <remarks> /// <para> /// If <paramref name="slkRole"/> is <c>SlkRole.Learner</c>, default properties for a /// self-assigned assignment are returned. In this case, the returned /// <c>AssignmentProperties</c> will contain no users in /// <c>AssignmentProperties.Instructors</c>, and <c>AssignmentProperties.Learners</c> will /// contain only the current user. /// </para> /// <para> /// <b>Security:</b>  If <pr>slkRole</pr> is /// <a href="Microsoft.SharePointLearningKit.SlkRole.Enumeration.htm">SlkRole.Instructor</a>, /// this operation fails if the <a href="SlkApi.htm#AccessingSlkStore">current user</a> doesn't /// have SLK /// <a href="Microsoft.SharePointLearningKit.SlkSPSiteMapping.InstructorPermission.Property.htm">instructor</a> /// permissions on <pr>destinationSPWeb</pr>. Also fails if the current user doesn't have access to the /// package/file. /// </para> /// </remarks> /// <param name="store"></param> /// <param name="destinationSPWeb">The <c>SPWeb</c> that the assignment would be assigned in.</param> /// <param name="slkRole">The <c>SlkRole</c> for which information is to be retrieved. /// Use <c>SlkRole.Learner</c> to get default information for a self-assigned assignment, /// i.e. an assignment with no instructors for which the current learner is the only /// learner. Otherwise, use <c>SlkRole.Instructor</c>.</param> /// <returns></returns> public static AssignmentProperties CreateNewAssignmentObject(ISlkStore store, SPWeb destinationSPWeb, SlkRole slkRole) { // Security checks: Fails if the user isn't an instructor on the web if SlkRole=Instructor // (verified by EnsureInstructor). Fails if the user doesn't have access to the // package (verified by calling RegisterPackage or by accessing // the properties of the non-elearning file). // Check parameters if (destinationSPWeb == null) { throw new ArgumentNullException("destinationSPWeb"); } // Verify that the web is in the site if (destinationSPWeb.Site.ID != store.SPSiteGuid) { throw new InvalidOperationException(SlkCulture.GetResources().SPWebDoesNotMatchSlkSPSite); } UserItemIdentifier currentUserId = store.CurrentUserId; AssignmentProperties assignment = new AssignmentProperties(null, store); assignment.StartDate = DateTime.Today; // midnight today assignment.DueDate = null; assignment.EmailChanges = store.Settings.EmailSettings.DefaultEmailingOn; assignment.CreatedById = currentUserId; store.AddCustomProperties(assignment, destinationSPWeb); // Role checking and determine if self assigned bool isSelfAssigned; if (slkRole == SlkRole.Instructor) { store.EnsureInstructor(destinationSPWeb); isSelfAssigned = false; } else if (slkRole == SlkRole.Learner) { isSelfAssigned = true; } else { throw new ArgumentException(SlkCulture.GetResources().InvalidSlkRole, "slkRole"); } assignment.ShowAnswersToLearners = isSelfAssigned; assignment.AutoReturn = isSelfAssigned; if (isSelfAssigned) { assignment.Learners.Add(new SlkUser(currentUserId, destinationSPWeb.CurrentUser)); } else { assignment.Instructors.Add(new SlkUser(currentUserId, destinationSPWeb.CurrentUser)); } return(assignment); }
/// <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>Initializes an instance of this class, given a <c>UserItemIdentifier</c>.</summary> /// <remarks>When this constructor is used, the <c>SPUser</c> and <c>Name</c> properties are <c>null</c>.</remarks> /// <param name="userId">The SharePoint Learning Kit <c>UserItemIdentifier</c> of the user.</param> SlkUser(UserItemIdentifier userId) { if (userId == null) { throw new ArgumentNullException("userId"); } UserId = userId; }
/// <summary> /// Uses <c>RequestCurrentUserInfo</c> and checks user existance /// by calling <c>CheckCurrentUserIdentifier</c> which returns user id based /// on currently iudico-authorized user. /// </summary> /// <returns>UserItemIdentifier value which represents UserItem primary ID.</returns> protected UserItemIdentifier GetCurrentUserIdentifier() { LearningStoreJob job = LStore.CreateJob(); RequestCurrentUserInfo(job); ReadOnlyCollection <object> results = job.Execute(); UserItemIdentifier result = CheckCurrentUserIdentifier((DataTable)results[0]); return(result); }
void CheckUserIsInstructor() { UserItemIdentifier current = Assignment.Store.CurrentUserId; foreach (SlkUser instructor in Assignment.Instructors) { if (instructor.UserId == current) { return; } } throw new SafeToDisplayException(SlkCulture.GetResources().ChangeLearnerAssignmentNotInstructor); }
protected override void OnLoad(EventArgs e) { // 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()) { // skip the code below during postback since <OriginalInstructor> will have been // populated from view state already if (IsPostBack) { return; } // populate the <OriginalInstructor> drop-down list with the names and SLK user // identifiers of all users who are instructors on any assignments in the current // SharePoint site collection using (SPWeb spWeb = SPControl.GetContextWeb(HttpContext.Current)) { SlkStore slkStore = SlkStore.GetStore(spWeb); LearningStoreJob job = slkStore.LearningStore.CreateJob(); LearningStoreQuery query = slkStore.LearningStore.CreateQuery( "AllAssignmentInstructors"); query.SetParameter("SPSiteGuid", spWeb.Site.ID); query.AddColumn("InstructorName"); query.AddColumn("InstructorId"); query.AddSort("InstructorName", LearningStoreSortDirection.Ascending); job.PerformQuery(query); DataRowCollection rows = job.Execute <DataTable>().Rows; OriginalInstructor.Items.Add(String.Empty); foreach (DataRow row in rows) { ListItem listItem = new ListItem(); listItem.Text = (string)row["InstructorName"]; UserItemIdentifier originalInstructorId = new UserItemIdentifier((LearningStoreItemIdentifier)row["InstructorId"]); listItem.Value = originalInstructorId.GetKey().ToString( CultureInfo.InvariantCulture); OriginalInstructor.Items.Add(listItem); } } } }
void VerifyIsValidSelfAssigned() { // set <currentUserId> to the UserItemIdentifier of the current user; note that this // requires a round trip to the database UserItemIdentifier currentUserId = Store.CurrentUserId; // verify that <properties> specify no instructors and that the current user is the // only learner if (Instructors.Count != 0) { throw new UnauthorizedAccessException(SlkCulture.GetResources().InvalidSelfAssignment); } if ((Learners.Count != 1) || (Learners[0].UserId != currentUserId)) { throw new UnauthorizedAccessException(SlkCulture.GetResources().InvalidSelfAssignment); } }
/////////////////////////////////////////////////////////////////////////// // Public Methods // // <summary> // Initializes an instance of this class. // </summary> // // <param name="id">The value to use for the <c>Id</c> property.</param> // // <param name="name">The value to use for the <c>Name</c> property.</param> // public LStoreUserInfo(UserItemIdentifier id, string name) { m_id = id; m_name = name; }
/// <summary> /// Initializes an instance of this class. /// </summary> /// <param name="id">The value to use for the <c>Id</c> property.</param> /// <param name="name">The value to use for the <c>Name</c> property.</param> public LStoreUserInfo(UserItemIdentifier id, string name) { this.mId = id; this.mName = name; }
/// <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; }
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; } } }
/// <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); }