protected void slkButtonDelete_Click(object sender, EventArgs e) { try { // Delete corresponding assignment folder from the drop box if exists if (AssignmentProperties.PackageFormat == null) { DropBoxManager dropBoxMgr = new DropBoxManager(AssignmentProperties); dropBoxMgr.DeleteAssignmentFolder(); } SlkStore.DeleteAssignment(AssignmentProperties.Id); Response.Redirect(SPWeb.ServerRelativeUrl, true); } catch (ThreadAbortException) { // Calling Response.Redirect throws a ThreadAbortException which will // flag an error in the next step if we don't do this. throw; } catch (Exception exception) { errorBanner.AddException(SlkStore, new SafeToDisplayException(PageCulture.Resources.LobbyDeleteException)); SlkStore.LogException(exception); } }
protected void slkButtonSubmit_Click(object sender, EventArgs e) { try { try { LearnerAssignmentProperties.Submit(); LearnerAssignmentProperties.SaveLearnerComment(LearnerComments.Text); } catch (InvalidOperationException) { // state transition isn't supported errorBanner.AddException(SlkStore, new SafeToDisplayException(PageCulture.Resources.LobbyCannotChangeState)); } // Clear the object so it will refresh from the database LearnerAssignmentProperties = null; } catch (LearningStoreConstraintViolationException exception) { // any exceptions here will be handled in PreRender errorBanner.AddException(SlkStore, new SafeToDisplayException(PageCulture.Resources.LobbySubmitException)); SlkStore.LogException(exception); } }
/// <summary>See <see cref="Microsoft.SharePoint.WebControls.UnsecuredLayoutsPageBase.OnPreInit"/>.</summary> protected override void OnPreInit(EventArgs e) { try { if (OverrideMasterPage) { if (SPWeb != null) { AnonymousSlkStore store = AnonymousSlkStore.GetStore(SPWeb.Site); if (store.Settings.UseMasterPageForApplicationPages) { MasterPageFile = SPWeb.CustomMasterUrl; } } } } catch (UserNotFoundException) { // No SPWeb.CurrentUser, so store need resetting m_slkStore = null; } catch (SafeToDisplayException) { } catch (Exception) { // Don't let an error stop the page rendering. Let the error happen during the actual rendering and be handled there. // Only issue this may cause is incorrect master page. m_slkStore = null; } base.OnPreInit(e); }
protected void Page_Load(object sender, EventArgs e) { try { SlkUtilities.RetryOnDeadlock(delegate() { m_helper = new ChangeActivityHelper(Request, Response); m_helper.ProcessPageLoad(TryGetSessionView, TryGetAttemptId, TryGetActivityId, RegisterError, GetErrorInfo, GetMessage); m_pageLoadSuccessful = (!HasError); }); } catch (Exception e2) { // Unexpected exceptions are not shown to user SlkStore.LogError(FramesetResources.FRM_UnknownExceptionMsg, e2.ToString()); RegisterError(ResHelper.GetMessage(FramesetResources.FRM_UnknownExceptionTitle), ResHelper.GetMessage(SlkFrameset.FRM_UnexpectedExceptionMsg), false); m_pageLoadSuccessful = false; // Clear the response in case something has been written Response.Clear(); } }
/// <summary> /// Sets the final points and updates the in-memory LearnerAssignmentProperties. /// </summary> /// <param name="points"></param> private void SetFinalPoints(float?points) { SlkStore.SetFinalPoints(LearnerAssignmentGuidId, points); // Force an update to the in-memory record of LearnerAssignment GetLearnerAssignment(true); }
/// <summary> /// Increments the final points in the assignment and updates the in-memory LearnerAssignmentProperties. /// </summary> /// <param name="delta"></param> private void IncrementFinalPoints(float delta) { SlkStore.IncrementFinalPoints(LearnerAssignmentGuidId, delta); // Force an update to the in-memory record of LearnerAssignment GetLearnerAssignment(true); }
/// <summary> /// This is an internal helper function. This function will bring back an SLKStore Object. /// </summary> /// <returns>SLKStore Object stamped with the currently logged user</returns> private SlkStore GetSLKStore() { try { //Getting User Object using (SPSite siteForUser = new SPSite(classesUrl)) { using (SPWeb webForUser = siteForUser.RootWeb) { //TODO: Does not handle invalid users gracefully. SPUserToken token = webForUser.AllUsers[Username].UserToken; using (SPSite site = new SPSite(classesUrl, token)) { using (SPWeb web = site.OpenWeb()) { return(SlkStore.GetStore(web)); } } } } } catch (Exception exception) { hasError = true; errorDesc = exception.Message; return(null); } }
/// <summary> /// Adds a SharePoint Web site to the SLK user web list of a given user. A user web list is /// the list of Web sites shown in E-Learning Actions pages that are displayed within a given /// site collection. /// </summary> /// /// <param name="loginName">The login name, e.g. "MyDomain\SlkLearner123". If the login name /// starts with ".\", it's assumed to be a local machine account.</param> /// /// <param name="siteCollectionUrl">The URL of the site collection containing the user web /// list to update.</param> /// /// <param name="webSiteUrl">The URL of the Web site to add to the user web list.</param> /// static void AddToUserWebList(string loginName, string siteCollectionUrl, string webSiteUrl) { Console.WriteLine("Adding \"{0}\" to the user web list of \"{1}\" in \"{2}\"", webSiteUrl, loginName, siteCollectionUrl); // "log in" to SharePoint as the user running this program using (SPSite currentUserSite = new SPSite(siteCollectionUrl)) { if (loginName.StartsWith(@".\")) { loginName = String.Format(@"{0}\{1}", currentUserSite.HostName, loginName.Substring(2)); } SPWeb rootWeb = currentUserSite.RootWeb; // set <spUser> to the user corresponding to <loginName> SPUser spUser = rootWeb.AllUsers[loginName]; // "log in" to SharePoint as the user <spUser>, and set <slkStore> to refer to that // user and the site collection specified by <siteCollectionUrl> using (SPSite destinationSite = new SPSite(webSiteUrl, spUser.UserToken)) { using (SPWeb destinationWeb = destinationSite.OpenWeb()) { SlkStore slkStore = SlkStore.GetStore(destinationWeb); slkStore.AddToUserWebList(destinationWeb); } } } }
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] // all exceptions caught and written to server event log protected void Page_Load(object sender, EventArgs e) { try { CheckPlayAssignment(); SlkUtilities.RetryOnDeadlock(delegate() { Response.Clear(); ClearError(); m_framesetHelper = new FramesetHelper(); m_framesetHelper.ProcessPageLoad(SlkStore.PackageStore, TryGetSessionView, TryGetAttemptId, ProcessViewRequest); // If this is not e-learning content, then we have to write the content directly to response. if (!HasError && !m_isELearning) { SendNonElearningContent(); Response.End(); } }); } catch (ThreadAbortException) { // response ended. Do nothing. return; } catch (FileNotFoundException) { Response.StatusCode = 404; Response.StatusDescription = "Not Found"; RegisterError(SlkFrameset.FRM_DocumentNotFoundTitleHtml, SlkFrameset.FRM_DocumentNotFound, false); } catch (UserNotFoundException) { Response.StatusCode = 500; Response.StatusDescription = "Internal Server Error"; // This probably indicates the site allows anonymous access and the user is not signed in. RegisterError(SlkFrameset.FRM_AssignmentNotAvailableTitle, SlkFrameset.FRM_SignInRequiredMsgHtml, false); } catch (HttpException ex) { // Do not set response codes SlkStore.LogException(ex); RegisterError(SlkFrameset.FRM_AssignmentNotAvailableTitle, SlkFrameset.FRM_AssignmentNotAvailableMsgHtml, false); } catch (Exception ex) { Response.StatusCode = 500; Response.StatusDescription = "Internal Server Error"; SlkStore.LogException(ex); RegisterError(SlkFrameset.FRM_AssignmentNotAvailableTitle, SlkFrameset.FRM_AssignmentNotAvailableMsgHtml, false); } }
/// <summary> /// This is an internal helper function. This function will bring back Learner assignments. /// </summary> /// <param name="slkStore">SLkStore object stamped with the identity of the currently logged user</param> private void ProcessLearnerAssignments(SlkStore slkStore) { //Declarations LearningStoreQuery _storeQueryObject; LearningStoreJob _storeJobObject; DataRowCollection _dataRowsCollectionObject; Appointments.AppointmentRow _appointmentDataRow; LearningStoreItemIdentifier _assignmentItemIdentifier; try { // Constructing the StoreQuery Object _storeQueryObject = slkStore.LearningStore.CreateQuery(LearnerAssignmentListForLearners.ViewName); _storeQueryObject.AddColumn(LearnerAssignmentListForLearners.LearnerAssignmentId); _storeQueryObject.AddColumn(LearnerAssignmentListForLearners.AssignmentTitle); _storeQueryObject.AddColumn(LearnerAssignmentListForLearners.AssignmentStartDate); _storeQueryObject.AddColumn(LearnerAssignmentListForLearners.AssignmentDueDate); _storeQueryObject.AddColumn(LearnerAssignmentListForLearners.AssignmentDescription); _storeQueryObject.AddColumn(LearnerAssignmentListForLearners.AssignmentSPWebGuid); _storeQueryObject.AddCondition(LearnerAssignmentListForLearners.AssignmentDueDate, LearningStoreConditionOperator.NotEqual, null); _storeQueryObject.AddSort(LearnerAssignmentListForLearners.AssignmentDueDate, LearningStoreSortDirection.Ascending); //_storeQueryObject.AddCondition(LearnerAssignmentListForLearners.LearnerName, LearningStoreConditionOperator.Equal, userName); //Creating the Job Object _storeJobObject = slkStore.LearningStore.CreateJob(); _storeJobObject.PerformQuery(_storeQueryObject); //Executing the Job _dataRowsCollectionObject = _storeJobObject.Execute <DataTable>().Rows; if (_dataRowsCollectionObject != null) { // Formatting the results foreach (DataRow _rowTempObject in _dataRowsCollectionObject) { //Console.WriteLine(dr[AssignmentListForInstructors.AssignmentTitle].ToString()); _appointmentDataRow = this.Appointment.NewAppointmentRow(); _appointmentDataRow.Title = (_rowTempObject[LearnerAssignmentListForLearners.AssignmentTitle] != null) ? _rowTempObject[LearnerAssignmentListForLearners.AssignmentTitle].ToString() : string.Empty; _assignmentItemIdentifier = (LearningStoreItemIdentifier)((_rowTempObject[LearnerAssignmentListForLearners.LearnerAssignmentId] != null) ? _rowTempObject[LearnerAssignmentListForLearners.LearnerAssignmentId] : string.Empty); _appointmentDataRow.ID = _assignmentItemIdentifier.GetKey().ToString(); _appointmentDataRow.BeginDate = (DateTime)((_rowTempObject[LearnerAssignmentListForLearners.AssignmentDueDate] != null) ? _rowTempObject[LearnerAssignmentListForLearners.AssignmentDueDate] : DateTime.MinValue); _appointmentDataRow.EndDate = (DateTime)((_rowTempObject[LearnerAssignmentListForLearners.AssignmentDueDate] != null) ? _rowTempObject[LearnerAssignmentListForLearners.AssignmentDueDate] : DateTime.MinValue); _appointmentDataRow.Subject = (_rowTempObject[LearnerAssignmentListForLearners.AssignmentTitle] != null) ? _rowTempObject[LearnerAssignmentListForLearners.AssignmentTitle].ToString() : string.Empty; _appointmentDataRow.Source = "ClassServerAssignment"; _appointmentDataRow.URL = "/_layouts/1033/LgUtilities/showSlkdetails.aspx?assignmentID=" + _appointmentDataRow.ID + "&UT=0" + "&classesURL=" + ClassesUrl + "&userName="******"\", @"\\"); this.Appointment.AddAppointmentRow(_appointmentDataRow); } } } catch (Exception exception) { HasError = true; ErrorDescription = "Learner Assignment Retrieval :" + exception.Message; } }
/// <summary>Process the emails for a given url.</summary> public void Process(string url) { using (SPSite site = new SPSite(url)) { using (SPWeb web = site.OpenWeb()) { SlkStore store = SlkStore.GetStore(web); Process(store); } } }
/// <summary> /// Over rides OnPreRender. /// </summary> /// <param name="e">An EventArgs that contains the event data.</param> protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); string exceptionMessage = string.Empty; try { this.SetResourceText(); AssignmentProperties assignmentProperties = SlkStore.LoadAssignmentProperties(AssignmentItemIdentifier, SlkRole.Instructor); using (SPSite site = new SPSite(assignmentProperties.SPSiteGuid, SPContext.Current.Site.Zone)) { using (SPWeb web = site.OpenWeb(assignmentProperties.SPWebGuid)) { if (!(SlkStore.IsInstructor(web))) { exceptionMessage = PageCulture.Resources.CommentedFilesNoAccessException; throw new SafeToDisplayException(exceptionMessage); } } } //Checks if all learners have completed the assignment. if (!IsPostBack) { bool isAssignmentsCompleted = true; m_assignmentProperties = SlkStore.GetGradingProperties(AssignmentItemIdentifier); ReadOnlyCollection <LearnerAssignmentProperties> learnersGradingCollection = m_assignmentProperties.Results; foreach (LearnerAssignmentProperties learnerGrading in learnersGradingCollection) { if (learnerGrading.Status != LearnerAssignmentState.Completed) { isAssignmentsCompleted = false; } } if (!isAssignmentsCompleted) { exceptionMessage = PageCulture.Resources.CommentedFilesAssignmnetsNotCompleted; throw new SafeToDisplayException(exceptionMessage); } } } catch (Exception ex) { this.contentPanel.Visible = false; this.errorBanner.Clear(); this.errorBanner.AddError(ErrorType.Error, ex.Message); } }
/// <summary> /// Loads the grading list control /// </summary> private void LoadGradingList() { try { gradingList.AssignmentProperties = AssignmentProperties; gradingList.Initialize(SlkStore.Settings); } catch (InvalidOperationException exception) { SlkStore.LogException(exception); throw new SafeToDisplayException(PageCulture.Resources.GradingInvalidAssignmentId, AssignmentId); } }
void CreateSitesDropDown() { SPWeb web = SPContext.Current.Web; SlkStore store = SlkStore.GetStore(web); webList = new UserWebList(store, web); sites = new DropDownList(); foreach (WebListItem item in webList.Items) { sites.Items.Add(new ListItem(item.Title, item.SPWebGuid.ToString())); } Controls.Add(sites); }
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); } } } }
// TODO: Needs error handling. Remove catch all exceptions and ignore as that is worse than none. /// <summary>See <see cref="Microsoft.SharePoint.WebControls.UnsecuredLayoutsPageBase.OnInit"/>.</summary> protected override void OnLoad(EventArgs e) { AssignmentProperties assignmentProperties = SlkStore.LoadAssignmentProperties(AssignmentItemIdentifier, SlkRole.Instructor); using (AssignmentDownloader downloader = new AssignmentDownloader(assignmentProperties)) { string zippedFileName = downloader.ZippedFileName; String userAgent = Request.Headers["User-Agent"]; if (userAgent.Contains("MSIE 7.0")) { zippedFileName = zippedFileName.Replace(" ", "%20"); } using (Stream iStream = new FileStream(downloader.ZippedFilePath, FileMode.Open, FileAccess.Read, FileShare.Read)) { // Buffer to read 10K bytes in chunk: byte[] buffer = new Byte[10000]; // Total bytes to read: long dataToRead = iStream.Length; Response.ContentType = "application/octet-stream"; Response.AddHeader("Content-Disposition", "attachment; filename=\"" + zippedFileName + ".zip\""); // Read the bytes. while (dataToRead > 0) { // Verify that the client is connected. if (Response.IsClientConnected) { int length = iStream.Read(buffer, 0, 10000); Response.OutputStream.Write(buffer, 0, length); Response.Flush(); dataToRead = dataToRead - length; } else { //prevent infinite loop if user disconnects dataToRead = -1; } } } Response.Close(); } }
private void HandleNonELearningAssignment() { if (LearnerAssignmentProperties.Status == LearnerAssignmentState.NotStarted) { if (AssignmentProperties.IsNoPackageAssignment) { startAssignment = true; } else { try { CopyDocumentToDropBox(); } catch (SPException) { // Sometimes fails first time try { CopyDocumentToDropBox(); } catch (SPException exception) { SlkStore.LogException(exception); } } if (assignmentFile != null && assignmentFile.IsOwaCompatible && SlkStore.Settings.DropBoxSettings.UseOfficeWebApps) { // If using office web apps need to change the status of the assignment as the begin button is just a url rather than a script // which opens the document in another application startAssignment = true; initialViewForOfficeWebApps = true; } } } else { if (AssignmentProperties.IsNoPackageAssignment == false) { FindDocumentUrl(); } } }
/// <summary> /// Performs the Query Execution and Execute /// </summary> /// <param name="queryDef"></param> /// <returns>Query Count</returns> private int ExecuteQuery(QueryDefinition queryDef) { try { // create a job for executing the queries specified by <querySetDef> LearningStoreJob job = SlkStore.LearningStore.CreateJob(); PerformQuery(queryDef, job); // execute the job DataTable queryResults = job.Execute <DataTable>(); return(queryResults != null ? queryResults.Rows.Count : -1); } catch (SqlException ex) { SlkStore.LogException(ex); return(-1); } }
/// <summary> /// Over rides OnPreRender. /// </summary> /// <param name="e">An EventArgs that contains the event data.</param> protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); if (!Page.IsPostBack) { try { this.SetResourceText(); if ( (SlkStore.IsInstructor(SPWeb) && (Status == LearnerAssignmentState.Completed || Status == LearnerAssignmentState.Final)) || SlkStore.IsLearner(SPWeb) || (SlkStore.IsObserver(SPWeb) && Status == LearnerAssignmentState.Final) ) { BuildPageContent(); } else { string exceptionMessage; if (SlkStore.IsInstructor(SPWeb)) { exceptionMessage = PageCulture.Resources.SubmittedFilesTeacherNoAccessException; } else { exceptionMessage = PageCulture.Resources.SubmittedFilesLearnerNoAccessException; } throw new SafeToDisplayException(exceptionMessage); } } catch (Exception ex) { this.contentPanel.Visible = false; this.errorBanner.Clear(); this.errorBanner.AddException(SlkStore, ex); } } }
/// <summary>Unlocks a file.</summary> /// <param name="file">The file to unlock.</param> /// <param name="currentUser">The current user id.</param> public static void UnlockFile(SPFile file, int currentUser) { try { if (file.LockedByUser != null && file.LockedByUser.ID != currentUser) { using (new AllowUnsafeUpdates(file.Web)) { file.ReleaseLock(file.LockId); } } } catch (SPException e) { SlkCulture culture = new SlkCulture(); string message = string.Format(CultureInfo.CurrentUICulture, culture.Resources.FailUnlockFile, file.Item.Url); SlkStore.GetStore(file.Web).LogException(e); throw new SafeToDisplayException(message); } }
/// <summary>Creates a self assingment.</summary> /// <returns>The ID of the learner assignment.</returns> public static Guid CreateSelfAssignment(SlkStore store, SPWeb web, SharePointFileLocation location, Nullable <int> organizationIndex) { AssignmentProperties properties = CreateNewAssignmentObject(store, web, SlkRole.Learner); properties.SetLocation(location, organizationIndex); // Have to allow unsafe updates or self assignment fails bool allowUnsafeUpdates = web.AllowUnsafeUpdates; web.AllowUnsafeUpdates = true; try { properties.Save(web, SlkRole.Learner); } finally { web.AllowUnsafeUpdates = allowUnsafeUpdates; } return(properties.Learners[0].AssignmentUserGuidId); }
bool Show() { if (showEvaluated == false) { if (AlwaysShow) { show = true; } else { SPWeb web = SPContext.Current.Web; SlkStore store = SlkStore.GetStore(web); show = store.IsInstructor(web); } showEvaluated = true; } return(show); }
void LoadAssignmentProperties() { if (SlkStore.IsInstructor(SPWeb)) { this.assignmentProperties = SlkStore.LoadAssignmentPropertiesForLearner(LearnerAssignmentGuid, SlkRole.Instructor); } else if (SlkStore.IsLearner(SPWeb)) { this.assignmentProperties = SlkStore.LoadAssignmentPropertiesForLearner(LearnerAssignmentGuid, SlkRole.Learner); } else if (SlkStore.IsObserver(SPWeb)) { this.assignmentProperties = SlkStore.LoadAssignmentPropertiesForLearner(LearnerAssignmentGuid, SlkRole.Learner); } else { this.assignmentProperties = SlkStore.LoadAssignmentPropertiesForLearner(LearnerAssignmentGuid, SlkRole.None); } learnerAssignmentProperties = assignmentProperties.Results[0]; }
/// <summary>Retrieves the data.</summary> public void GetData() { //Getting the SLKstore object SlkStore _slkStore = GetSLKStore(); // switch (assignmentMode) { case AssignmentMode.Instructor: ProcessInstructorAssignments(_slkStore); break; case AssignmentMode.Learner: ProcessLearnerAssignments(_slkStore); break; case AssignmentMode.All: ProcessAllAssignments(_slkStore); break; } }
/// <summary> /// accesses the document library at the path provided, /// loops through the learning packages /// located the library and reads the package Id from package manifest /// </summary> /// <param name="siteURL">web site url</param> /// <param name="documentLibraryName">document library name</param> /// <returns></returns> public Hashtable GetAllLearningResources(string siteURL, string documentLibraryName) { Hashtable resources = new Hashtable(); SharePointV3 sharepoint = new SharePointV3(); SPWeb documentLibWeb = sharepoint.OpenWeb(siteURL); SPDocumentLibrary docLibrary = sharepoint.GetDocumentLibrary(documentLibraryName, documentLibWeb); Microsoft.SharePointLearningKit.SlkStore store = SlkStore.GetStore(documentLibWeb); foreach (SPListItem item in docLibrary.Items) { //if this list item is a file if (item.File != null) { SharePointFileLocation fileLocation = new SharePointFileLocation(documentLibWeb, item.UniqueId, item.File.UIVersion); string location = fileLocation.ToString(); try { PackageInformation info = store.GetPackageInformation(location); XPathNavigator manifestNavigator = info.ManifestReader.CreateNavigator(); Guid packageIdentifier = ManifestParser.ParseIndexXml(manifestNavigator); if (packageIdentifier == Guid.Empty) { packageIdentifier = ManifestParser.ParseImsManifestXml(manifestNavigator); } if (packageIdentifier != Guid.Empty) { resources.Add(packageIdentifier.ToString(), location); } } catch { //not a valid learning package, do nothing } } } return(resources); }
protected void Page_Load(object sender, EventArgs e) { try { SlkUtilities.RetryOnDeadlock(delegate() { // Clear data that may need to be reset on retry Response.Clear(); ClearError(); m_tocHelper = new TocHelper(); string submitText = ""; SessionView view; if (TryGetSessionView(false, out view)) { if (view == SessionView.Execute) { submitText = SlkFrameset.TOC_SubmitAssignment; } else { submitText = SlkFrameset.TOC_SubmitGrading; } } m_tocHelper.ProcessPageLoad(Response, SlkStore.PackageStore, TryGetSessionView, TryGetAttemptId, ProcessViewRequest, RegisterError, submitText); }); } catch (Exception ex) { // Unexpected exceptions are not shown to user SlkStore.LogError(FramesetResources.FRM_UnknownExceptionMsg, ex.ToString()); RegisterError(ResHelper.GetMessage(FramesetResources.FRM_UnknownExceptionTitle), ResHelper.GetMessage(SlkFrameset.FRM_UnexpectedExceptionMsg), false); } }
/// <summary> /// Provides an option to override and update the cached data about the /// current learner assignment. /// </summary> /// <param name="forceUpdate">If false, the value is cached.</param> /// <returns></returns> protected LearnerAssignmentProperties GetLearnerAssignment(bool forceUpdate) { // If the current value has not been set, or if we have to update it, get // the information from the base class. if (learnerAssignmentProperties == null || forceUpdate) { SlkRole slkRole; if (SlkStore.IsObserver(SPWeb) && AssignmentView == AssignmentView.StudentReview) { // If the user is an observer and the AssignmentView is 'StudentReview', then // set the slkrole to 'Observer'; Otherwise get the role using GetSlkRole method slkRole = SlkRole.Observer; } else { slkRole = GetSlkRole(AssignmentView); } AssignmentProperties assignment = SlkStore.LoadAssignmentPropertiesForLearner(LearnerAssignmentGuidId, slkRole); learnerAssignmentProperties = assignment.Results[0]; } return(learnerAssignmentProperties); }
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] // all exceptions caught and written to event log rather than getting aspx error page protected void Page_Load(object sender, EventArgs e) { try { bool isPosted = false; if (String.CompareOrdinal(Request.HttpMethod, "POST") == 0) { isPosted = true; } // Get the path to the content. This may be part of the url (if we are running without // an http module) or a URL parameter (with http module). We run in both modes because // VS.NET does not parse URLs of the form: /.../Content.aspx/0/1/foo.gif correctly without // the assistance of the module. m_contentPath = GetContentPath(); SPSecurity.CatchAccessDeniedException = true; SlkUtilities.RetryOnDeadlock(delegate() { // Initialize data that may get set on a first try, but must be reset for retry Response.Clear(); ClearError(); learnerAssignment = null; m_contentHelper = new ContentHelper(Request, Response, SlkEmbeddedUIPath); m_contentHelper.ProcessPageLoad(SlkStore.PackageStore, String.IsNullOrEmpty(m_contentPath), isPosted, TryGetViewInfo, TryGetAttemptInfo, TryGetActivityInfo, GetResourcePath, AppendContentFrameDetails, UpdateRenderContext, ProcessPostedData, ProcessViewRequest, ProcessPostedDataComplete, RegisterError, GetErrorInfo, GetMessage); }); } catch (ThreadAbortException) { // response ended. Do nothing. return; } catch (UnauthorizedAccessException uae) { SlkStore.LogError(FramesetResources.FRM_UnknownExceptionMsg, uae.ToString()); RegisterError(ResHelper.GetMessage(FramesetResources.FRM_UnknownExceptionTitle), ResHelper.GetMessage(SlkFrameset.FRM_UnexpectedExceptionMsg), false); // Clear the response in case something has been written Response.Clear(); } catch (Exception e2) { // Unexpected exceptions are not shown to user SlkStore.LogError(FramesetResources.FRM_UnknownExceptionMsg, e2.ToString()); RegisterError(ResHelper.GetMessage(FramesetResources.FRM_UnknownExceptionTitle), ResHelper.GetMessage(SlkFrameset.FRM_UnexpectedExceptionMsg), false); // Clear the response in case something has been written Response.Clear(); } }
public static void RunProgram(string classWebUrl) { Stack <IDisposable> disposer = new Stack <IDisposable>(); try { // "log in" to SLK as the current user, and set <memberships> to information about // the instructors and learners in the class Web site (i.e. the SPWeb with URL // <classWebUrl>) SPSite spSite = new SPSite(classWebUrl); disposer.Push(spSite); SPWeb spWeb = spSite.OpenWeb(); disposer.Push(spWeb); SlkStore slkStore = SlkStore.GetStore(spWeb); SlkMemberships memberships = slkStore.GetMemberships(spWeb, null, null); // make sure there's at least one instructor and one learner on the class Web; these // roles are defined by the "SLK Instructor" and "SLK Learner" permissions (as defined // in the SharePoint Learning Kit configuration page in SharePoint Central // Administration) if (memberships.Instructors.Count == 0) { throw new Exception("Class Web must have at least one instructor"); } if (memberships.Learners.Count == 0) { throw new Exception("Class Web must have at least one learner"); } // arbitrarily choose the first instructor in the class as the user who will create // the assignments SlkUser primaryInstructor = memberships.Instructors[0]; // set <classWeb> to the SPWeb of the SharePoint Web site that the new assignment will // be associated with; "log into" this Web site as the instructor retrieved above SPSite classSite = new SPSite(classWebUrl, primaryInstructor.SPUser.UserToken); disposer.Push(classSite); SPWeb classWeb = classSite.OpenWeb(); disposer.Push(classWeb); // set <slkStore> to the SharePoint Learning Kit store associated with the SPSite of // <classWeb> slkStore = SlkStore.GetStore(classWeb); // set <packageLocations> to the SharePointPackageStore-format location strings // corresponding to each element of <PackageUrls>; "log into" these Web sites as the // instructor retrieved above string[] packageLocations = new string[PackageUrls.Length]; for (int packageIndex = 0; packageIndex < packageLocations.Length; packageIndex++) { // set <packageWeb> to the SPWeb of the SharePoint Web site containing the package // or document to assign string packageUrl = PackageUrls[packageIndex]; SPSite packageSite = new SPSite(packageUrl, primaryInstructor.SPUser.UserToken); disposer.Push(packageSite); SPWeb packageWeb = packageSite.OpenWeb(); disposer.Push(packageWeb); // set <spFile> to the SPFile of the package or document to assign SPFile spFile = packageWeb.GetFile(packageUrl); // set the current element of <packageLocation> to the SharePointPackageStore // format location string that uniquely identifies the current version of the // <spFile> packageLocations[packageIndex] = new SharePointFileLocation( packageWeb, spFile.UniqueId, spFile.UIVersion).ToString(); } // create a random number generator s_random = new Random(RandomNumberSeed); // set <maxNumberOfLearners> to the number of learners in the class int maxNumberOfLearners = memberships.Learners.Count; // set <learners> to an array of learners of this class; for each assignment, we'll // shuffle this array and choose a subset to be learners on the assignment SlkUser[] learners = new SlkUser[memberships.Learners.Count]; memberships.Learners.CopyTo(learners, 0); // display table header Console.WriteLine("Assign. No. of Due Not"); Console.WriteLine("ID Learners Date Started Active Completed Final"); Console.WriteLine("----------------------------------------------------------"); // create assignments as specified by the constants at the top of this source file for (int assignmentIndex = 0; assignmentIndex < NumberOfAssignments; assignmentIndex++) { // set <fraction> to be proportional to <assignmentIndex>, between 0.0 and 1.0 double fraction = (double)assignmentIndex / NumberOfAssignments; // randomly choose an e-learning package or non-e-learning document to be assigned string packageLocation = packageLocations[s_random.Next(0, PackageUrls.Length)]; // get some information about the package/document; set <isNonELearning> to true if // if it's a non-e-learning document; NOTE: this is oversimplified code -- proper // production code should handle error conditions more carefully SPFile spFile = SlkUtilities.GetSPFileFromPackageLocation(packageLocation); bool isNonELearning; SharePointFileLocation spFileLocation; SharePointFileLocation.TryParse(packageLocation, out spFileLocation); using (SharePointPackageReader spPackageReader = new SharePointPackageReader(slkStore.SharePointCacheSettings, spFileLocation)) { isNonELearning = PackageValidator.Validate(spPackageReader).HasErrors; } // set <assignmentProperties> to the default assignment properties for the package // or document being assigned; some of these properties will be overridden below LearningStoreXml packageWarnings; int?organizationIndex = (isNonELearning ? (int?)null : 0); AssignmentProperties assignmentProperties = slkStore.GetNewAssignmentDefaultProperties( classWeb, packageLocation, organizationIndex, SlkRole.Instructor, out packageWarnings); // randomly generate a title for the assignment assignmentProperties.Title = CreateRandomTitle(); // set the due date of the assignment based on <fraction>, // <OldestAssignmentDaysAgo>, and <NewestAssignmentDaysFromNow> assignmentProperties.DueDate = DateTime.Now.AddDays( (OldestAssignmentDaysAgo + NewestAssignmentDaysFromNow) * fraction - OldestAssignmentDaysAgo); // set the start date of the assignment to be a day earlier than the earliest // due date assignmentProperties.StartDate = DateTime.Today.AddDays( -OldestAssignmentDaysAgo - 1); // randomly set Points Possible if ((assignmentProperties.PointsPossible == null) && (s_random.NextDouble() > FractionOfBlankPointsPossible)) { const int divideBy = 4; const int maxValue = 100; assignmentProperties.PointsPossible = (float)Math.Round( s_random.NextDouble() * divideBy * maxValue) / maxValue; } // make all instructors of this class (i.e. all SharePoint users that have the SLK // Instructor permission) be instructors on this assignment assignmentProperties.Instructors.Clear(); foreach (SlkUser slkUser in memberships.Instructors) { assignmentProperties.Instructors.Add(slkUser); } // shuffle <learners> for (int learnerIndex = 0; learnerIndex < learners.Length; learnerIndex++) { int otherLearnerIndex = s_random.Next(0, learners.Length); SlkUser temp = learners[learnerIndex]; learners[learnerIndex] = learners[otherLearnerIndex]; learners[otherLearnerIndex] = temp; } // randomly choose a number of learners for this assignment int numberOfLearners = s_random.Next( Math.Min(maxNumberOfLearners, MinLearnersPerAssignment), maxNumberOfLearners + 1); // copy the first <numberOfLearners> learners to <assignmentProperties> assignmentProperties.Learners.Clear(); for (int learnerIndex = 0; learnerIndex < numberOfLearners; learnerIndex++) { assignmentProperties.Learners.Add(learners[learnerIndex]); } // create the assignment AssignmentItemIdentifier assignmentId = slkStore.CreateAssignment(classWeb, packageLocation, organizationIndex, SlkRole.Instructor, assignmentProperties); // set <gradingPropertiesList> to information about the learner assignments of the // new assignment; in particular, we need the learner assignment IDs AssignmentProperties basicAssignmentProperties; ReadOnlyCollection <GradingProperties> gradingPropertiesList = slkStore.GetGradingProperties(assignmentId, out basicAssignmentProperties); // adjust the status of each learner assignment of this assignment according to // the rules specified in constants at the top of this source file int[] newStatusCount = new int[(int)LearnerAssignmentState.Final + 1]; for (int learnerIndex = 0; learnerIndex < gradingPropertiesList.Count; learnerIndex++) { // set <gradingProperties> to information about this learner assignment GradingProperties gradingProperties = gradingPropertiesList[learnerIndex]; // set <newStatus> to the new status of the assignment, applying the rules // specified in constants at the top of this source file if (fraction > 1 - FractionOfAssignmentsNotStarted) { gradingProperties.Status = LearnerAssignmentState.NotStarted; } else if (fraction < FractionOfAssignmentsAllFinal) { gradingProperties.Status = LearnerAssignmentState.Final; } else { gradingProperties.Status = (LearnerAssignmentState) s_random.Next(0, (int)LearnerAssignmentState.Final + 1); } // if we're transitioning learner assignment to Final state, optionally // assign a final points value if ((gradingProperties.Status == LearnerAssignmentState.Final) && (assignmentProperties.PointsPossible != null)) { if (s_random.NextDouble() < FractionOfOverriddenFinalPoints) { const int divideBy = 4; gradingProperties.FinalPoints = (float)Math.Round( s_random.NextDouble() * divideBy * assignmentProperties.PointsPossible.Value) / divideBy; } } // update statistics newStatusCount[(int)gradingProperties.Status]++; } // save changes to the assignment string warnings = slkStore.SetGradingProperties(assignmentId, gradingPropertiesList); Debug.Assert(warnings == null, warnings); // display feedback Console.WriteLine("{0,-8}{1,-10}{2,-10:d}{3,-8}{4,-7}{5,-10}{6,-6}", assignmentId.GetKey(), assignmentProperties.Learners.Count, assignmentProperties.DueDate, newStatusCount[0], newStatusCount[1], newStatusCount[2], newStatusCount[3]); } } finally { // dispose of objects used by this method while (disposer.Count > 0) { disposer.Pop().Dispose(); } } }
void CheckAndDisplayFile() { ResourceFileName.Text = Server.HtmlEncode(SPFile.Name); DocLibLink.NavigateUrl = SPList.DefaultViewUrl; DocLibLink.Text = Server.HtmlEncode(SPList.Title); // Make sure that the package isn't checked out. //Using LoginName instead of Sid as Sid may be empty while using FBA #if SP2007 if (SPFile.CheckOutStatus != SPFile.SPCheckOutStatus.None && SPFile.CheckedOutBy.LoginName.Equals(SPWeb.CurrentUser.LoginName)) #else if (SPFile.CheckOutType != SPFile.SPCheckOutType.None && SPFile.CheckedOutByUser.LoginName.Equals(SPWeb.CurrentUser.LoginName)) #endif { // If it's checked out by the current user, show an error. throw new SafeToDisplayException(PageCulture.Resources.ActionsCheckedOutError); } // no minor versions or limited version number warnings if (!SPList.EnableVersioning || SPList.MajorVersionLimit != 0 || SPList.MajorWithMinorVersionsLimit != 0) { if (SlkStore.Settings.AutoVersionLibrariesIfUnversioned) { SlkStore.VersionLibrary((SPDocumentLibrary)SPList); Response.Redirect(Request.RawUrl, true); } else { errorBanner.AddError(ErrorType.Warning, PageCulture.Format(PageCulture.Resources.ActionsVersioningOff, Server.HtmlEncode(SPList.Title))); } } // If the current file isn't a published version, show a warning. // If the document library doesn't have minor versions, the file is NEVER SPFileLevel.Published if (SPList.EnableMinorVersions) { if (SPFile.Level == SPFileLevel.Draft) { errorBanner.AddError(ErrorType.Warning, PageCulture.Resources.ActionsDraftVersion); } } if (!IsPostBack) { // get information about the package: populate the "Organizations" row // (as applicable) in the UI, and set <title> and <description> to the text // of the title and description to display string title, description; if (NonELearning) { // non-e-learning content... // set <title> and <description> title = SPFile.Title; if (String.IsNullOrEmpty(title)) { title = Path.GetFileNameWithoutExtension(SPFile.Name); } description = string.Empty; // hide the "Organizations" row organizationRow.Visible = false; organizationRowBottomLine.Visible = false; } else { // e-learning content... // set <packageInformation> to refer to information about the package title = package.Title; description = package.Description; // populate the drop-down list of organizations; hide the entire row containing that drop-down if there's only one organization if (package.Organizations.Count <= 1) { organizationRow.Visible = false; organizationRowBottomLine.Visible = false; } else { foreach (OrganizationNodeReader nodeReader in package.Organizations) { string id = nodeReader.Id; organizationList.Items.Add(new ListItem(Server.HtmlEncode(GetDefaultTitle(nodeReader.Title, id)), id)); } ListItem defaultOrganization = organizationList.Items.FindByValue(package.DefaultOrganizationId.ToString(CultureInfo.InvariantCulture)); if (defaultOrganization != null) { defaultOrganization.Selected = true; } } } // copy <title> to the UI lblTitle.Text = Server.HtmlEncode(title); lblDescription.Text = SlkUtilities.GetCrlfHtmlEncodedText(description); } // if the package has warnings, tell the user if (package.Warnings != null) { StringBuilder sb = new StringBuilder(); sb.Append(PageCulture.Resources.ActionsWarning); sb.AppendLine("<br />"); sb.Append("<a href=\"javascript: __doPostBack('showWarnings','');\">"); if (ShowWarnings) { sb.Append(PageCulture.Resources.ActionsHideDetails); } else { sb.Append(PageCulture.Resources.ActionsShowDetails); } sb.AppendLine("</a>"); if (ShowWarnings) { sb.AppendLine("<ul style=\"margin-top:0;margin-bottom:0;margin-left:24;\">"); using (XmlReader xmlReader = package.Warnings.CreateReader()) { XPathNavigator root = new XPathDocument(xmlReader).CreateNavigator(); foreach (XPathNavigator error in root.Select("/Warnings/Warning")) { sb.Append("<li>"); sb.Append(Server.HtmlEncode(error.Value)); sb.AppendLine("</li>"); } } sb.Append("</ul>\n"); } errorBanner.AddHtmlErrorText(ErrorType.Warning, sb.ToString()); } }